blob: 17b2316bede553f485d0871af6b701bc6a02fc0d [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000033#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000034#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000035#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000036#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000037#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000038#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000039#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000040#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000041#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000042#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000043#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000044#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000045#include "llvm/Support/Mutex.h"
46#include "llvm/Support/Program.h"
47#include "llvm/Support/Signals.h"
48#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000049#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000050
Steve Naroff50398192009-08-28 15:28:48 +000051using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000052using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000053using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000054using namespace clang::cxtu;
Steve Naroff50398192009-08-28 15:28:48 +000055
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000056CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000057 if (!TU)
58 return 0;
59 CXTranslationUnit D = new CXTranslationUnitImpl();
60 D->TUData = TU;
61 D->StringPool = createCXStringPool();
62 return D;
63}
64
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000065cxtu::CXTUOwner::~CXTUOwner() {
66 if (TU)
67 clang_disposeTranslationUnit(TU);
68}
69
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070/// \brief The result of comparing two source ranges.
71enum RangeComparisonResult {
72 /// \brief Either the ranges overlap or one of the ranges is invalid.
73 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075 /// \brief The first range ends before the second range starts.
76 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000077
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 /// \brief The first range starts after the second range ends.
79 RangeAfter
80};
81
Ted Kremenekf0e23e82010-02-17 00:41:40 +000082/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000084static RangeComparisonResult RangeCompare(SourceManager &SM,
85 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 SourceRange R2) {
87 assert(R1.isValid() && "First range is invalid?");
88 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000089 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000090 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000091 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000092 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000093 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000094 return RangeAfter;
95 return RangeOverlap;
96}
97
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098/// \brief Determine if a source location falls within, before, or after a
99/// a given source range.
100static RangeComparisonResult LocationCompare(SourceManager &SM,
101 SourceLocation L, SourceRange R) {
102 assert(R.isValid() && "First range is invalid?");
103 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000104 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000105 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000106 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
107 return RangeBefore;
108 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
109 return RangeAfter;
110 return RangeOverlap;
111}
112
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000113/// \brief Translate a Clang source range into a CIndex source range.
114///
115/// Clang internally represents ranges where the end location points to the
116/// start of the token at the end. However, for external clients it is more
117/// useful to have a CXSourceRange be a proper half-open interval. This routine
118/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000119CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000120 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000121 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000122 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000123 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000124 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000125 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000126 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000127 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000128 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000129 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000130 }
131
132 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
133 R.getBegin().getRawEncoding(),
134 EndLoc.getRawEncoding() };
135 return Result;
136}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000137
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000138//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000139// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000140//===----------------------------------------------------------------------===//
141
Steve Naroff89922f82009-08-31 00:59:03 +0000142namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000143
144class VisitorJob {
145public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000146 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000147 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000148 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 ExplicitTemplateArgsVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000150 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000151 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000152 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000153protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000154 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000155 CXCursor parent;
156 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000157 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
158 : parent(C), K(k) {
159 data[0] = d1;
160 data[1] = d2;
161 data[2] = d3;
162 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000163public:
164 Kind getKind() const { return K; }
165 const CXCursor &getParent() const { return parent; }
166 static bool classof(VisitorJob *VJ) { return true; }
167};
168
Chris Lattner5f9e2722011-07-23 10:55:15 +0000169typedef SmallVector<VisitorJob, 10> VisitorWorkList;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000170
Douglas Gregorb1373d02010-01-20 20:59:29 +0000171// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000172class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000173 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000174{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000176 CXTranslationUnit TU;
177 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000179 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000180 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000181
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182 /// \brief The declaration that serves at the parent of any statement or
183 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000184 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000186 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000187 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000188
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000189 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000190 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000191
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000192 /// \brief Whether we should visit the preprocessing record entries last,
193 /// after visiting other declarations.
194 bool VisitPreprocessorLast;
195
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000196 /// \brief When valid, a source range to which the cursor should restrict
197 /// its search.
198 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000200 // FIXME: Eventually remove. This part of a hack to support proper
201 // iteration over all Decls contained lexically within an ObjC container.
202 DeclContext::decl_iterator *DI_current;
203 DeclContext::decl_iterator DE_current;
204
Ted Kremenekd1ded662010-11-15 23:31:32 +0000205 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000206 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
207 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000208
Douglas Gregorb1373d02010-01-20 20:59:29 +0000209 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000210 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
212 /// \brief Determine whether this particular source range comes before, comes
213 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000215 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000216 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
217
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000218 class SetParentRAII {
219 CXCursor &Parent;
220 Decl *&StmtParent;
221 CXCursor OldParent;
222
223 public:
224 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
225 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
226 {
227 Parent = NewParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231
232 ~SetParentRAII() {
233 Parent = OldParent;
234 if (clang_isDeclaration(Parent.kind))
235 StmtParent = getCursorDecl(Parent);
236 }
237 };
238
Steve Naroff89922f82009-08-31 00:59:03 +0000239public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000240 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
241 CXClientData ClientData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000242 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000243 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000244 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
245 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor08e0bc12011-09-10 00:09:20 +0000246 VisitPreprocessorLast(VisitPreprocessorLast),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000247 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 {
249 Parent.kind = CXCursor_NoDeclFound;
250 Parent.data[0] = 0;
251 Parent.data[1] = 0;
252 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000253 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000254 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000255
Ted Kremenekd1ded662010-11-15 23:31:32 +0000256 ~CursorVisitor() {
257 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000258 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000259 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
260 delete *I;
261 }
262 }
263
Ted Kremeneka60ed472010-11-16 08:15:36 +0000264 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
265 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000266
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000267 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000268
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000269 bool visitPreprocessedEntitiesInRegion();
270
271 template<typename InputIterator>
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000272 bool visitPreprocessedEntities(InputIterator First, InputIterator Last);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000273
Douglas Gregorb1373d02010-01-20 20:59:29 +0000274 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000275
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000276 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000277 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000278 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000279 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000280 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000281 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000282 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000283 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
284 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000285 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000286 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000287 bool VisitClassTemplatePartialSpecializationDecl(
288 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000289 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitEnumConstantDecl(EnumConstantDecl *D);
291 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
292 bool VisitFunctionDecl(FunctionDecl *ND);
293 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000294 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000295 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000296 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000297 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000298 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000299 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
300 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
301 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
302 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000303 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000304 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
305 bool VisitObjCImplDecl(ObjCImplDecl *D);
306 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
307 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000308 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
309 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
310 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000311 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000312 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000313 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000314 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000315 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000316 bool VisitUsingDecl(UsingDecl *D);
317 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
318 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000319
Douglas Gregor01829d32010-08-31 14:41:23 +0000320 // Name visitor
321 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000322 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000323 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000324
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000325 // Template visitors
326 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000327 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000328 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
329
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000330 // Type visitors
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000331#define ABSTRACT_TYPELOC(CLASS, PARENT)
332#define TYPELOC(CLASS, PARENT) \
333 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
334#include "clang/AST/TypeLocNodes.def"
335
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000337 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000338 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
339
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000340 // Data-recursive visitor functions.
341 bool IsInRegionOfInterest(CXCursor C);
342 bool RunVisitorWorkList(VisitorWorkList &WL);
343 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000344 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000345};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000346
Ted Kremenekab188932010-01-05 19:32:54 +0000347} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000348
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000349static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000350static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
351
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000352
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000353RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000354 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000355}
356
Douglas Gregorb1373d02010-01-20 20:59:29 +0000357/// \brief Visit the given cursor and, if requested by the visitor,
358/// its children.
359///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360/// \param Cursor the cursor to visit.
361///
362/// \param CheckRegionOfInterest if true, then the caller already checked that
363/// this cursor is within the region of interest.
364///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000365/// \returns true if the visitation should be aborted, false if it
366/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000368 if (clang_isInvalid(Cursor.kind))
369 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000370
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 if (clang_isDeclaration(Cursor.kind)) {
372 Decl *D = getCursorDecl(Cursor);
373 assert(D && "Invalid declaration cursor");
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000374 // Ignore implicit declarations, unless it's an objc method because
375 // currently we should report implicit methods for properties when indexing.
376 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 return false;
378 }
379
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000380 // If we have a range of interest, and this cursor doesn't intersect with it,
381 // we're done.
382 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000383 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000384 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385 return false;
386 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 switch (Visitor(Cursor, Parent, ClientData)) {
389 case CXChildVisit_Break:
390 return true;
391
392 case CXChildVisit_Continue:
393 return false;
394
395 case CXChildVisit_Recurse:
396 return VisitChildren(Cursor);
397 }
398
Douglas Gregorfd643772010-01-25 16:45:46 +0000399 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400}
401
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000402bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000403 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000404 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000405
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000406 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000407 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000408 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000409 Entities = PPRec.getPreprocessedEntitiesInRange(MappedRange);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000410 return visitPreprocessedEntities(Entities.first, Entities.second);
411 }
412
Douglas Gregor788f5a12010-03-20 00:41:21 +0000413 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000414 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
415
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000416 if (OnlyLocalDecls)
417 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000418
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000419 return visitPreprocessedEntities(PPRec.begin(), PPRec.end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000420}
421
422template<typename InputIterator>
423bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
424 InputIterator Last) {
425 for (; First != Last; ++First) {
426 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
427 if (Visit(MakeMacroExpansionCursor(ME, TU)))
428 return true;
429
430 continue;
431 }
432
433 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
434 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
435 return true;
436
437 continue;
438 }
439
440 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
441 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
442 return true;
443
444 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000445 }
446 }
447
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000448 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000449}
450
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000452///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453/// \returns true if the visitation should be aborted, false if it
454/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000456 if (clang_isReference(Cursor.kind) &&
457 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000458 // By definition, references have no children.
459 return false;
460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461
462 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000464 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 if (clang_isDeclaration(Cursor.kind)) {
467 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000468 if (!D)
469 return false;
470
Ted Kremenek539311e2010-02-18 18:47:01 +0000471 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000473
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000474 if (clang_isStatement(Cursor.kind)) {
475 if (Stmt *S = getCursorStmt(Cursor))
476 return Visit(S);
477
478 return false;
479 }
480
481 if (clang_isExpression(Cursor.kind)) {
482 if (Expr *E = getCursorExpr(Cursor))
483 return Visit(E);
484
485 return false;
486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000487
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000489 CXTranslationUnit tu = getCursorTU(Cursor);
490 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000491
492 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
493 for (unsigned I = 0; I != 2; ++I) {
494 if (VisitOrder[I]) {
495 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
496 RegionOfInterest.isInvalid()) {
497 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
498 TLEnd = CXXUnit->top_level_end();
499 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000500 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000501 return true;
502 }
503 } else if (VisitDeclContext(
504 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000505 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000506 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000507 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000508
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000509 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000510 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
511 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000513
Douglas Gregor7b691f332010-01-20 21:13:59 +0000514 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000516
Douglas Gregorc314aa42011-03-02 19:17:03 +0000517 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
518 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
519 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
520 return Visit(BaseTSInfo->getTypeLoc());
521 }
522 }
523 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000524
525 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
526 IBOutletCollectionAttr *A =
527 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
528 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
529 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
530 A->getInterfaceLoc(), TU));
531 }
532
Douglas Gregorb1373d02010-01-20 20:59:29 +0000533 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000534 return false;
535}
536
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000537bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000538 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
539 if (Visit(TSInfo->getTypeLoc()))
540 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000541
Ted Kremenek664cffd2010-07-22 11:30:19 +0000542 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000543 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000544
545 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000546}
547
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000548llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
549 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000550 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000551 if (Range.isInvalid())
552 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000553
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000554 switch (CompareRegionOfInterest(Range)) {
555 case RangeBefore:
556 // This declaration comes before the region of interest; skip it.
557 return llvm::Optional<bool>();
558
559 case RangeAfter:
560 // This declaration comes after the region of interest; we're done.
561 return false;
562
563 case RangeOverlap:
564 // This declaration overlaps the region of interest; visit it.
565 break;
566 }
567 }
568 return true;
569}
570
571bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
572 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
573
574 // FIXME: Eventually remove. This part of a hack to support proper
575 // iteration over all Decls contained lexically within an ObjC container.
576 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
577 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
578
579 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000580 Decl *D = *I;
581 if (D->getLexicalDeclContext() != DC)
582 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000583 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000584 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
585 if (!V.hasValue())
586 continue;
587 if (!V.getValue())
588 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000589 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000590 return true;
591 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000592 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000593}
594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
596 llvm_unreachable("Translation units are visited directly by Visit()");
597 return false;
598}
599
Richard Smith162e1c12011-04-15 14:24:37 +0000600bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
601 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
602 return Visit(TSInfo->getTypeLoc());
603
604 return false;
605}
606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
608 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
609 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000610
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000611 return false;
612}
613
614bool CursorVisitor::VisitTagDecl(TagDecl *D) {
615 return VisitDeclContext(D);
616}
617
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000618bool CursorVisitor::VisitClassTemplateSpecializationDecl(
619 ClassTemplateSpecializationDecl *D) {
620 bool ShouldVisitBody = false;
621 switch (D->getSpecializationKind()) {
622 case TSK_Undeclared:
623 case TSK_ImplicitInstantiation:
624 // Nothing to visit
625 return false;
626
627 case TSK_ExplicitInstantiationDeclaration:
628 case TSK_ExplicitInstantiationDefinition:
629 break;
630
631 case TSK_ExplicitSpecialization:
632 ShouldVisitBody = true;
633 break;
634 }
635
636 // Visit the template arguments used in the specialization.
637 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
638 TypeLoc TL = SpecType->getTypeLoc();
639 if (TemplateSpecializationTypeLoc *TSTLoc
640 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
641 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
642 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
643 return true;
644 }
645 }
646
647 if (ShouldVisitBody && VisitCXXRecordDecl(D))
648 return true;
649
650 return false;
651}
652
Douglas Gregor74dbe642010-08-31 19:31:58 +0000653bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
654 ClassTemplatePartialSpecializationDecl *D) {
655 // FIXME: Visit the "outer" template parameter lists on the TagDecl
656 // before visiting these template parameters.
657 if (VisitTemplateParameters(D->getTemplateParameters()))
658 return true;
659
660 // Visit the partial specialization arguments.
661 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
662 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
663 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
664 return true;
665
666 return VisitCXXRecordDecl(D);
667}
668
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000669bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000670 // Visit the default argument.
671 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
672 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
673 if (Visit(DefArg->getTypeLoc()))
674 return true;
675
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000676 return false;
677}
678
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000679bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
680 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000681 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000682 return false;
683}
684
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000685bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
686 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
687 if (Visit(TSInfo->getTypeLoc()))
688 return true;
689
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000690 // Visit the nested-name-specifier, if present.
691 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
692 if (VisitNestedNameSpecifierLoc(QualifierLoc))
693 return true;
694
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000695 return false;
696}
697
Douglas Gregora67e03f2010-09-09 21:42:20 +0000698/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000699static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
700 CXXCtorInitializer const * const *X
701 = static_cast<CXXCtorInitializer const * const *>(Xp);
702 CXXCtorInitializer const * const *Y
703 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000704
705 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
706 return -1;
707 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
708 return 1;
709 else
710 return 0;
711}
712
Douglas Gregorb1373d02010-01-20 20:59:29 +0000713bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000714 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
715 // Visit the function declaration's syntactic components in the order
716 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000717 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000718 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
719
720 // If we have a function declared directly (without the use of a typedef),
721 // visit just the return type. Otherwise, just visit the function's type
722 // now.
723 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
724 (!FTL && Visit(TL)))
725 return true;
726
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000727 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000728 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
729 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000730 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000731
732 // Visit the declaration name.
733 if (VisitDeclarationNameInfo(ND->getNameInfo()))
734 return true;
735
736 // FIXME: Visit explicitly-specified template arguments!
737
738 // Visit the function parameters, if we have a function type.
739 if (FTL && VisitFunctionTypeLoc(*FTL, true))
740 return true;
741
742 // FIXME: Attributes?
743 }
744
Sean Hunt10620eb2011-05-06 20:44:56 +0000745 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000746 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
747 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000748 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000749 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
750 IEnd = Constructor->init_end();
751 I != IEnd; ++I) {
752 if (!(*I)->isWritten())
753 continue;
754
755 WrittenInits.push_back(*I);
756 }
757
758 // Sort the initializers in source order
759 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000760 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761
762 // Visit the initializers in source order
763 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000764 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000765 if (Init->isAnyMemberInitializer()) {
766 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000767 Init->getMemberLocation(), TU)))
768 return true;
769 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
770 if (Visit(BaseInfo->getTypeLoc()))
771 return true;
772 }
773
774 // Visit the initializer value.
775 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000776 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000777 return true;
778 }
779 }
780
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000781 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000782 return true;
783 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregorb1373d02010-01-20 20:59:29 +0000785 return false;
786}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
789 if (VisitDeclaratorDecl(D))
790 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000791
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000792 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000793 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 return false;
796}
797
798bool CursorVisitor::VisitVarDecl(VarDecl *D) {
799 if (VisitDeclaratorDecl(D))
800 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000803 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 return false;
806}
807
Douglas Gregor84b51d72010-09-01 20:16:53 +0000808bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
809 if (VisitDeclaratorDecl(D))
810 return true;
811
812 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
813 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000814 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000815
816 return false;
817}
818
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000819bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
820 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
821 // before visiting these template parameters.
822 if (VisitTemplateParameters(D->getTemplateParameters()))
823 return true;
824
825 return VisitFunctionDecl(D->getTemplatedDecl());
826}
827
Douglas Gregor39d6f072010-08-31 19:02:00 +0000828bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
829 // FIXME: Visit the "outer" template parameter lists on the TagDecl
830 // before visiting these template parameters.
831 if (VisitTemplateParameters(D->getTemplateParameters()))
832 return true;
833
834 return VisitCXXRecordDecl(D->getTemplatedDecl());
835}
836
Douglas Gregor84b51d72010-09-01 20:16:53 +0000837bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
838 if (VisitTemplateParameters(D->getTemplateParameters()))
839 return true;
840
841 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
842 VisitTemplateArgumentLoc(D->getDefaultArgument()))
843 return true;
844
845 return false;
846}
847
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000849 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
850 if (Visit(TSInfo->getTypeLoc()))
851 return true;
852
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 PEnd = ND->param_end();
855 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000856 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 return true;
858 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000859
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000861 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000862 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000863
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000864 return false;
865}
866
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000867namespace {
868 struct ContainerDeclsSort {
869 SourceManager &SM;
870 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
871 bool operator()(Decl *A, Decl *B) {
872 SourceLocation L_A = A->getLocStart();
873 SourceLocation L_B = B->getLocStart();
874 assert(L_A.isValid() && L_B.isValid());
875 return SM.isBeforeInTranslationUnit(L_A, L_B);
876 }
877 };
878}
879
Douglas Gregora59e3902010-01-21 23:27:09 +0000880bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000881 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
882 // an @implementation can lexically contain Decls that are not properly
883 // nested in the AST. When we identify such cases, we need to retrofit
884 // this nesting here.
885 if (!DI_current)
886 return VisitDeclContext(D);
887
888 // Scan the Decls that immediately come after the container
889 // in the current DeclContext. If any fall within the
890 // container's lexical region, stash them into a vector
891 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000892 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000893 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000894 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000895 if (EndLoc.isValid()) {
896 DeclContext::decl_iterator next = *DI_current;
897 while (++next != DE_current) {
898 Decl *D_next = *next;
899 if (!D_next)
900 break;
901 SourceLocation L = D_next->getLocStart();
902 if (!L.isValid())
903 break;
904 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
905 *DI_current = next;
906 DeclsInContainer.push_back(D_next);
907 continue;
908 }
909 break;
910 }
911 }
912
913 // The common case.
914 if (DeclsInContainer.empty())
915 return VisitDeclContext(D);
916
917 // Get all the Decls in the DeclContext, and sort them with the
918 // additional ones we've collected. Then visit them.
919 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
920 I!=E; ++I) {
921 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000922 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
923 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000924 continue;
925 DeclsInContainer.push_back(subDecl);
926 }
927
928 // Now sort the Decls so that they appear in lexical order.
929 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
930 ContainerDeclsSort(SM));
931
932 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000933 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000934 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000935 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000936 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
937 if (!V.hasValue())
938 continue;
939 if (!V.getValue())
940 return false;
941 if (Visit(Cursor, true))
942 return true;
943 }
944 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000945}
946
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000948 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
949 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000950 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000951
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000952 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
953 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
954 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000955 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000956 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000957
Douglas Gregora59e3902010-01-21 23:27:09 +0000958 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000959}
960
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000961bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
962 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
963 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
964 E = PID->protocol_end(); I != E; ++I, ++PL)
965 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
966 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000967
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000968 return VisitObjCContainerDecl(PID);
969}
970
Ted Kremenek23173d72010-05-18 21:09:07 +0000971bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000972 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000973 return true;
974
Ted Kremenek23173d72010-05-18 21:09:07 +0000975 // FIXME: This implements a workaround with @property declarations also being
976 // installed in the DeclContext for the @interface. Eventually this code
977 // should be removed.
978 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
979 if (!CDecl || !CDecl->IsClassExtension())
980 return false;
981
982 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
983 if (!ID)
984 return false;
985
986 IdentifierInfo *PropertyId = PD->getIdentifier();
987 ObjCPropertyDecl *prevDecl =
988 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
989
990 if (!prevDecl)
991 return false;
992
993 // Visit synthesized methods since they will be skipped when visiting
994 // the @interface.
995 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000996 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000997 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000998 return true;
999
1000 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001001 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001002 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001003 return true;
1004
1005 return false;
1006}
1007
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001009 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001010 if (D->getSuperClass() &&
1011 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001013 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001016 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1017 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1018 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001019 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001020 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021
Douglas Gregora59e3902010-01-21 23:27:09 +00001022 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001023}
1024
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001025bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1026 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001027}
1028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001030 // 'ID' could be null when dealing with invalid code.
1031 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1032 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001035 return VisitObjCImplDecl(D);
1036}
1037
1038bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1039#if 0
1040 // Issue callbacks for super class.
1041 // FIXME: No source location information!
1042 if (D->getSuperClass() &&
1043 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045 TU)))
1046 return true;
1047#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001049 return VisitObjCImplDecl(D);
1050}
1051
1052bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1053 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1054 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1055 E = D->protocol_end();
1056 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001057 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001058 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001059
1060 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001061}
1062
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001064 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1065 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001066 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001067 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001068}
1069
Douglas Gregora4ffd852010-11-17 01:03:52 +00001070bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1071 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1072 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1073
1074 return false;
1075}
1076
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001077bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1078 return VisitDeclContext(D);
1079}
1080
Douglas Gregor69319002010-08-31 23:48:11 +00001081bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001082 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001083 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1084 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001085 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001086
1087 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1088 D->getTargetNameLoc(), TU));
1089}
1090
Douglas Gregor7e242562010-09-01 19:52:22 +00001091bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001092 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001093 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1094 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001095 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001096 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001097
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001098 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1099 return true;
1100
Douglas Gregor7e242562010-09-01 19:52:22 +00001101 return VisitDeclarationNameInfo(D->getNameInfo());
1102}
1103
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001104bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001106 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1107 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001108 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001109
1110 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1111 D->getIdentLocation(), TU));
1112}
1113
Douglas Gregor7e242562010-09-01 19:52:22 +00001114bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001116 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1117 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001119 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120
Douglas Gregor7e242562010-09-01 19:52:22 +00001121 return VisitDeclarationNameInfo(D->getNameInfo());
1122}
1123
1124bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1125 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001126 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001127 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1128 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001129 return true;
1130
Douglas Gregor7e242562010-09-01 19:52:22 +00001131 return false;
1132}
1133
Douglas Gregor01829d32010-08-31 14:41:23 +00001134bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1135 switch (Name.getName().getNameKind()) {
1136 case clang::DeclarationName::Identifier:
1137 case clang::DeclarationName::CXXLiteralOperatorName:
1138 case clang::DeclarationName::CXXOperatorName:
1139 case clang::DeclarationName::CXXUsingDirective:
1140 return false;
1141
1142 case clang::DeclarationName::CXXConstructorName:
1143 case clang::DeclarationName::CXXDestructorName:
1144 case clang::DeclarationName::CXXConversionFunctionName:
1145 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1146 return Visit(TSInfo->getTypeLoc());
1147 return false;
1148
1149 case clang::DeclarationName::ObjCZeroArgSelector:
1150 case clang::DeclarationName::ObjCOneArgSelector:
1151 case clang::DeclarationName::ObjCMultiArgSelector:
1152 // FIXME: Per-identifier location info?
1153 return false;
1154 }
1155
1156 return false;
1157}
1158
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001159bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1160 SourceRange Range) {
1161 // FIXME: This whole routine is a hack to work around the lack of proper
1162 // source information in nested-name-specifiers (PR5791). Since we do have
1163 // a beginning source location, we can visit the first component of the
1164 // nested-name-specifier, if it's a single-token component.
1165 if (!NNS)
1166 return false;
1167
1168 // Get the first component in the nested-name-specifier.
1169 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1170 NNS = Prefix;
1171
1172 switch (NNS->getKind()) {
1173 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001174 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1175 TU));
1176
Douglas Gregor14aba762011-02-24 02:36:08 +00001177 case NestedNameSpecifier::NamespaceAlias:
1178 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1179 Range.getBegin(), TU));
1180
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001181 case NestedNameSpecifier::TypeSpec: {
1182 // If the type has a form where we know that the beginning of the source
1183 // range matches up with a reference cursor. Visit the appropriate reference
1184 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001185 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001186 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1187 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1188 if (const TagType *Tag = dyn_cast<TagType>(T))
1189 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1190 if (const TemplateSpecializationType *TST
1191 = dyn_cast<TemplateSpecializationType>(T))
1192 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1193 break;
1194 }
1195
1196 case NestedNameSpecifier::TypeSpecWithTemplate:
1197 case NestedNameSpecifier::Global:
1198 case NestedNameSpecifier::Identifier:
1199 break;
1200 }
1201
1202 return false;
1203}
1204
Douglas Gregordc355712011-02-25 00:36:19 +00001205bool
1206CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001207 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001208 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1209 Qualifiers.push_back(Qualifier);
1210
1211 while (!Qualifiers.empty()) {
1212 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1213 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1214 switch (NNS->getKind()) {
1215 case NestedNameSpecifier::Namespace:
1216 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
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::NamespaceAlias:
1224 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001225 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001226 TU)))
1227 return true;
1228
1229 break;
1230
1231 case NestedNameSpecifier::TypeSpec:
1232 case NestedNameSpecifier::TypeSpecWithTemplate:
1233 if (Visit(Q.getTypeLoc()))
1234 return true;
1235
1236 break;
1237
1238 case NestedNameSpecifier::Global:
1239 case NestedNameSpecifier::Identifier:
1240 break;
1241 }
1242 }
1243
1244 return false;
1245}
1246
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001247bool CursorVisitor::VisitTemplateParameters(
1248 const TemplateParameterList *Params) {
1249 if (!Params)
1250 return false;
1251
1252 for (TemplateParameterList::const_iterator P = Params->begin(),
1253 PEnd = Params->end();
1254 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001255 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001256 return true;
1257 }
1258
1259 return false;
1260}
1261
Douglas Gregor0b36e612010-08-31 20:37:03 +00001262bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1263 switch (Name.getKind()) {
1264 case TemplateName::Template:
1265 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1266
1267 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001268 // Visit the overloaded template set.
1269 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1270 return true;
1271
Douglas Gregor0b36e612010-08-31 20:37:03 +00001272 return false;
1273
1274 case TemplateName::DependentTemplate:
1275 // FIXME: Visit nested-name-specifier.
1276 return false;
1277
1278 case TemplateName::QualifiedTemplate:
1279 // FIXME: Visit nested-name-specifier.
1280 return Visit(MakeCursorTemplateRef(
1281 Name.getAsQualifiedTemplateName()->getDecl(),
1282 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001283
1284 case TemplateName::SubstTemplateTemplateParm:
1285 return Visit(MakeCursorTemplateRef(
1286 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1287 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001288
1289 case TemplateName::SubstTemplateTemplateParmPack:
1290 return Visit(MakeCursorTemplateRef(
1291 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1292 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001293 }
1294
1295 return false;
1296}
1297
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1299 switch (TAL.getArgument().getKind()) {
1300 case TemplateArgument::Null:
1301 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001302 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001303 return false;
1304
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001305 case TemplateArgument::Type:
1306 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1307 return Visit(TSInfo->getTypeLoc());
1308 return false;
1309
1310 case TemplateArgument::Declaration:
1311 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001312 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001313 return false;
1314
1315 case TemplateArgument::Expression:
1316 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001317 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001318 return false;
1319
1320 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001321 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001322 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1323 return true;
1324
Douglas Gregora7fc9012011-01-05 18:58:31 +00001325 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001326 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001327 }
1328
1329 return false;
1330}
1331
Ted Kremeneka0536d82010-05-07 01:04:29 +00001332bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1333 return VisitDeclContext(D);
1334}
1335
Douglas Gregor01829d32010-08-31 14:41:23 +00001336bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1337 return Visit(TL.getUnqualifiedLoc());
1338}
1339
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001341 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001342
1343 // Some builtin types (such as Objective-C's "id", "sel", and
1344 // "Class") have associated declarations. Create cursors for those.
1345 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001346 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001347
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001348 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001349 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001350 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001351#define BUILTIN_TYPE(Id, SingletonId)
1352#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1353#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1354#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1355#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1356#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001357 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001358
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001359 case BuiltinType::ObjCId:
1360 VisitType = Context.getObjCIdType();
1361 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001362
1363 case BuiltinType::ObjCClass:
1364 VisitType = Context.getObjCClassType();
1365 break;
1366
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367 case BuiltinType::ObjCSel:
1368 VisitType = Context.getObjCSelType();
1369 break;
1370 }
1371
1372 if (!VisitType.isNull()) {
1373 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001374 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375 TU));
1376 }
1377
1378 return false;
1379}
1380
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001381bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001382 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001383}
1384
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1386 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1387}
1388
1389bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001390 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001391 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001392
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1394}
1395
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001396bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001397 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001398}
1399
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001400bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1401 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1402 return true;
1403
John McCallc12c5bb2010-05-15 11:32:37 +00001404 return false;
1405}
1406
1407bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1408 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1409 return true;
1410
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001411 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1412 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1413 TU)))
1414 return true;
1415 }
1416
1417 return false;
1418}
1419
1420bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001421 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001422}
1423
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001424bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1425 return Visit(TL.getInnerLoc());
1426}
1427
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001428bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1429 return Visit(TL.getPointeeLoc());
1430}
1431
1432bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1433 return Visit(TL.getPointeeLoc());
1434}
1435
1436bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1437 return Visit(TL.getPointeeLoc());
1438}
1439
1440bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001441 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001442}
1443
1444bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001445 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001446}
1447
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001448bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1449 return Visit(TL.getModifiedLoc());
1450}
1451
Douglas Gregor01829d32010-08-31 14:41:23 +00001452bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1453 bool SkipResultType) {
1454 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455 return true;
1456
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001457 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001458 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001459 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001460 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001461
1462 return false;
1463}
1464
1465bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1466 if (Visit(TL.getElementLoc()))
1467 return true;
1468
1469 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001470 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001471
1472 return false;
1473}
1474
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001475bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1476 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001477 // Visit the template name.
1478 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1479 TL.getTemplateNameLoc()))
1480 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001481
1482 // Visit the template arguments.
1483 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1484 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1485 return true;
1486
1487 return false;
1488}
1489
Douglas Gregor2332c112010-01-21 20:48:56 +00001490bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1491 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1492}
1493
1494bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1495 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1496 return Visit(TSInfo->getTypeLoc());
1497
1498 return false;
1499}
1500
Sean Huntca63c202011-05-24 22:41:36 +00001501bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1502 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1503 return Visit(TSInfo->getTypeLoc());
1504
1505 return false;
1506}
1507
Douglas Gregor2494dd02011-03-01 01:34:45 +00001508bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1509 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1510 return true;
1511
1512 return false;
1513}
1514
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001515bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1516 DependentTemplateSpecializationTypeLoc TL) {
1517 // Visit the nested-name-specifier, if there is one.
1518 if (TL.getQualifierLoc() &&
1519 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1520 return true;
1521
1522 // Visit the template arguments.
1523 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1524 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1525 return true;
1526
1527 return false;
1528}
1529
Douglas Gregor9e876872011-03-01 18:12:44 +00001530bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1531 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1532 return true;
1533
1534 return Visit(TL.getNamedTypeLoc());
1535}
1536
Douglas Gregor7536dd52010-12-20 02:24:11 +00001537bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1538 return Visit(TL.getPatternLoc());
1539}
1540
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001541bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1542 if (Expr *E = TL.getUnderlyingExpr())
1543 return Visit(MakeCXCursor(E, StmtParent, TU));
1544
1545 return false;
1546}
1547
1548bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1549 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1550}
1551
Eli Friedmanb001de72011-10-06 23:00:33 +00001552bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1553 return Visit(TL.getValueLoc());
1554}
1555
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001556#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1557bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1558 return Visit##PARENT##Loc(TL); \
1559}
1560
1561DEFAULT_TYPELOC_IMPL(Complex, Type)
1562DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1563DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1564DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1565DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1566DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1567DEFAULT_TYPELOC_IMPL(Vector, Type)
1568DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1569DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1570DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1571DEFAULT_TYPELOC_IMPL(Record, TagType)
1572DEFAULT_TYPELOC_IMPL(Enum, TagType)
1573DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1574DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1575DEFAULT_TYPELOC_IMPL(Auto, Type)
1576
Ted Kremenek3064ef92010-08-27 21:34:58 +00001577bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001578 // Visit the nested-name-specifier, if present.
1579 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1580 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1581 return true;
1582
John McCall5e1cdac2011-10-07 06:10:15 +00001583 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001584 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1585 E = D->bases_end(); I != E; ++I) {
1586 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1587 return true;
1588 }
1589 }
1590
1591 return VisitTagDecl(D);
1592}
1593
Ted Kremenek09dfa372010-02-18 05:46:33 +00001594bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001595 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1596 i != e; ++i)
1597 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001598 return true;
1599
1600 return false;
1601}
1602
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001603//===----------------------------------------------------------------------===//
1604// Data-recursive visitor methods.
1605//===----------------------------------------------------------------------===//
1606
Ted Kremenek28a71942010-11-13 00:36:47 +00001607namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001608#define DEF_JOB(NAME, DATA, KIND)\
1609class NAME : public VisitorJob {\
1610public:\
1611 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1612 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001613 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001614};
1615
1616DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1617DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001618DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001619DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001620DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001621 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001622DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001623#undef DEF_JOB
1624
1625class DeclVisit : public VisitorJob {
1626public:
1627 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1628 VisitorJob(parent, VisitorJob::DeclVisitKind,
1629 d, isFirst ? (void*) 1 : (void*) 0) {}
1630 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001631 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001632 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001633 Decl *get() const { return static_cast<Decl*>(data[0]); }
1634 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001635};
Ted Kremenek035dc412010-11-13 00:36:50 +00001636class TypeLocVisit : public VisitorJob {
1637public:
1638 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1639 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1640 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1641
1642 static bool classof(const VisitorJob *VJ) {
1643 return VJ->getKind() == TypeLocVisitKind;
1644 }
1645
Ted Kremenek82f3c502010-11-15 22:23:26 +00001646 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001647 QualType T = QualType::getFromOpaquePtr(data[0]);
1648 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001649 }
1650};
1651
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001652class LabelRefVisit : public VisitorJob {
1653public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001654 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1655 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001656 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001657
1658 static bool classof(const VisitorJob *VJ) {
1659 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1660 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001661 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001662 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001663 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001664};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001665
1666class NestedNameSpecifierLocVisit : public VisitorJob {
1667public:
1668 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1669 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1670 Qualifier.getNestedNameSpecifier(),
1671 Qualifier.getOpaqueData()) { }
1672
1673 static bool classof(const VisitorJob *VJ) {
1674 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1675 }
1676
1677 NestedNameSpecifierLoc get() const {
1678 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1679 data[1]);
1680 }
1681};
1682
Ted Kremenekf64d8032010-11-18 00:02:32 +00001683class DeclarationNameInfoVisit : public VisitorJob {
1684public:
1685 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1686 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1687 static bool classof(const VisitorJob *VJ) {
1688 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1689 }
1690 DeclarationNameInfo get() const {
1691 Stmt *S = static_cast<Stmt*>(data[0]);
1692 switch (S->getStmtClass()) {
1693 default:
1694 llvm_unreachable("Unhandled Stmt");
1695 case Stmt::CXXDependentScopeMemberExprClass:
1696 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1697 case Stmt::DependentScopeDeclRefExprClass:
1698 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1699 }
1700 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001701};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001702class MemberRefVisit : public VisitorJob {
1703public:
1704 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1705 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001706 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001707 static bool classof(const VisitorJob *VJ) {
1708 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1709 }
1710 FieldDecl *get() const {
1711 return static_cast<FieldDecl*>(data[0]);
1712 }
1713 SourceLocation getLoc() const {
1714 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1715 }
1716};
Ted Kremenek28a71942010-11-13 00:36:47 +00001717class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1718 VisitorWorkList &WL;
1719 CXCursor Parent;
1720public:
1721 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1722 : WL(wl), Parent(parent) {}
1723
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001724 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001725 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001726 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001727 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001728 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001729 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001730 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001731 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001732 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001733 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001734 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001735 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001736 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001737 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001738 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001739 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001740 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001741 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001742 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1743 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001744 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001745 void VisitIfStmt(IfStmt *If);
1746 void VisitInitListExpr(InitListExpr *IE);
1747 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001748 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001749 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001750 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1751 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001752 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001753 void VisitStmt(Stmt *S);
1754 void VisitSwitchStmt(SwitchStmt *S);
1755 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001756 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001757 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001758 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001759 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001760 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001761 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001762 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001763
Ted Kremenek28a71942010-11-13 00:36:47 +00001764private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001765 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001766 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001767 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001768 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001769 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001770 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001771 void AddTypeLoc(TypeSourceInfo *TI);
1772 void EnqueueChildren(Stmt *S);
1773};
1774} // end anonyous namespace
1775
Ted Kremenekf64d8032010-11-18 00:02:32 +00001776void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1777 // 'S' should always be non-null, since it comes from the
1778 // statement we are visiting.
1779 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1780}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001781
1782void
1783EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1784 if (Qualifier)
1785 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1786}
1787
Ted Kremenek28a71942010-11-13 00:36:47 +00001788void EnqueueVisitor::AddStmt(Stmt *S) {
1789 if (S)
1790 WL.push_back(StmtVisit(S, Parent));
1791}
Ted Kremenek035dc412010-11-13 00:36:50 +00001792void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001793 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001794 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001795}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001796void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001797 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001798 if (A)
1799 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001800 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001801}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001802void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1803 if (D)
1804 WL.push_back(MemberRefVisit(D, L, Parent));
1805}
Ted Kremenek28a71942010-11-13 00:36:47 +00001806void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1807 if (TI)
1808 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1809 }
1810void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001811 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001812 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001813 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001814 }
1815 if (size == WL.size())
1816 return;
1817 // Now reverse the entries we just added. This will match the DFS
1818 // ordering performed by the worklist.
1819 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1820 std::reverse(I, E);
1821}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001822void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1823 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1824}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001825void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1826 AddDecl(B->getBlockDecl());
1827}
Ted Kremenek28a71942010-11-13 00:36:47 +00001828void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1829 EnqueueChildren(E);
1830 AddTypeLoc(E->getTypeSourceInfo());
1831}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001832void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1833 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1834 E = S->body_rend(); I != E; ++I) {
1835 AddStmt(*I);
1836 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001837}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001838void EnqueueVisitor::
1839VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1840 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1841 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001842 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1843 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001844 if (!E->isImplicitAccess())
1845 AddStmt(E->getBase());
1846}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001847void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1848 // Enqueue the initializer or constructor arguments.
1849 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1850 AddStmt(E->getConstructorArg(I-1));
1851 // Enqueue the array size, if any.
1852 AddStmt(E->getArraySize());
1853 // Enqueue the allocated type.
1854 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1855 // Enqueue the placement arguments.
1856 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1857 AddStmt(E->getPlacementArg(I-1));
1858}
Ted Kremenek28a71942010-11-13 00:36:47 +00001859void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001860 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1861 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001862 AddStmt(CE->getCallee());
1863 AddStmt(CE->getArg(0));
1864}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001865void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1866 // Visit the name of the type being destroyed.
1867 AddTypeLoc(E->getDestroyedTypeInfo());
1868 // Visit the scope type that looks disturbingly like the nested-name-specifier
1869 // but isn't.
1870 AddTypeLoc(E->getScopeTypeInfo());
1871 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001872 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1873 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001874 // Visit base expression.
1875 AddStmt(E->getBase());
1876}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001877void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1878 AddTypeLoc(E->getTypeSourceInfo());
1879}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001880void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1881 EnqueueChildren(E);
1882 AddTypeLoc(E->getTypeSourceInfo());
1883}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001884void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1885 EnqueueChildren(E);
1886 if (E->isTypeOperand())
1887 AddTypeLoc(E->getTypeOperandSourceInfo());
1888}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001889
1890void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1891 *E) {
1892 EnqueueChildren(E);
1893 AddTypeLoc(E->getTypeSourceInfo());
1894}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001895void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1896 EnqueueChildren(E);
1897 if (E->isTypeOperand())
1898 AddTypeLoc(E->getTypeOperandSourceInfo());
1899}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001900void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001901 if (DR->hasExplicitTemplateArgs()) {
1902 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1903 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001904 WL.push_back(DeclRefExprParts(DR, Parent));
1905}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001906void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1907 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1908 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001909 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001910}
Ted Kremenek035dc412010-11-13 00:36:50 +00001911void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1912 unsigned size = WL.size();
1913 bool isFirst = true;
1914 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1915 D != DEnd; ++D) {
1916 AddDecl(*D, isFirst);
1917 isFirst = false;
1918 }
1919 if (size == WL.size())
1920 return;
1921 // Now reverse the entries we just added. This will match the DFS
1922 // ordering performed by the worklist.
1923 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1924 std::reverse(I, E);
1925}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001926void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1927 AddStmt(E->getInit());
1928 typedef DesignatedInitExpr::Designator Designator;
1929 for (DesignatedInitExpr::reverse_designators_iterator
1930 D = E->designators_rbegin(), DEnd = E->designators_rend();
1931 D != DEnd; ++D) {
1932 if (D->isFieldDesignator()) {
1933 if (FieldDecl *Field = D->getField())
1934 AddMemberRef(Field, D->getFieldLoc());
1935 continue;
1936 }
1937 if (D->isArrayDesignator()) {
1938 AddStmt(E->getArrayIndex(*D));
1939 continue;
1940 }
1941 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1942 AddStmt(E->getArrayRangeEnd(*D));
1943 AddStmt(E->getArrayRangeStart(*D));
1944 }
1945}
Ted Kremenek28a71942010-11-13 00:36:47 +00001946void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1947 EnqueueChildren(E);
1948 AddTypeLoc(E->getTypeInfoAsWritten());
1949}
1950void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1951 AddStmt(FS->getBody());
1952 AddStmt(FS->getInc());
1953 AddStmt(FS->getCond());
1954 AddDecl(FS->getConditionVariable());
1955 AddStmt(FS->getInit());
1956}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001957void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1958 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1959}
Ted Kremenek28a71942010-11-13 00:36:47 +00001960void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1961 AddStmt(If->getElse());
1962 AddStmt(If->getThen());
1963 AddStmt(If->getCond());
1964 AddDecl(If->getConditionVariable());
1965}
1966void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1967 // We care about the syntactic form of the initializer list, only.
1968 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1969 IE = Syntactic;
1970 EnqueueChildren(IE);
1971}
1972void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001973 WL.push_back(MemberExprParts(M, Parent));
1974
1975 // If the base of the member access expression is an implicit 'this', don't
1976 // visit it.
1977 // FIXME: If we ever want to show these implicit accesses, this will be
1978 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001979 if (!M->isImplicitAccess())
1980 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001981}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001982void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1983 AddTypeLoc(E->getEncodedTypeSourceInfo());
1984}
Ted Kremenek28a71942010-11-13 00:36:47 +00001985void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1986 EnqueueChildren(M);
1987 AddTypeLoc(M->getClassReceiverTypeInfo());
1988}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001989void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1990 // Visit the components of the offsetof expression.
1991 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1992 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1993 const OffsetOfNode &Node = E->getComponent(I-1);
1994 switch (Node.getKind()) {
1995 case OffsetOfNode::Array:
1996 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1997 break;
1998 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00001999 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002000 break;
2001 case OffsetOfNode::Identifier:
2002 case OffsetOfNode::Base:
2003 continue;
2004 }
2005 }
2006 // Visit the type into which we're computing the offset.
2007 AddTypeLoc(E->getTypeSourceInfo());
2008}
Ted Kremenek28a71942010-11-13 00:36:47 +00002009void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002010 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002011 WL.push_back(OverloadExprParts(E, Parent));
2012}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002013void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2014 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002015 EnqueueChildren(E);
2016 if (E->isArgumentType())
2017 AddTypeLoc(E->getArgumentTypeInfo());
2018}
Ted Kremenek28a71942010-11-13 00:36:47 +00002019void EnqueueVisitor::VisitStmt(Stmt *S) {
2020 EnqueueChildren(S);
2021}
2022void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2023 AddStmt(S->getBody());
2024 AddStmt(S->getCond());
2025 AddDecl(S->getConditionVariable());
2026}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002027
Ted Kremenek28a71942010-11-13 00:36:47 +00002028void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2029 AddStmt(W->getBody());
2030 AddStmt(W->getCond());
2031 AddDecl(W->getConditionVariable());
2032}
John Wiegley21ff2e52011-04-28 00:16:57 +00002033
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002034void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2035 AddTypeLoc(E->getQueriedTypeSourceInfo());
2036}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002037
2038void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002039 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002040 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002041}
2042
John Wiegley21ff2e52011-04-28 00:16:57 +00002043void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2044 AddTypeLoc(E->getQueriedTypeSourceInfo());
2045}
2046
John Wiegley55262202011-04-25 06:54:41 +00002047void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2048 EnqueueChildren(E);
2049}
2050
Ted Kremenek28a71942010-11-13 00:36:47 +00002051void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2052 VisitOverloadExpr(U);
2053 if (!U->isImplicitAccess())
2054 AddStmt(U->getBase());
2055}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002056void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2057 AddStmt(E->getSubExpr());
2058 AddTypeLoc(E->getWrittenTypeInfo());
2059}
Douglas Gregor94d96292011-01-19 20:34:17 +00002060void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2061 WL.push_back(SizeOfPackExprParts(E, Parent));
2062}
Ted Kremenek60458782010-11-12 21:34:16 +00002063
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002064void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002065 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002066}
2067
2068bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2069 if (RegionOfInterest.isValid()) {
2070 SourceRange Range = getRawCursorExtent(C);
2071 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2072 return false;
2073 }
2074 return true;
2075}
2076
2077bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2078 while (!WL.empty()) {
2079 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002080 VisitorJob LI = WL.back();
2081 WL.pop_back();
2082
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002083 // Set the Parent field, then back to its old value once we're done.
2084 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2085
2086 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002087 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002088 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002089 if (!D)
2090 continue;
2091
2092 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002093 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2094 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002095 return true;
2096
2097 continue;
2098 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002099 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002100 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002101 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2102 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2103 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2104 Arg != ArgEnd; ++Arg) {
2105 if (VisitTemplateArgumentLoc(*Arg))
2106 return true;
2107 }
2108 continue;
2109 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002110 case VisitorJob::TypeLocVisitKind: {
2111 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002112 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002113 return true;
2114 continue;
2115 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002116 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002117 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002118 if (LabelStmt *stmt = LS->getStmt()) {
2119 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2120 TU))) {
2121 return true;
2122 }
2123 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002124 continue;
2125 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002126
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002127 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2128 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2129 if (VisitNestedNameSpecifierLoc(V->get()))
2130 return true;
2131 continue;
2132 }
2133
Ted Kremenekf64d8032010-11-18 00:02:32 +00002134 case VisitorJob::DeclarationNameInfoVisitKind: {
2135 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2136 ->get()))
2137 return true;
2138 continue;
2139 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002140 case VisitorJob::MemberRefVisitKind: {
2141 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2142 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2143 return true;
2144 continue;
2145 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002146 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002147 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002148 if (!S)
2149 continue;
2150
Ted Kremenekf1107452010-11-12 18:26:56 +00002151 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002152 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002153 if (!IsInRegionOfInterest(Cursor))
2154 continue;
2155 switch (Visitor(Cursor, Parent, ClientData)) {
2156 case CXChildVisit_Break: return true;
2157 case CXChildVisit_Continue: break;
2158 case CXChildVisit_Recurse:
2159 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002160 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002161 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002162 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002163 }
2164 case VisitorJob::MemberExprPartsKind: {
2165 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002166 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002167
2168 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002169 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2170 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002171 return true;
2172
2173 // Visit the declaration name.
2174 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2175 return true;
2176
2177 // Visit the explicitly-specified template arguments, if any.
2178 if (M->hasExplicitTemplateArgs()) {
2179 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2180 *ArgEnd = Arg + M->getNumTemplateArgs();
2181 Arg != ArgEnd; ++Arg) {
2182 if (VisitTemplateArgumentLoc(*Arg))
2183 return true;
2184 }
2185 }
2186 continue;
2187 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002188 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002189 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002190 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002191 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2192 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002193 return true;
2194 // Visit declaration name.
2195 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2196 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002197 continue;
2198 }
Ted Kremenek60458782010-11-12 21:34:16 +00002199 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002200 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002201 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002202 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2203 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002204 return true;
2205 // Visit the declaration name.
2206 if (VisitDeclarationNameInfo(O->getNameInfo()))
2207 return true;
2208 // Visit the overloaded declaration reference.
2209 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2210 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002211 continue;
2212 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002213 case VisitorJob::SizeOfPackExprPartsKind: {
2214 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2215 NamedDecl *Pack = E->getPack();
2216 if (isa<TemplateTypeParmDecl>(Pack)) {
2217 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2218 E->getPackLoc(), TU)))
2219 return true;
2220
2221 continue;
2222 }
2223
2224 if (isa<TemplateTemplateParmDecl>(Pack)) {
2225 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2226 E->getPackLoc(), TU)))
2227 return true;
2228
2229 continue;
2230 }
2231
2232 // Non-type template parameter packs and function parameter packs are
2233 // treated like DeclRefExpr cursors.
2234 continue;
2235 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002236 }
2237 }
2238 return false;
2239}
2240
Ted Kremenekcdba6592010-11-18 00:42:18 +00002241bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002242 VisitorWorkList *WL = 0;
2243 if (!WorkListFreeList.empty()) {
2244 WL = WorkListFreeList.back();
2245 WL->clear();
2246 WorkListFreeList.pop_back();
2247 }
2248 else {
2249 WL = new VisitorWorkList();
2250 WorkListCache.push_back(WL);
2251 }
2252 EnqueueWorkList(*WL, S);
2253 bool result = RunVisitorWorkList(*WL);
2254 WorkListFreeList.push_back(WL);
2255 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002256}
2257
Francois Pichet48a8d142011-07-25 22:00:44 +00002258namespace {
2259typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2260RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2261 const DeclarationNameInfo &NI,
2262 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002263 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002264 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2265 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2266 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2267
2268 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2269
2270 RefNamePieces Pieces;
2271
2272 if (WantQualifier && QLoc.isValid())
2273 Pieces.push_back(QLoc);
2274
2275 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2276 Pieces.push_back(NI.getLoc());
2277
2278 if (WantTemplateArgs && TemplateArgs)
2279 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2280 TemplateArgs->RAngleLoc));
2281
2282 if (Kind == DeclarationName::CXXOperatorName) {
2283 Pieces.push_back(SourceLocation::getFromRawEncoding(
2284 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2285 Pieces.push_back(SourceLocation::getFromRawEncoding(
2286 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2287 }
2288
2289 if (WantSinglePiece) {
2290 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2291 Pieces.clear();
2292 Pieces.push_back(R);
2293 }
2294
2295 return Pieces;
2296}
2297}
2298
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002299//===----------------------------------------------------------------------===//
2300// Misc. API hooks.
2301//===----------------------------------------------------------------------===//
2302
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002303static llvm::sys::Mutex EnableMultithreadingMutex;
2304static bool EnabledMultithreading;
2305
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002306extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002307CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2308 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002309 // Disable pretty stack trace functionality, which will otherwise be a very
2310 // poor citizen of the world and set up all sorts of signal handlers.
2311 llvm::DisablePrettyStackTrace = true;
2312
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002313 // We use crash recovery to make some of our APIs more reliable, implicitly
2314 // enable it.
2315 llvm::CrashRecoveryContext::Enable();
2316
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002317 // Enable support for multithreading in LLVM.
2318 {
2319 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2320 if (!EnabledMultithreading) {
2321 llvm::llvm_start_multithreaded();
2322 EnabledMultithreading = true;
2323 }
2324 }
2325
Douglas Gregora030b7c2010-01-22 20:35:53 +00002326 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002327 if (excludeDeclarationsFromPCH)
2328 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002329 if (displayDiagnostics)
2330 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002331 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002332}
2333
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002334void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002335 if (CIdx)
2336 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002337}
2338
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002339void clang_toggleCrashRecovery(unsigned isEnabled) {
2340 if (isEnabled)
2341 llvm::CrashRecoveryContext::Enable();
2342 else
2343 llvm::CrashRecoveryContext::Disable();
2344}
2345
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002346CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002347 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002348 if (!CIdx)
2349 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002350
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002351 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002352 FileSystemOptions FileSystemOpts;
2353 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002354
David Blaikied6471f72011-09-25 23:23:43 +00002355 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002356 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002357 CXXIdx->getOnlyLocalDecls(),
2358 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002359 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002360}
2361
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002362unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002363 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002364 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002365}
2366
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002367CXTranslationUnit
2368clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2369 const char *source_filename,
2370 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002371 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002372 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002373 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002374 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002375 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002376 return clang_parseTranslationUnit(CIdx, source_filename,
2377 command_line_args, num_command_line_args,
2378 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002379 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002380}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002381
2382struct ParseTranslationUnitInfo {
2383 CXIndex CIdx;
2384 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002385 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002386 int num_command_line_args;
2387 struct CXUnsavedFile *unsaved_files;
2388 unsigned num_unsaved_files;
2389 unsigned options;
2390 CXTranslationUnit result;
2391};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002392static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002393 ParseTranslationUnitInfo *PTUI =
2394 static_cast<ParseTranslationUnitInfo*>(UserData);
2395 CXIndex CIdx = PTUI->CIdx;
2396 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002397 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002398 int num_command_line_args = PTUI->num_command_line_args;
2399 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2400 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2401 unsigned options = PTUI->options;
2402 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002403
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002404 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002405 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002406
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002407 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2408
Douglas Gregor44c181a2010-07-23 00:33:23 +00002409 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002410 // FIXME: Add a flag for modules.
2411 TranslationUnitKind TUKind
2412 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002413 bool CacheCodeCompetionResults
2414 = options & CXTranslationUnit_CacheCompletionResults;
2415
Douglas Gregor5352ac02010-01-28 00:27:43 +00002416 // Configure the diagnostics.
2417 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002418 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002419 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2420 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002421
Ted Kremenek25a11e12011-03-22 01:15:24 +00002422 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002423 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2424 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002425 DiagCleanup(Diags.getPtr());
2426
2427 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2428 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2429
2430 // Recover resources if we crash before exiting this function.
2431 llvm::CrashRecoveryContextCleanupRegistrar<
2432 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2433
Douglas Gregor4db64a42010-01-23 00:14:00 +00002434 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002435 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002436 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002437 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002438 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2439 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002440 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441
Ted Kremenek25a11e12011-03-22 01:15:24 +00002442 llvm::OwningPtr<std::vector<const char *> >
2443 Args(new std::vector<const char*>());
2444
2445 // Recover resources if we crash before exiting this method.
2446 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2447 ArgsCleanup(Args.get());
2448
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002449 // Since the Clang C library is primarily used by batch tools dealing with
2450 // (often very broken) source code, where spell-checking can have a
2451 // significant negative impact on performance (particularly when
2452 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002453 // Only do this if we haven't found a spell-checking-related argument.
2454 bool FoundSpellCheckingArgument = false;
2455 for (int I = 0; I != num_command_line_args; ++I) {
2456 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2457 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2458 FoundSpellCheckingArgument = true;
2459 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002460 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002461 }
2462 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002463 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002464
Ted Kremenek25a11e12011-03-22 01:15:24 +00002465 Args->insert(Args->end(), command_line_args,
2466 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002467
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002468 // The 'source_filename' argument is optional. If the caller does not
2469 // specify it then it is assumed that the source file is specified
2470 // in the actual argument list.
2471 // Put the source file after command_line_args otherwise if '-x' flag is
2472 // present it will be unused.
2473 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002474 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002475
Douglas Gregor44c181a2010-07-23 00:33:23 +00002476 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002477 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002478 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002479 Args->push_back("-Xclang");
2480 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002481 NestedMacroExpansions
2482 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002483 }
2484
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002485 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002486 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002487 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2488 /* vector::data() not portable */,
2489 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002490 Diags,
2491 CXXIdx->getClangResourcesPath(),
2492 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002493 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002494 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002495 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002496 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002497 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002498 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002499 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002500 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002501
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002502 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002503 // Make sure to check that 'Unit' is non-NULL.
2504 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2505 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2506 DEnd = Unit->stored_diag_end();
2507 D != DEnd; ++D) {
2508 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2509 CXString Msg = clang_formatDiagnostic(&Diag,
2510 clang_defaultDiagnosticDisplayOptions());
2511 fprintf(stderr, "%s\n", clang_getCString(Msg));
2512 clang_disposeString(Msg);
2513 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002514#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002515 // On Windows, force a flush, since there may be multiple copies of
2516 // stderr and stdout in the file system, all with different buffers
2517 // but writing to the same device.
2518 fflush(stderr);
2519#endif
2520 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002521 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002522
Ted Kremeneka60ed472010-11-16 08:15:36 +00002523 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002524}
2525CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2526 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002527 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002528 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002529 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002530 unsigned num_unsaved_files,
2531 unsigned options) {
2532 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002533 num_command_line_args, unsaved_files,
2534 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002535 llvm::CrashRecoveryContext CRC;
2536
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002537 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002538 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2539 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2540 fprintf(stderr, " 'command_line_args' : [");
2541 for (int i = 0; i != num_command_line_args; ++i) {
2542 if (i)
2543 fprintf(stderr, ", ");
2544 fprintf(stderr, "'%s'", command_line_args[i]);
2545 }
2546 fprintf(stderr, "],\n");
2547 fprintf(stderr, " 'unsaved_files' : [");
2548 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2549 if (i)
2550 fprintf(stderr, ", ");
2551 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2552 unsaved_files[i].Length);
2553 }
2554 fprintf(stderr, "],\n");
2555 fprintf(stderr, " 'options' : %d,\n", options);
2556 fprintf(stderr, "}\n");
2557
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002558 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002559 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2560 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002561 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002562
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002563 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002564}
2565
Douglas Gregor19998442010-08-13 15:35:05 +00002566unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2567 return CXSaveTranslationUnit_None;
2568}
2569
2570int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2571 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002572 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002573 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002574
Douglas Gregor39c411f2011-07-06 16:43:36 +00002575 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002576 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2577 PrintLibclangResourceUsage(TU);
2578 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002579}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002580
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002581void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002582 if (CTUnit) {
2583 // If the translation unit has been marked as unsafe to free, just discard
2584 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002585 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002586 return;
2587
Ted Kremeneka60ed472010-11-16 08:15:36 +00002588 delete static_cast<ASTUnit *>(CTUnit->TUData);
2589 disposeCXStringPool(CTUnit->StringPool);
2590 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002591 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002592}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002593
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002594unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2595 return CXReparse_None;
2596}
2597
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002598struct ReparseTranslationUnitInfo {
2599 CXTranslationUnit TU;
2600 unsigned num_unsaved_files;
2601 struct CXUnsavedFile *unsaved_files;
2602 unsigned options;
2603 int result;
2604};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002605
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002606static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002607 ReparseTranslationUnitInfo *RTUI =
2608 static_cast<ReparseTranslationUnitInfo*>(UserData);
2609 CXTranslationUnit TU = RTUI->TU;
2610 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2611 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2612 unsigned options = RTUI->options;
2613 (void) options;
2614 RTUI->result = 1;
2615
Douglas Gregorabc563f2010-07-19 21:46:24 +00002616 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002617 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002618
Ted Kremeneka60ed472010-11-16 08:15:36 +00002619 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002620 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002621
Ted Kremenek25a11e12011-03-22 01:15:24 +00002622 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2623 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2624
2625 // Recover resources if we crash before exiting this function.
2626 llvm::CrashRecoveryContextCleanupRegistrar<
2627 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2628
Douglas Gregorabc563f2010-07-19 21:46:24 +00002629 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002630 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002631 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002632 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002633 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2634 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002635 }
2636
Ted Kremenek4ee99262011-03-22 20:16:19 +00002637 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2638 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002639 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002640}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002641
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002642int clang_reparseTranslationUnit(CXTranslationUnit TU,
2643 unsigned num_unsaved_files,
2644 struct CXUnsavedFile *unsaved_files,
2645 unsigned options) {
2646 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2647 options, 0 };
2648 llvm::CrashRecoveryContext CRC;
2649
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002650 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002651 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002652 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002653 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002654 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2655 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002656
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002657 return RTUI.result;
2658}
2659
Douglas Gregordf95a132010-08-09 20:45:32 +00002660
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002661CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002662 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002663 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002664
Ted Kremeneka60ed472010-11-16 08:15:36 +00002665 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002666 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002667}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002668
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002669CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002670 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002671 return Result;
2672}
2673
Ted Kremenekfb480492010-01-13 21:46:36 +00002674} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002675
Ted Kremenekfb480492010-01-13 21:46:36 +00002676//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002677// CXSourceLocation and CXSourceRange Operations.
2678//===----------------------------------------------------------------------===//
2679
Douglas Gregorb9790342010-01-22 21:44:22 +00002680extern "C" {
2681CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002682 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002683 return Result;
2684}
2685
2686unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002687 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2688 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2689 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002690}
2691
2692CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2693 CXFile file,
2694 unsigned line,
2695 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002696 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002697 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002698
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002699 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002700 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Argyrios Kyrtzidis57165be2011-10-10 21:57:15 +00002701 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002702 const FileEntry *File = static_cast<const FileEntry *>(file);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002703 SourceLocation SLoc = CXXUnit->getLocation(File, line, column);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002704 if (SLoc.isInvalid()) {
2705 if (Logging)
2706 llvm::errs() << "clang_getLocation(\"" << File->getName()
2707 << "\", " << line << ", " << column << ") = invalid\n";
2708 return clang_getNullLocation();
2709 }
2710
2711 if (Logging)
2712 llvm::errs() << "clang_getLocation(\"" << File->getName()
2713 << "\", " << line << ", " << column << ") = "
2714 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002715
2716 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2717}
2718
2719CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2720 CXFile file,
2721 unsigned offset) {
2722 if (!tu || !file)
2723 return clang_getNullLocation();
2724
Ted Kremeneka60ed472010-11-16 08:15:36 +00002725 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002726 SourceLocation SLoc
2727 = CXXUnit->getLocation(static_cast<const FileEntry *>(file), offset);
David Chisnall83889a72010-10-15 17:07:39 +00002728 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002729
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002730 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002731}
2732
Douglas Gregor5352ac02010-01-28 00:27:43 +00002733CXSourceRange clang_getNullRange() {
2734 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2735 return Result;
2736}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002737
Douglas Gregor5352ac02010-01-28 00:27:43 +00002738CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2739 if (begin.ptr_data[0] != end.ptr_data[0] ||
2740 begin.ptr_data[1] != end.ptr_data[1])
2741 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002742
2743 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002744 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002745 return Result;
2746}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002747
2748unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2749{
2750 return range1.ptr_data[0] == range2.ptr_data[0]
2751 && range1.ptr_data[1] == range2.ptr_data[1]
2752 && range1.begin_int_data == range2.begin_int_data
2753 && range1.end_int_data == range2.end_int_data;
2754}
Argyrios Kyrtzidisde5db642011-09-28 18:14:21 +00002755
2756int clang_Range_isNull(CXSourceRange range) {
2757 return clang_equalRanges(range, clang_getNullRange());
2758}
2759
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002760} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002761
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002762static void createNullLocation(CXFile *file, unsigned *line,
2763 unsigned *column, unsigned *offset) {
2764 if (file)
2765 *file = 0;
2766 if (line)
2767 *line = 0;
2768 if (column)
2769 *column = 0;
2770 if (offset)
2771 *offset = 0;
2772 return;
2773}
2774
2775extern "C" {
Chandler Carruth20174222011-08-31 16:53:37 +00002776void clang_getExpansionLocation(CXSourceLocation location,
2777 CXFile *file,
2778 unsigned *line,
2779 unsigned *column,
2780 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002781 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2782
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002783 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002784 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002785 return;
2786 }
2787
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002788 const SourceManager &SM =
2789 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth20174222011-08-31 16:53:37 +00002790 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002791
Chandler Carruthcea731a2011-07-14 16:07:57 +00002792 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002793 // This can manifest in invalid code.
Chandler Carruth20174222011-08-31 16:53:37 +00002794 FileID fileID = SM.getFileID(ExpansionLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002795 bool Invalid = false;
2796 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
Argyrios Kyrtzidisc705d252011-10-18 21:59:54 +00002797 if (Invalid || !sloc.isFile()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002798 createNullLocation(file, line, column, offset);
2799 return;
2800 }
2801
Douglas Gregor1db19de2010-01-19 21:36:55 +00002802 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002803 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002804 if (line)
Chandler Carruth20174222011-08-31 16:53:37 +00002805 *line = SM.getExpansionLineNumber(ExpansionLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002806 if (column)
Chandler Carruth20174222011-08-31 16:53:37 +00002807 *column = SM.getExpansionColumnNumber(ExpansionLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002808 if (offset)
Chandler Carruth20174222011-08-31 16:53:37 +00002809 *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2810}
2811
Argyrios Kyrtzidise6be34d2011-09-13 21:49:08 +00002812void clang_getPresumedLocation(CXSourceLocation location,
2813 CXString *filename,
2814 unsigned *line,
2815 unsigned *column) {
2816 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2817
2818 if (!location.ptr_data[0] || Loc.isInvalid()) {
2819 if (filename)
2820 *filename = createCXString("");
2821 if (line)
2822 *line = 0;
2823 if (column)
2824 *column = 0;
2825 }
2826 else {
2827 const SourceManager &SM =
2828 *static_cast<const SourceManager*>(location.ptr_data[0]);
2829 PresumedLoc PreLoc = SM.getPresumedLoc(Loc);
2830
2831 if (filename)
2832 *filename = createCXString(PreLoc.getFilename());
2833 if (line)
2834 *line = PreLoc.getLine();
2835 if (column)
2836 *column = PreLoc.getColumn();
2837 }
2838}
2839
Chandler Carruth20174222011-08-31 16:53:37 +00002840void clang_getInstantiationLocation(CXSourceLocation location,
2841 CXFile *file,
2842 unsigned *line,
2843 unsigned *column,
2844 unsigned *offset) {
2845 // Redirect to new API.
2846 clang_getExpansionLocation(location, file, line, column, offset);
Douglas Gregore69517c2010-01-26 03:07:15 +00002847}
2848
Douglas Gregora9b06d42010-11-09 06:24:54 +00002849void clang_getSpellingLocation(CXSourceLocation location,
2850 CXFile *file,
2851 unsigned *line,
2852 unsigned *column,
2853 unsigned *offset) {
2854 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2855
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002856 if (!location.ptr_data[0] || Loc.isInvalid())
2857 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002858
2859 const SourceManager &SM =
2860 *static_cast<const SourceManager*>(location.ptr_data[0]);
2861 SourceLocation SpellLoc = Loc;
2862 if (SpellLoc.isMacroID()) {
2863 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2864 if (SimpleSpellingLoc.isFileID() &&
2865 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2866 SpellLoc = SimpleSpellingLoc;
2867 else
Chandler Carruth40278532011-07-25 16:49:02 +00002868 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002869 }
2870
2871 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2872 FileID FID = LocInfo.first;
2873 unsigned FileOffset = LocInfo.second;
2874
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002875 if (FID.isInvalid())
2876 return createNullLocation(file, line, column, offset);
2877
Douglas Gregora9b06d42010-11-09 06:24:54 +00002878 if (file)
2879 *file = (void *)SM.getFileEntryForID(FID);
2880 if (line)
2881 *line = SM.getLineNumber(FID, FileOffset);
2882 if (column)
2883 *column = SM.getColumnNumber(FID, FileOffset);
2884 if (offset)
2885 *offset = FileOffset;
2886}
2887
Douglas Gregor1db19de2010-01-19 21:36:55 +00002888CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002889 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002890 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002891 return Result;
2892}
2893
2894CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002895 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002896 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002897 return Result;
2898}
2899
Douglas Gregorb9790342010-01-22 21:44:22 +00002900} // end: extern "C"
2901
Douglas Gregor1db19de2010-01-19 21:36:55 +00002902//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002903// CXFile Operations.
2904//===----------------------------------------------------------------------===//
2905
2906extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002907CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002908 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002909 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002910
Steve Naroff88145032009-10-27 14:35:18 +00002911 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002912 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002913}
2914
2915time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002916 if (!SFile)
2917 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002918
Steve Naroff88145032009-10-27 14:35:18 +00002919 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2920 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002921}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002922
Douglas Gregorb9790342010-01-22 21:44:22 +00002923CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2924 if (!tu)
2925 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002926
Ted Kremeneka60ed472010-11-16 08:15:36 +00002927 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002928
Douglas Gregorb9790342010-01-22 21:44:22 +00002929 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002930 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002931}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002932
Douglas Gregordd3e5542011-05-04 00:14:37 +00002933unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2934 if (!tu || !file)
2935 return 0;
2936
2937 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2938 FileEntry *FEnt = static_cast<FileEntry *>(file);
2939 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2940 .isFileMultipleIncludeGuarded(FEnt);
2941}
2942
Ted Kremenekfb480492010-01-13 21:46:36 +00002943} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002944
Ted Kremenekfb480492010-01-13 21:46:36 +00002945//===----------------------------------------------------------------------===//
2946// CXCursor Operations.
2947//===----------------------------------------------------------------------===//
2948
Ted Kremenekfb480492010-01-13 21:46:36 +00002949static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002950 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002951 return getDeclFromExpr(CE->getSubExpr());
2952
Ted Kremenekfb480492010-01-13 21:46:36 +00002953 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2954 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002955 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2956 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002957 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2958 return ME->getMemberDecl();
2959 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2960 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002961 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002962 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002963
Ted Kremenekfb480492010-01-13 21:46:36 +00002964 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2965 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002966 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002967 if (!CE->isElidable())
2968 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002969 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2970 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002971
Douglas Gregordb1314e2010-10-01 21:11:22 +00002972 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2973 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002974 if (SubstNonTypeTemplateParmPackExpr *NTTP
2975 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2976 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002977 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2978 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2979 isa<ParmVarDecl>(SizeOfPack->getPack()))
2980 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002981
Ted Kremenekfb480492010-01-13 21:46:36 +00002982 return 0;
2983}
2984
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002985static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002986 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2987 return getLocationFromExpr(CE->getSubExpr());
2988
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002989 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2990 return /*FIXME:*/Msg->getLeftLoc();
2991 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2992 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002993 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2994 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002995 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2996 return Member->getMemberLoc();
2997 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2998 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002999 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3000 return SizeOfPack->getPackLoc();
3001
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003002 return E->getLocStart();
3003}
3004
Ted Kremenekfb480492010-01-13 21:46:36 +00003005extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003006
3007unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003008 CXCursorVisitor visitor,
3009 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003010 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003011 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003012 return CursorVis.VisitChildren(parent);
3013}
3014
David Chisnall3387c652010-11-03 14:12:26 +00003015#ifndef __has_feature
3016#define __has_feature(x) 0
3017#endif
3018#if __has_feature(blocks)
3019typedef enum CXChildVisitResult
3020 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3021
3022static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3023 CXClientData client_data) {
3024 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3025 return block(cursor, parent);
3026}
3027#else
3028// If we are compiled with a compiler that doesn't have native blocks support,
3029// define and call the block manually, so the
3030typedef struct _CXChildVisitResult
3031{
3032 void *isa;
3033 int flags;
3034 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003035 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3036 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003037} *CXCursorVisitorBlock;
3038
3039static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3040 CXClientData client_data) {
3041 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3042 return block->invoke(block, cursor, parent);
3043}
3044#endif
3045
3046
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003047unsigned clang_visitChildrenWithBlock(CXCursor parent,
3048 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003049 return clang_visitChildren(parent, visitWithBlock, block);
3050}
3051
Douglas Gregor78205d42010-01-20 21:45:58 +00003052static CXString getDeclSpelling(Decl *D) {
3053 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003054 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003055 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003056 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3057 return createCXString(Property->getIdentifier()->getName());
3058
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003059 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003060 }
3061
Douglas Gregor78205d42010-01-20 21:45:58 +00003062 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003063 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003064
Douglas Gregor78205d42010-01-20 21:45:58 +00003065 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3066 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3067 // and returns different names. NamedDecl returns the class name and
3068 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003069 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003070
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003071 if (isa<UsingDirectiveDecl>(D))
3072 return createCXString("");
3073
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003074 llvm::SmallString<1024> S;
3075 llvm::raw_svector_ostream os(S);
3076 ND->printName(os);
3077
3078 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003079}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003080
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003081CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003082 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003083 return clang_getTranslationUnitSpelling(
3084 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003085
Steve Narofff334b4e2009-09-02 18:26:48 +00003086 if (clang_isReference(C.kind)) {
3087 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003088 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003089 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003090 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003091 }
3092 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003093 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003094 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003095 }
3096 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003097 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003098 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003099 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003100 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003101 case CXCursor_CXXBaseSpecifier: {
3102 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3103 return createCXString(B->getType().getAsString());
3104 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003105 case CXCursor_TypeRef: {
3106 TypeDecl *Type = getCursorTypeRef(C).first;
3107 assert(Type && "Missing type decl");
3108
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003109 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3110 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003111 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003112 case CXCursor_TemplateRef: {
3113 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003114 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003115
3116 return createCXString(Template->getNameAsString());
3117 }
Douglas Gregor69319002010-08-31 23:48:11 +00003118
3119 case CXCursor_NamespaceRef: {
3120 NamedDecl *NS = getCursorNamespaceRef(C).first;
3121 assert(NS && "Missing namespace decl");
3122
3123 return createCXString(NS->getNameAsString());
3124 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003125
Douglas Gregora67e03f2010-09-09 21:42:20 +00003126 case CXCursor_MemberRef: {
3127 FieldDecl *Field = getCursorMemberRef(C).first;
3128 assert(Field && "Missing member decl");
3129
3130 return createCXString(Field->getNameAsString());
3131 }
3132
Douglas Gregor36897b02010-09-10 00:22:18 +00003133 case CXCursor_LabelRef: {
3134 LabelStmt *Label = getCursorLabelRef(C).first;
3135 assert(Label && "Missing label");
3136
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003137 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003138 }
3139
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003140 case CXCursor_OverloadedDeclRef: {
3141 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3142 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3143 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3144 return createCXString(ND->getNameAsString());
3145 return createCXString("");
3146 }
3147 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3148 return createCXString(E->getName().getAsString());
3149 OverloadedTemplateStorage *Ovl
3150 = Storage.get<OverloadedTemplateStorage*>();
3151 if (Ovl->size() == 0)
3152 return createCXString("");
3153 return createCXString((*Ovl->begin())->getNameAsString());
3154 }
3155
Daniel Dunbaracca7252009-11-30 20:42:49 +00003156 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003157 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003158 }
3159 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003160
3161 if (clang_isExpression(C.kind)) {
3162 Decl *D = getDeclFromExpr(getCursorExpr(C));
3163 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003164 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003165 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003166 }
3167
Douglas Gregor36897b02010-09-10 00:22:18 +00003168 if (clang_isStatement(C.kind)) {
3169 Stmt *S = getCursorStmt(C);
3170 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003171 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003172
3173 return createCXString("");
3174 }
3175
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003176 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003177 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003178 ->getNameStart());
3179
Douglas Gregor572feb22010-03-18 18:04:21 +00003180 if (C.kind == CXCursor_MacroDefinition)
3181 return createCXString(getCursorMacroDefinition(C)->getName()
3182 ->getNameStart());
3183
Douglas Gregorecdcb882010-10-20 22:00:55 +00003184 if (C.kind == CXCursor_InclusionDirective)
3185 return createCXString(getCursorInclusionDirective(C)->getFileName());
3186
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003187 if (clang_isDeclaration(C.kind))
3188 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003189
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003190 if (C.kind == CXCursor_AnnotateAttr) {
3191 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3192 return createCXString(AA->getAnnotation());
3193 }
3194
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003195 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003196}
3197
Douglas Gregor358559d2010-10-02 22:49:11 +00003198CXString clang_getCursorDisplayName(CXCursor C) {
3199 if (!clang_isDeclaration(C.kind))
3200 return clang_getCursorSpelling(C);
3201
3202 Decl *D = getCursorDecl(C);
3203 if (!D)
3204 return createCXString("");
3205
Douglas Gregor30c42402011-09-27 22:38:19 +00003206 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003207 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3208 D = FunTmpl->getTemplatedDecl();
3209
3210 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3211 llvm::SmallString<64> Str;
3212 llvm::raw_svector_ostream OS(Str);
3213 OS << Function->getNameAsString();
3214 if (Function->getPrimaryTemplate())
3215 OS << "<>";
3216 OS << "(";
3217 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3218 if (I)
3219 OS << ", ";
3220 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3221 }
3222
3223 if (Function->isVariadic()) {
3224 if (Function->getNumParams())
3225 OS << ", ";
3226 OS << "...";
3227 }
3228 OS << ")";
3229 return createCXString(OS.str());
3230 }
3231
3232 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3233 llvm::SmallString<64> Str;
3234 llvm::raw_svector_ostream OS(Str);
3235 OS << ClassTemplate->getNameAsString();
3236 OS << "<";
3237 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3238 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3239 if (I)
3240 OS << ", ";
3241
3242 NamedDecl *Param = Params->getParam(I);
3243 if (Param->getIdentifier()) {
3244 OS << Param->getIdentifier()->getName();
3245 continue;
3246 }
3247
3248 // There is no parameter name, which makes this tricky. Try to come up
3249 // with something useful that isn't too long.
3250 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3251 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3252 else if (NonTypeTemplateParmDecl *NTTP
3253 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3254 OS << NTTP->getType().getAsString(Policy);
3255 else
3256 OS << "template<...> class";
3257 }
3258
3259 OS << ">";
3260 return createCXString(OS.str());
3261 }
3262
3263 if (ClassTemplateSpecializationDecl *ClassSpec
3264 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3265 // If the type was explicitly written, use that.
3266 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3267 return createCXString(TSInfo->getType().getAsString(Policy));
3268
3269 llvm::SmallString<64> Str;
3270 llvm::raw_svector_ostream OS(Str);
3271 OS << ClassSpec->getNameAsString();
3272 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003273 ClassSpec->getTemplateArgs().data(),
3274 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003275 Policy);
3276 return createCXString(OS.str());
3277 }
3278
3279 return clang_getCursorSpelling(C);
3280}
3281
Ted Kremeneke68fff62010-02-17 00:41:32 +00003282CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003283 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003284 case CXCursor_FunctionDecl:
3285 return createCXString("FunctionDecl");
3286 case CXCursor_TypedefDecl:
3287 return createCXString("TypedefDecl");
3288 case CXCursor_EnumDecl:
3289 return createCXString("EnumDecl");
3290 case CXCursor_EnumConstantDecl:
3291 return createCXString("EnumConstantDecl");
3292 case CXCursor_StructDecl:
3293 return createCXString("StructDecl");
3294 case CXCursor_UnionDecl:
3295 return createCXString("UnionDecl");
3296 case CXCursor_ClassDecl:
3297 return createCXString("ClassDecl");
3298 case CXCursor_FieldDecl:
3299 return createCXString("FieldDecl");
3300 case CXCursor_VarDecl:
3301 return createCXString("VarDecl");
3302 case CXCursor_ParmDecl:
3303 return createCXString("ParmDecl");
3304 case CXCursor_ObjCInterfaceDecl:
3305 return createCXString("ObjCInterfaceDecl");
3306 case CXCursor_ObjCCategoryDecl:
3307 return createCXString("ObjCCategoryDecl");
3308 case CXCursor_ObjCProtocolDecl:
3309 return createCXString("ObjCProtocolDecl");
3310 case CXCursor_ObjCPropertyDecl:
3311 return createCXString("ObjCPropertyDecl");
3312 case CXCursor_ObjCIvarDecl:
3313 return createCXString("ObjCIvarDecl");
3314 case CXCursor_ObjCInstanceMethodDecl:
3315 return createCXString("ObjCInstanceMethodDecl");
3316 case CXCursor_ObjCClassMethodDecl:
3317 return createCXString("ObjCClassMethodDecl");
3318 case CXCursor_ObjCImplementationDecl:
3319 return createCXString("ObjCImplementationDecl");
3320 case CXCursor_ObjCCategoryImplDecl:
3321 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003322 case CXCursor_CXXMethod:
3323 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003324 case CXCursor_UnexposedDecl:
3325 return createCXString("UnexposedDecl");
3326 case CXCursor_ObjCSuperClassRef:
3327 return createCXString("ObjCSuperClassRef");
3328 case CXCursor_ObjCProtocolRef:
3329 return createCXString("ObjCProtocolRef");
3330 case CXCursor_ObjCClassRef:
3331 return createCXString("ObjCClassRef");
3332 case CXCursor_TypeRef:
3333 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003334 case CXCursor_TemplateRef:
3335 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003336 case CXCursor_NamespaceRef:
3337 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003338 case CXCursor_MemberRef:
3339 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003340 case CXCursor_LabelRef:
3341 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003342 case CXCursor_OverloadedDeclRef:
3343 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003344 case CXCursor_IntegerLiteral:
3345 return createCXString("IntegerLiteral");
3346 case CXCursor_FloatingLiteral:
3347 return createCXString("FloatingLiteral");
3348 case CXCursor_ImaginaryLiteral:
3349 return createCXString("ImaginaryLiteral");
3350 case CXCursor_StringLiteral:
3351 return createCXString("StringLiteral");
3352 case CXCursor_CharacterLiteral:
3353 return createCXString("CharacterLiteral");
3354 case CXCursor_ParenExpr:
3355 return createCXString("ParenExpr");
3356 case CXCursor_UnaryOperator:
3357 return createCXString("UnaryOperator");
3358 case CXCursor_ArraySubscriptExpr:
3359 return createCXString("ArraySubscriptExpr");
3360 case CXCursor_BinaryOperator:
3361 return createCXString("BinaryOperator");
3362 case CXCursor_CompoundAssignOperator:
3363 return createCXString("CompoundAssignOperator");
3364 case CXCursor_ConditionalOperator:
3365 return createCXString("ConditionalOperator");
3366 case CXCursor_CStyleCastExpr:
3367 return createCXString("CStyleCastExpr");
3368 case CXCursor_CompoundLiteralExpr:
3369 return createCXString("CompoundLiteralExpr");
3370 case CXCursor_InitListExpr:
3371 return createCXString("InitListExpr");
3372 case CXCursor_AddrLabelExpr:
3373 return createCXString("AddrLabelExpr");
3374 case CXCursor_StmtExpr:
3375 return createCXString("StmtExpr");
3376 case CXCursor_GenericSelectionExpr:
3377 return createCXString("GenericSelectionExpr");
3378 case CXCursor_GNUNullExpr:
3379 return createCXString("GNUNullExpr");
3380 case CXCursor_CXXStaticCastExpr:
3381 return createCXString("CXXStaticCastExpr");
3382 case CXCursor_CXXDynamicCastExpr:
3383 return createCXString("CXXDynamicCastExpr");
3384 case CXCursor_CXXReinterpretCastExpr:
3385 return createCXString("CXXReinterpretCastExpr");
3386 case CXCursor_CXXConstCastExpr:
3387 return createCXString("CXXConstCastExpr");
3388 case CXCursor_CXXFunctionalCastExpr:
3389 return createCXString("CXXFunctionalCastExpr");
3390 case CXCursor_CXXTypeidExpr:
3391 return createCXString("CXXTypeidExpr");
3392 case CXCursor_CXXBoolLiteralExpr:
3393 return createCXString("CXXBoolLiteralExpr");
3394 case CXCursor_CXXNullPtrLiteralExpr:
3395 return createCXString("CXXNullPtrLiteralExpr");
3396 case CXCursor_CXXThisExpr:
3397 return createCXString("CXXThisExpr");
3398 case CXCursor_CXXThrowExpr:
3399 return createCXString("CXXThrowExpr");
3400 case CXCursor_CXXNewExpr:
3401 return createCXString("CXXNewExpr");
3402 case CXCursor_CXXDeleteExpr:
3403 return createCXString("CXXDeleteExpr");
3404 case CXCursor_UnaryExpr:
3405 return createCXString("UnaryExpr");
3406 case CXCursor_ObjCStringLiteral:
3407 return createCXString("ObjCStringLiteral");
3408 case CXCursor_ObjCEncodeExpr:
3409 return createCXString("ObjCEncodeExpr");
3410 case CXCursor_ObjCSelectorExpr:
3411 return createCXString("ObjCSelectorExpr");
3412 case CXCursor_ObjCProtocolExpr:
3413 return createCXString("ObjCProtocolExpr");
3414 case CXCursor_ObjCBridgedCastExpr:
3415 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003416 case CXCursor_BlockExpr:
3417 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003418 case CXCursor_PackExpansionExpr:
3419 return createCXString("PackExpansionExpr");
3420 case CXCursor_SizeOfPackExpr:
3421 return createCXString("SizeOfPackExpr");
3422 case CXCursor_UnexposedExpr:
3423 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003424 case CXCursor_DeclRefExpr:
3425 return createCXString("DeclRefExpr");
3426 case CXCursor_MemberRefExpr:
3427 return createCXString("MemberRefExpr");
3428 case CXCursor_CallExpr:
3429 return createCXString("CallExpr");
3430 case CXCursor_ObjCMessageExpr:
3431 return createCXString("ObjCMessageExpr");
3432 case CXCursor_UnexposedStmt:
3433 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003434 case CXCursor_DeclStmt:
3435 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003436 case CXCursor_LabelStmt:
3437 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003438 case CXCursor_CompoundStmt:
3439 return createCXString("CompoundStmt");
3440 case CXCursor_CaseStmt:
3441 return createCXString("CaseStmt");
3442 case CXCursor_DefaultStmt:
3443 return createCXString("DefaultStmt");
3444 case CXCursor_IfStmt:
3445 return createCXString("IfStmt");
3446 case CXCursor_SwitchStmt:
3447 return createCXString("SwitchStmt");
3448 case CXCursor_WhileStmt:
3449 return createCXString("WhileStmt");
3450 case CXCursor_DoStmt:
3451 return createCXString("DoStmt");
3452 case CXCursor_ForStmt:
3453 return createCXString("ForStmt");
3454 case CXCursor_GotoStmt:
3455 return createCXString("GotoStmt");
3456 case CXCursor_IndirectGotoStmt:
3457 return createCXString("IndirectGotoStmt");
3458 case CXCursor_ContinueStmt:
3459 return createCXString("ContinueStmt");
3460 case CXCursor_BreakStmt:
3461 return createCXString("BreakStmt");
3462 case CXCursor_ReturnStmt:
3463 return createCXString("ReturnStmt");
3464 case CXCursor_AsmStmt:
3465 return createCXString("AsmStmt");
3466 case CXCursor_ObjCAtTryStmt:
3467 return createCXString("ObjCAtTryStmt");
3468 case CXCursor_ObjCAtCatchStmt:
3469 return createCXString("ObjCAtCatchStmt");
3470 case CXCursor_ObjCAtFinallyStmt:
3471 return createCXString("ObjCAtFinallyStmt");
3472 case CXCursor_ObjCAtThrowStmt:
3473 return createCXString("ObjCAtThrowStmt");
3474 case CXCursor_ObjCAtSynchronizedStmt:
3475 return createCXString("ObjCAtSynchronizedStmt");
3476 case CXCursor_ObjCAutoreleasePoolStmt:
3477 return createCXString("ObjCAutoreleasePoolStmt");
3478 case CXCursor_ObjCForCollectionStmt:
3479 return createCXString("ObjCForCollectionStmt");
3480 case CXCursor_CXXCatchStmt:
3481 return createCXString("CXXCatchStmt");
3482 case CXCursor_CXXTryStmt:
3483 return createCXString("CXXTryStmt");
3484 case CXCursor_CXXForRangeStmt:
3485 return createCXString("CXXForRangeStmt");
3486 case CXCursor_SEHTryStmt:
3487 return createCXString("SEHTryStmt");
3488 case CXCursor_SEHExceptStmt:
3489 return createCXString("SEHExceptStmt");
3490 case CXCursor_SEHFinallyStmt:
3491 return createCXString("SEHFinallyStmt");
3492 case CXCursor_NullStmt:
3493 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003494 case CXCursor_InvalidFile:
3495 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003496 case CXCursor_InvalidCode:
3497 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003498 case CXCursor_NoDeclFound:
3499 return createCXString("NoDeclFound");
3500 case CXCursor_NotImplemented:
3501 return createCXString("NotImplemented");
3502 case CXCursor_TranslationUnit:
3503 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003504 case CXCursor_UnexposedAttr:
3505 return createCXString("UnexposedAttr");
3506 case CXCursor_IBActionAttr:
3507 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003508 case CXCursor_IBOutletAttr:
3509 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003510 case CXCursor_IBOutletCollectionAttr:
3511 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003512 case CXCursor_CXXFinalAttr:
3513 return createCXString("attribute(final)");
3514 case CXCursor_CXXOverrideAttr:
3515 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003516 case CXCursor_AnnotateAttr:
3517 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003518 case CXCursor_PreprocessingDirective:
3519 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003520 case CXCursor_MacroDefinition:
3521 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003522 case CXCursor_MacroExpansion:
3523 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003524 case CXCursor_InclusionDirective:
3525 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003526 case CXCursor_Namespace:
3527 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003528 case CXCursor_LinkageSpec:
3529 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003530 case CXCursor_CXXBaseSpecifier:
3531 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003532 case CXCursor_Constructor:
3533 return createCXString("CXXConstructor");
3534 case CXCursor_Destructor:
3535 return createCXString("CXXDestructor");
3536 case CXCursor_ConversionFunction:
3537 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003538 case CXCursor_TemplateTypeParameter:
3539 return createCXString("TemplateTypeParameter");
3540 case CXCursor_NonTypeTemplateParameter:
3541 return createCXString("NonTypeTemplateParameter");
3542 case CXCursor_TemplateTemplateParameter:
3543 return createCXString("TemplateTemplateParameter");
3544 case CXCursor_FunctionTemplate:
3545 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003546 case CXCursor_ClassTemplate:
3547 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003548 case CXCursor_ClassTemplatePartialSpecialization:
3549 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003550 case CXCursor_NamespaceAlias:
3551 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003552 case CXCursor_UsingDirective:
3553 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003554 case CXCursor_UsingDeclaration:
3555 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003556 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003557 return createCXString("TypeAliasDecl");
3558 case CXCursor_ObjCSynthesizeDecl:
3559 return createCXString("ObjCSynthesizeDecl");
3560 case CXCursor_ObjCDynamicDecl:
3561 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003562 case CXCursor_CXXAccessSpecifier:
3563 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003564 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003565
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003566 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003567 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003568}
Steve Naroff89922f82009-08-31 00:59:03 +00003569
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003570struct GetCursorData {
3571 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003572 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003573 CXCursor &BestCursor;
3574
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003575 GetCursorData(SourceManager &SM,
3576 SourceLocation tokenBegin, CXCursor &outputCursor)
3577 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3578 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3579 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003580};
3581
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003582static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3583 CXCursor parent,
3584 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003585 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3586 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003587
3588 // If we point inside a macro argument we should provide info of what the
3589 // token is so use the actual cursor, don't replace it with a macro expansion
3590 // cursor.
3591 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3592 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003593
3594 if (clang_isDeclaration(cursor.kind)) {
3595 // Avoid having the implicit methods override the property decls.
3596 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3597 if (MD->isImplicit())
3598 return CXChildVisit_Break;
3599 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003600
3601 if (clang_isExpression(cursor.kind) &&
3602 clang_isDeclaration(BestCursor->kind)) {
3603 Decl *D = getCursorDecl(*BestCursor);
3604
3605 // Avoid having the cursor of an expression replace the declaration cursor
3606 // when the expression source range overlaps the declaration range.
3607 // This can happen for C++ constructor expressions whose range generally
3608 // include the variable declaration, e.g.:
3609 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3610 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3611 D->getLocation() == Data->TokenBeginLoc)
3612 return CXChildVisit_Break;
3613 }
3614
Douglas Gregor93798e22010-11-05 21:11:19 +00003615 // If our current best cursor is the construction of a temporary object,
3616 // don't replace that cursor with a type reference, because we want
3617 // clang_getCursor() to point at the constructor.
3618 if (clang_isExpression(BestCursor->kind) &&
3619 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003620 cursor.kind == CXCursor_TypeRef) {
3621 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3622 // as having the actual point on the type reference.
3623 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003624 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003625 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003626
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003627 *BestCursor = cursor;
3628 return CXChildVisit_Recurse;
3629}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003630
Douglas Gregorb9790342010-01-22 21:44:22 +00003631CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3632 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003633 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003634
Ted Kremeneka60ed472010-11-16 08:15:36 +00003635 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003636 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3637
Ted Kremeneka297de22010-01-25 22:34:44 +00003638 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003639 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003640
Douglas Gregor40749ee2010-11-03 00:35:38 +00003641 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003642 if (Logging) {
3643 CXFile SearchFile;
3644 unsigned SearchLine, SearchColumn;
3645 CXFile ResultFile;
3646 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003647 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3648 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003649 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3650
Chandler Carruth20174222011-08-31 16:53:37 +00003651 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3652 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3653 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003654 SearchFileName = clang_getFileName(SearchFile);
3655 ResultFileName = clang_getFileName(ResultFile);
3656 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003657 USR = clang_getCursorUSR(Result);
3658 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003659 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3660 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003661 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3662 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003663 clang_disposeString(SearchFileName);
3664 clang_disposeString(ResultFileName);
3665 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003666 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003667
3668 CXCursor Definition = clang_getCursorDefinition(Result);
3669 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3670 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3671 CXString DefinitionKindSpelling
3672 = clang_getCursorKindSpelling(Definition.kind);
3673 CXFile DefinitionFile;
3674 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003675 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3676 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003677 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3678 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3679 clang_getCString(DefinitionKindSpelling),
3680 clang_getCString(DefinitionFileName),
3681 DefinitionLine, DefinitionColumn);
3682 clang_disposeString(DefinitionFileName);
3683 clang_disposeString(DefinitionKindSpelling);
3684 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003685 }
3686
Ted Kremeneke68fff62010-02-17 00:41:32 +00003687 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003688}
3689
Ted Kremenek73885552009-11-17 19:28:59 +00003690CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003691 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003692}
3693
3694unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003695 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003696}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003697
Douglas Gregor9ce55842010-11-20 00:09:34 +00003698unsigned clang_hashCursor(CXCursor C) {
3699 unsigned Index = 0;
3700 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3701 Index = 1;
3702
3703 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3704 std::make_pair(C.kind, C.data[Index]));
3705}
3706
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003707unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003708 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3709}
3710
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003711unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003712 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3713}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003714
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003715unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003716 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3717}
3718
Douglas Gregor97b98722010-01-19 23:20:36 +00003719unsigned clang_isExpression(enum CXCursorKind K) {
3720 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3721}
3722
3723unsigned clang_isStatement(enum CXCursorKind K) {
3724 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3725}
3726
Douglas Gregor8be80e12011-07-06 03:00:34 +00003727unsigned clang_isAttribute(enum CXCursorKind K) {
3728 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3729}
3730
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003731unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3732 return K == CXCursor_TranslationUnit;
3733}
3734
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003735unsigned clang_isPreprocessing(enum CXCursorKind K) {
3736 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3737}
3738
Ted Kremenekad6eff62010-03-08 21:17:29 +00003739unsigned clang_isUnexposed(enum CXCursorKind K) {
3740 switch (K) {
3741 case CXCursor_UnexposedDecl:
3742 case CXCursor_UnexposedExpr:
3743 case CXCursor_UnexposedStmt:
3744 case CXCursor_UnexposedAttr:
3745 return true;
3746 default:
3747 return false;
3748 }
3749}
3750
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003751CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003752 return C.kind;
3753}
3754
Douglas Gregor98258af2010-01-18 22:46:11 +00003755CXSourceLocation clang_getCursorLocation(CXCursor C) {
3756 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003757 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003758 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003759 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3760 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003761 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003762 }
3763
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003764 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003765 std::pair<ObjCProtocolDecl *, SourceLocation> P
3766 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003767 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003768 }
3769
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003770 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003771 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3772 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003773 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003774 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003775
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003776 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003777 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003778 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003779 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003780
3781 case CXCursor_TemplateRef: {
3782 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3783 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3784 }
3785
Douglas Gregor69319002010-08-31 23:48:11 +00003786 case CXCursor_NamespaceRef: {
3787 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3788 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3789 }
3790
Douglas Gregora67e03f2010-09-09 21:42:20 +00003791 case CXCursor_MemberRef: {
3792 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3793 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3794 }
3795
Ted Kremenek3064ef92010-08-27 21:34:58 +00003796 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003797 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3798 if (!BaseSpec)
3799 return clang_getNullLocation();
3800
3801 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3802 return cxloc::translateSourceLocation(getCursorContext(C),
3803 TSInfo->getTypeLoc().getBeginLoc());
3804
3805 return cxloc::translateSourceLocation(getCursorContext(C),
3806 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003807 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003808
Douglas Gregor36897b02010-09-10 00:22:18 +00003809 case CXCursor_LabelRef: {
3810 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3811 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3812 }
3813
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003814 case CXCursor_OverloadedDeclRef:
3815 return cxloc::translateSourceLocation(getCursorContext(C),
3816 getCursorOverloadedDeclRef(C).second);
3817
Douglas Gregorf46034a2010-01-18 23:41:10 +00003818 default:
3819 // FIXME: Need a way to enumerate all non-reference cases.
3820 llvm_unreachable("Missed a reference kind");
3821 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003822 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003823
3824 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003825 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003826 getLocationFromExpr(getCursorExpr(C)));
3827
Douglas Gregor36897b02010-09-10 00:22:18 +00003828 if (clang_isStatement(C.kind))
3829 return cxloc::translateSourceLocation(getCursorContext(C),
3830 getCursorStmt(C)->getLocStart());
3831
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003832 if (C.kind == CXCursor_PreprocessingDirective) {
3833 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3834 return cxloc::translateSourceLocation(getCursorContext(C), L);
3835 }
Douglas Gregor48072312010-03-18 15:23:44 +00003836
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003837 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003838 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003839 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003840 return cxloc::translateSourceLocation(getCursorContext(C), L);
3841 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003842
3843 if (C.kind == CXCursor_MacroDefinition) {
3844 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3845 return cxloc::translateSourceLocation(getCursorContext(C), L);
3846 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003847
3848 if (C.kind == CXCursor_InclusionDirective) {
3849 SourceLocation L
3850 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3851 return cxloc::translateSourceLocation(getCursorContext(C), L);
3852 }
3853
Ted Kremenek9a700d22010-05-12 06:16:13 +00003854 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003855 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003856
Douglas Gregorf46034a2010-01-18 23:41:10 +00003857 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003858 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003859 // FIXME: Multiple variables declared in a single declaration
3860 // currently lack the information needed to correctly determine their
3861 // ranges when accounting for the type-specifier. We use context
3862 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3863 // and if so, whether it is the first decl.
3864 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3865 if (!cxcursor::isFirstInDeclGroup(C))
3866 Loc = VD->getLocation();
3867 }
3868
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003869 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003870}
Douglas Gregora7bde202010-01-19 00:34:46 +00003871
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003872} // end extern "C"
3873
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003874CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3875 assert(TU);
3876
3877 // Guard against an invalid SourceLocation, or we may assert in one
3878 // of the following calls.
3879 if (SLoc.isInvalid())
3880 return clang_getNullCursor();
3881
3882 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3883
3884 // Translate the given source location to make it point at the beginning of
3885 // the token under the cursor.
3886 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3887 CXXUnit->getASTContext().getLangOptions());
3888
3889 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3890 if (SLoc.isValid()) {
3891 // FIXME: Would be great to have a "hint" cursor, then walk from that
3892 // hint cursor upward until we find a cursor whose source range encloses
3893 // the region of interest, rather than starting from the translation unit.
3894 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
3895 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3896 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3897 /*VisitPreprocessorLast=*/true,
3898 SourceLocation(SLoc));
3899 CursorVis.VisitChildren(Parent);
3900 }
3901
3902 return Result;
3903}
3904
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003905static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003906 if (clang_isReference(C.kind)) {
3907 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003908 case CXCursor_ObjCSuperClassRef:
3909 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003910
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003911 case CXCursor_ObjCProtocolRef:
3912 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003913
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003914 case CXCursor_ObjCClassRef:
3915 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003916
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003917 case CXCursor_TypeRef:
3918 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003919
3920 case CXCursor_TemplateRef:
3921 return getCursorTemplateRef(C).second;
3922
Douglas Gregor69319002010-08-31 23:48:11 +00003923 case CXCursor_NamespaceRef:
3924 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003925
3926 case CXCursor_MemberRef:
3927 return getCursorMemberRef(C).second;
3928
Ted Kremenek3064ef92010-08-27 21:34:58 +00003929 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003930 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003931
Douglas Gregor36897b02010-09-10 00:22:18 +00003932 case CXCursor_LabelRef:
3933 return getCursorLabelRef(C).second;
3934
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003935 case CXCursor_OverloadedDeclRef:
3936 return getCursorOverloadedDeclRef(C).second;
3937
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003938 default:
3939 // FIXME: Need a way to enumerate all non-reference cases.
3940 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003941 }
3942 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003943
3944 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003945 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003946
3947 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003948 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003949
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003950 if (clang_isAttribute(C.kind))
3951 return getCursorAttr(C)->getRange();
3952
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003953 if (C.kind == CXCursor_PreprocessingDirective)
3954 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003955
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003956 if (C.kind == CXCursor_MacroExpansion) {
3957 ASTUnit *TU = getCursorASTUnit(C);
3958 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3959 return TU->mapRangeFromPreamble(Range);
3960 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003961
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003962 if (C.kind == CXCursor_MacroDefinition) {
3963 ASTUnit *TU = getCursorASTUnit(C);
3964 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3965 return TU->mapRangeFromPreamble(Range);
3966 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003967
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003968 if (C.kind == CXCursor_InclusionDirective) {
3969 ASTUnit *TU = getCursorASTUnit(C);
3970 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3971 return TU->mapRangeFromPreamble(Range);
3972 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003973
Ted Kremenek007a7c92010-11-01 23:26:51 +00003974 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3975 Decl *D = cxcursor::getCursorDecl(C);
3976 SourceRange R = D->getSourceRange();
3977 // FIXME: Multiple variables declared in a single declaration
3978 // currently lack the information needed to correctly determine their
3979 // ranges when accounting for the type-specifier. We use context
3980 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3981 // and if so, whether it is the first decl.
3982 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3983 if (!cxcursor::isFirstInDeclGroup(C))
3984 R.setBegin(VD->getLocation());
3985 }
3986 return R;
3987 }
Douglas Gregor66537982010-11-17 17:14:07 +00003988 return SourceRange();
3989}
3990
3991/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3992/// the decl-specifier-seq for declarations.
3993static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3994 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3995 Decl *D = cxcursor::getCursorDecl(C);
3996 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003997
Douglas Gregor2494dd02011-03-01 01:34:45 +00003998 // Adjust the start of the location for declarations preceded by
3999 // declaration specifiers.
4000 SourceLocation StartLoc;
4001 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4002 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4003 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4004 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4005 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4006 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4007 }
4008
4009 if (StartLoc.isValid() && R.getBegin().isValid() &&
4010 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4011 R.setBegin(StartLoc);
4012
4013 // FIXME: Multiple variables declared in a single declaration
4014 // currently lack the information needed to correctly determine their
4015 // ranges when accounting for the type-specifier. We use context
4016 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4017 // and if so, whether it is the first decl.
4018 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4019 if (!cxcursor::isFirstInDeclGroup(C))
4020 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004021 }
4022
4023 return R;
4024 }
4025
4026 return getRawCursorExtent(C);
4027}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004028
4029extern "C" {
4030
4031CXSourceRange clang_getCursorExtent(CXCursor C) {
4032 SourceRange R = getRawCursorExtent(C);
4033 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004034 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004035
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004036 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004037}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004038
4039CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004040 if (clang_isInvalid(C.kind))
4041 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004042
Ted Kremeneka60ed472010-11-16 08:15:36 +00004043 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004044 if (clang_isDeclaration(C.kind)) {
4045 Decl *D = getCursorDecl(C);
4046 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004047 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004048 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004049 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004050 if (ObjCForwardProtocolDecl *Protocols
4051 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004052 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004053 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004054 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4055 return MakeCXCursor(Property, tu);
4056
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004057 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004058 }
4059
Douglas Gregor97b98722010-01-19 23:20:36 +00004060 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004061 Expr *E = getCursorExpr(C);
4062 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004063 if (D) {
4064 CXCursor declCursor = MakeCXCursor(D, tu);
4065 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4066 declCursor);
4067 return declCursor;
4068 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004069
4070 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004071 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004072
Douglas Gregor97b98722010-01-19 23:20:36 +00004073 return clang_getNullCursor();
4074 }
4075
Douglas Gregor36897b02010-09-10 00:22:18 +00004076 if (clang_isStatement(C.kind)) {
4077 Stmt *S = getCursorStmt(C);
4078 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004079 if (LabelDecl *label = Goto->getLabel())
4080 if (LabelStmt *labelS = label->getStmt())
4081 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004082
4083 return clang_getNullCursor();
4084 }
4085
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004086 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004087 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004088 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004089 }
4090
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004091 if (!clang_isReference(C.kind))
4092 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004093
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004094 switch (C.kind) {
4095 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004096 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004097
4098 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004099 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004100
4101 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004102 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004103
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004104 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004105 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004106
4107 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004108 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004109
Douglas Gregor69319002010-08-31 23:48:11 +00004110 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004111 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004112
Douglas Gregora67e03f2010-09-09 21:42:20 +00004113 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004115
Ted Kremenek3064ef92010-08-27 21:34:58 +00004116 case CXCursor_CXXBaseSpecifier: {
4117 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4118 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004119 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004120 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004121
Douglas Gregor36897b02010-09-10 00:22:18 +00004122 case CXCursor_LabelRef:
4123 // FIXME: We end up faking the "parent" declaration here because we
4124 // don't want to make CXCursor larger.
4125 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004126 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4127 .getTranslationUnitDecl(),
4128 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004129
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004130 case CXCursor_OverloadedDeclRef:
4131 return C;
4132
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004133 default:
4134 // We would prefer to enumerate all non-reference cursor kinds here.
4135 llvm_unreachable("Unhandled reference cursor kind");
4136 break;
4137 }
4138 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004139
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004140 return clang_getNullCursor();
4141}
4142
Douglas Gregorb6998662010-01-19 19:34:47 +00004143CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004144 if (clang_isInvalid(C.kind))
4145 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004146
Ted Kremeneka60ed472010-11-16 08:15:36 +00004147 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004148
Douglas Gregorb6998662010-01-19 19:34:47 +00004149 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004150 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004151 C = clang_getCursorReferenced(C);
4152 WasReference = true;
4153 }
4154
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004155 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004156 return clang_getCursorReferenced(C);
4157
Douglas Gregorb6998662010-01-19 19:34:47 +00004158 if (!clang_isDeclaration(C.kind))
4159 return clang_getNullCursor();
4160
4161 Decl *D = getCursorDecl(C);
4162 if (!D)
4163 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004164
Douglas Gregorb6998662010-01-19 19:34:47 +00004165 switch (D->getKind()) {
4166 // Declaration kinds that don't really separate the notions of
4167 // declaration and definition.
4168 case Decl::Namespace:
4169 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004170 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004171 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004172 case Decl::TemplateTypeParm:
4173 case Decl::EnumConstant:
4174 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004175 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004176 case Decl::ObjCIvar:
4177 case Decl::ObjCAtDefsField:
4178 case Decl::ImplicitParam:
4179 case Decl::ParmVar:
4180 case Decl::NonTypeTemplateParm:
4181 case Decl::TemplateTemplateParm:
4182 case Decl::ObjCCategoryImpl:
4183 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004184 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004185 case Decl::LinkageSpec:
4186 case Decl::ObjCPropertyImpl:
4187 case Decl::FileScopeAsm:
4188 case Decl::StaticAssert:
4189 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004190 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004191 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004192 return C;
4193
4194 // Declaration kinds that don't make any sense here, but are
4195 // nonetheless harmless.
4196 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004197 break;
4198
4199 // Declaration kinds for which the definition is not resolvable.
4200 case Decl::UnresolvedUsingTypename:
4201 case Decl::UnresolvedUsingValue:
4202 break;
4203
4204 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004205 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004206 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004207
4208 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004209 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004210
4211 case Decl::Enum:
4212 case Decl::Record:
4213 case Decl::CXXRecord:
4214 case Decl::ClassTemplateSpecialization:
4215 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004216 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004217 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004218 return clang_getNullCursor();
4219
4220 case Decl::Function:
4221 case Decl::CXXMethod:
4222 case Decl::CXXConstructor:
4223 case Decl::CXXDestructor:
4224 case Decl::CXXConversion: {
4225 const FunctionDecl *Def = 0;
4226 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004227 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004228 return clang_getNullCursor();
4229 }
4230
4231 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004232 // Ask the variable if it has a definition.
4233 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004234 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004235 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004236 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004237
Douglas Gregorb6998662010-01-19 19:34:47 +00004238 case Decl::FunctionTemplate: {
4239 const FunctionDecl *Def = 0;
4240 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004241 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004242 return clang_getNullCursor();
4243 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004244
Douglas Gregorb6998662010-01-19 19:34:47 +00004245 case Decl::ClassTemplate: {
4246 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004247 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004248 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004249 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004250 return clang_getNullCursor();
4251 }
4252
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004253 case Decl::Using:
4254 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004255 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004256
4257 case Decl::UsingShadow:
4258 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004259 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004260 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004261
4262 case Decl::ObjCMethod: {
4263 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4264 if (Method->isThisDeclarationADefinition())
4265 return C;
4266
4267 // Dig out the method definition in the associated
4268 // @implementation, if we have it.
4269 // FIXME: The ASTs should make finding the definition easier.
4270 if (ObjCInterfaceDecl *Class
4271 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4272 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4273 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4274 Method->isInstanceMethod()))
4275 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004276 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004277
4278 return clang_getNullCursor();
4279 }
4280
4281 case Decl::ObjCCategory:
4282 if (ObjCCategoryImplDecl *Impl
4283 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004284 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004285 return clang_getNullCursor();
4286
4287 case Decl::ObjCProtocol:
4288 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4289 return C;
4290 return clang_getNullCursor();
4291
4292 case Decl::ObjCInterface:
4293 // There are two notions of a "definition" for an Objective-C
4294 // class: the interface and its implementation. When we resolved a
4295 // reference to an Objective-C class, produce the @interface as
4296 // the definition; when we were provided with the interface,
4297 // produce the @implementation as the definition.
4298 if (WasReference) {
4299 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4300 return C;
4301 } else if (ObjCImplementationDecl *Impl
4302 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004303 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004304 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004305
Douglas Gregorb6998662010-01-19 19:34:47 +00004306 case Decl::ObjCProperty:
4307 // FIXME: We don't really know where to find the
4308 // ObjCPropertyImplDecls that implement this property.
4309 return clang_getNullCursor();
4310
4311 case Decl::ObjCCompatibleAlias:
4312 if (ObjCInterfaceDecl *Class
4313 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4314 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004315 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004316
Douglas Gregorb6998662010-01-19 19:34:47 +00004317 return clang_getNullCursor();
4318
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004319 case Decl::ObjCForwardProtocol:
4320 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004321 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004322
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004323 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004324 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004325 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004326
4327 case Decl::Friend:
4328 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004329 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004330 return clang_getNullCursor();
4331
4332 case Decl::FriendTemplate:
4333 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004334 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004335 return clang_getNullCursor();
4336 }
4337
4338 return clang_getNullCursor();
4339}
4340
4341unsigned clang_isCursorDefinition(CXCursor C) {
4342 if (!clang_isDeclaration(C.kind))
4343 return 0;
4344
4345 return clang_getCursorDefinition(C) == C;
4346}
4347
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004348CXCursor clang_getCanonicalCursor(CXCursor C) {
4349 if (!clang_isDeclaration(C.kind))
4350 return C;
4351
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004352 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004353 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4354 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4355 return MakeCXCursor(CatD, getCursorTU(C));
4356
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004357 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4358 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4359 return MakeCXCursor(IFD, getCursorTU(C));
4360
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004361 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004362 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004363
4364 return C;
4365}
4366
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004367unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004368 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004369 return 0;
4370
4371 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4372 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4373 return E->getNumDecls();
4374
4375 if (OverloadedTemplateStorage *S
4376 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4377 return S->size();
4378
4379 Decl *D = Storage.get<Decl*>();
4380 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004381 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004382 if (isa<ObjCClassDecl>(D))
4383 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004384 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4385 return Protocols->protocol_size();
4386
4387 return 0;
4388}
4389
4390CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004391 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004392 return clang_getNullCursor();
4393
4394 if (index >= clang_getNumOverloadedDecls(cursor))
4395 return clang_getNullCursor();
4396
Ted Kremeneka60ed472010-11-16 08:15:36 +00004397 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004398 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4399 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004400 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004401
4402 if (OverloadedTemplateStorage *S
4403 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004404 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004405
4406 Decl *D = Storage.get<Decl*>();
4407 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4408 // FIXME: This is, unfortunately, linear time.
4409 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4410 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004411 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004412 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004413 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004414 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004415 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004416 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004417
4418 return clang_getNullCursor();
4419}
4420
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004421void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004422 const char **startBuf,
4423 const char **endBuf,
4424 unsigned *startLine,
4425 unsigned *startColumn,
4426 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004427 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004428 assert(getCursorDecl(C) && "CXCursor has null decl");
4429 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004430 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4431 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004432
Steve Naroff4ade6d62009-09-23 17:52:52 +00004433 SourceManager &SM = FD->getASTContext().getSourceManager();
4434 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4435 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4436 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4437 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4438 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4439 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4440}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004441
Douglas Gregor430d7a12011-07-25 17:48:11 +00004442
4443CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4444 unsigned PieceIndex) {
4445 RefNamePieces Pieces;
4446
4447 switch (C.kind) {
4448 case CXCursor_MemberRefExpr:
4449 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4450 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4451 E->getQualifierLoc().getSourceRange());
4452 break;
4453
4454 case CXCursor_DeclRefExpr:
4455 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4456 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4457 E->getQualifierLoc().getSourceRange(),
4458 E->getExplicitTemplateArgsOpt());
4459 break;
4460
4461 case CXCursor_CallExpr:
4462 if (CXXOperatorCallExpr *OCE =
4463 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4464 Expr *Callee = OCE->getCallee();
4465 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4466 Callee = ICE->getSubExpr();
4467
4468 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4469 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4470 DRE->getQualifierLoc().getSourceRange());
4471 }
4472 break;
4473
4474 default:
4475 break;
4476 }
4477
4478 if (Pieces.empty()) {
4479 if (PieceIndex == 0)
4480 return clang_getCursorExtent(C);
4481 } else if (PieceIndex < Pieces.size()) {
4482 SourceRange R = Pieces[PieceIndex];
4483 if (R.isValid())
4484 return cxloc::translateSourceRange(getCursorContext(C), R);
4485 }
4486
4487 return clang_getNullRange();
4488}
4489
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004490void clang_enableStackTraces(void) {
4491 llvm::sys::PrintStackTraceOnErrorSignal();
4492}
4493
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004494void clang_executeOnThread(void (*fn)(void*), void *user_data,
4495 unsigned stack_size) {
4496 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4497}
4498
Ted Kremenekfb480492010-01-13 21:46:36 +00004499} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004500
Ted Kremenekfb480492010-01-13 21:46:36 +00004501//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004502// Token-based Operations.
4503//===----------------------------------------------------------------------===//
4504
4505/* CXToken layout:
4506 * int_data[0]: a CXTokenKind
4507 * int_data[1]: starting token location
4508 * int_data[2]: token length
4509 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004510 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004511 * otherwise unused.
4512 */
4513extern "C" {
4514
4515CXTokenKind clang_getTokenKind(CXToken CXTok) {
4516 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4517}
4518
4519CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4520 switch (clang_getTokenKind(CXTok)) {
4521 case CXToken_Identifier:
4522 case CXToken_Keyword:
4523 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004524 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4525 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004526
4527 case CXToken_Literal: {
4528 // We have stashed the starting pointer in the ptr_data field. Use it.
4529 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004530 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004531 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004532
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004533 case CXToken_Punctuation:
4534 case CXToken_Comment:
4535 break;
4536 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004537
4538 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004539 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004540 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004541 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004542 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004543
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004544 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4545 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004546 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004547 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004548 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004549 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4550 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004551 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004552
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004553 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004554}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004555
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004556CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004557 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004558 if (!CXXUnit)
4559 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004560
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004561 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4562 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4563}
4564
4565CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004566 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004567 if (!CXXUnit)
4568 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004569
4570 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004571 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4572}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004573
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004574static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4575 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004576 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4577 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004578 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004579 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004580 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004581
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004582 // Cannot tokenize across files.
4583 if (BeginLocInfo.first != EndLocInfo.first)
4584 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004585
4586 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004587 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004588 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004589 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004590 if (Invalid)
4591 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004592
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004593 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4594 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004595 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004596 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004597
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004598 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004599 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004600 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004601 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004602 do {
4603 // Lex the next token
4604 Lex.LexFromRawLexer(Tok);
4605 if (Tok.is(tok::eof))
4606 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004607
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004608 // Initialize the CXToken.
4609 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004610
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004611 // - Common fields
4612 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4613 CXTok.int_data[2] = Tok.getLength();
4614 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004615
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004616 // - Kind-specific fields
4617 if (Tok.isLiteral()) {
4618 CXTok.int_data[0] = CXToken_Literal;
4619 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004620 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004621 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004622 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004623 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004624
David Chisnall096428b2010-10-13 21:44:48 +00004625 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004626 CXTok.int_data[0] = CXToken_Keyword;
4627 }
4628 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004629 CXTok.int_data[0] = Tok.is(tok::identifier)
4630 ? CXToken_Identifier
4631 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004632 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004633 CXTok.ptr_data = II;
4634 } else if (Tok.is(tok::comment)) {
4635 CXTok.int_data[0] = CXToken_Comment;
4636 CXTok.ptr_data = 0;
4637 } else {
4638 CXTok.int_data[0] = CXToken_Punctuation;
4639 CXTok.ptr_data = 0;
4640 }
4641 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004642 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004643 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004644}
4645
4646void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4647 CXToken **Tokens, unsigned *NumTokens) {
4648 if (Tokens)
4649 *Tokens = 0;
4650 if (NumTokens)
4651 *NumTokens = 0;
4652
4653 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4654 if (!CXXUnit || !Tokens || !NumTokens)
4655 return;
4656
4657 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4658
4659 SourceRange R = cxloc::translateCXSourceRange(Range);
4660 if (R.isInvalid())
4661 return;
4662
4663 SmallVector<CXToken, 32> CXTokens;
4664 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004665
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004666 if (CXTokens.empty())
4667 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004668
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004669 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4670 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4671 *NumTokens = CXTokens.size();
4672}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004673
Ted Kremenek6db61092010-05-05 00:55:15 +00004674void clang_disposeTokens(CXTranslationUnit TU,
4675 CXToken *Tokens, unsigned NumTokens) {
4676 free(Tokens);
4677}
4678
4679} // end: extern "C"
4680
4681//===----------------------------------------------------------------------===//
4682// Token annotation APIs.
4683//===----------------------------------------------------------------------===//
4684
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004685typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004686static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4687 CXCursor parent,
4688 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004689namespace {
4690class AnnotateTokensWorker {
4691 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004692 CXToken *Tokens;
4693 CXCursor *Cursors;
4694 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004695 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004696 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004697 CursorVisitor AnnotateVis;
4698 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004699 bool HasContextSensitiveKeywords;
4700
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004701 bool MoreTokens() const { return TokIdx < NumTokens; }
4702 unsigned NextToken() const { return TokIdx; }
4703 void AdvanceToken() { ++TokIdx; }
4704 SourceLocation GetTokenLoc(unsigned tokI) {
4705 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4706 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004707 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004708 return Tokens[tokI].int_data[3] != 0;
4709 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004710 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004711 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4712 }
4713
4714 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004715 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4716 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004717
Ted Kremenek6db61092010-05-05 00:55:15 +00004718public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004719 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004720 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004721 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004722 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004723 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004724 AnnotateVis(tu,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00004725 AnnotateTokensVisitor, this, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004726 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4727 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004728
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004729 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004730 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004731 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004732 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004733 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004734 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004735
4736 /// \brief Determine whether the annotator saw any cursors that have
4737 /// context-sensitive keywords.
4738 bool hasContextSensitiveKeywords() const {
4739 return HasContextSensitiveKeywords;
4740 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004741};
4742}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004743
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004744void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4745 // Walk the AST within the region of interest, annotating tokens
4746 // along the way.
4747 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004748
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004749 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4750 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004751 if (Pos != Annotated.end() &&
4752 (clang_isInvalid(Cursors[I].kind) ||
4753 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004754 Cursors[I] = Pos->second;
4755 }
4756
4757 // Finish up annotating any tokens left.
4758 if (!MoreTokens())
4759 return;
4760
4761 const CXCursor &C = clang_getNullCursor();
4762 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4763 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4764 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004765 }
4766}
4767
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004768/// \brief It annotates and advances tokens with a cursor until the comparison
4769//// between the cursor location and the source range is the same as
4770/// \arg compResult.
4771///
4772/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4773/// Pass RangeOverlap to annotate tokens inside a range.
4774void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4775 RangeComparisonResult compResult,
4776 SourceRange range) {
4777 while (MoreTokens()) {
4778 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004779 if (isFunctionMacroToken(I))
4780 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004781
4782 SourceLocation TokLoc = GetTokenLoc(I);
4783 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4784 Cursors[I] = updateC;
4785 AdvanceToken();
4786 continue;
4787 }
4788 break;
4789 }
4790}
4791
4792/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004793void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4794 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004795 RangeComparisonResult compResult,
4796 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004797 assert(MoreTokens());
4798 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004799 "Should be called only for macro arg tokens");
4800
4801 // This works differently than annotateAndAdvanceTokens; because expanded
4802 // macro arguments can have arbitrary translation-unit source order, we do not
4803 // advance the token index one by one until a token fails the range test.
4804 // We only advance once past all of the macro arg tokens if all of them
4805 // pass the range test. If one of them fails we keep the token index pointing
4806 // at the start of the macro arg tokens so that the failing token will be
4807 // annotated by a subsequent annotation try.
4808
4809 bool atLeastOneCompFail = false;
4810
4811 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004812 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4813 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004814 if (TokLoc.isFileID())
4815 continue; // not macro arg token, it's parens or comma.
4816 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4817 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4818 Cursors[I] = updateC;
4819 } else
4820 atLeastOneCompFail = true;
4821 }
4822
4823 if (!atLeastOneCompFail)
4824 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4825}
4826
Ted Kremenek6db61092010-05-05 00:55:15 +00004827enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004828AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004829 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004830 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004831 if (cursorRange.isInvalid())
4832 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004833
4834 if (!HasContextSensitiveKeywords) {
4835 // Objective-C properties can have context-sensitive keywords.
4836 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4837 if (ObjCPropertyDecl *Property
4838 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4839 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4840 }
4841 // Objective-C methods can have context-sensitive keywords.
4842 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4843 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4844 if (ObjCMethodDecl *Method
4845 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4846 if (Method->getObjCDeclQualifier())
4847 HasContextSensitiveKeywords = true;
4848 else {
4849 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4850 PEnd = Method->param_end();
4851 P != PEnd; ++P) {
4852 if ((*P)->getObjCDeclQualifier()) {
4853 HasContextSensitiveKeywords = true;
4854 break;
4855 }
4856 }
4857 }
4858 }
4859 }
4860 // C++ methods can have context-sensitive keywords.
4861 else if (cursor.kind == CXCursor_CXXMethod) {
4862 if (CXXMethodDecl *Method
4863 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4864 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4865 HasContextSensitiveKeywords = true;
4866 }
4867 }
4868 // C++ classes can have context-sensitive keywords.
4869 else if (cursor.kind == CXCursor_StructDecl ||
4870 cursor.kind == CXCursor_ClassDecl ||
4871 cursor.kind == CXCursor_ClassTemplate ||
4872 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4873 if (Decl *D = getCursorDecl(cursor))
4874 if (D->hasAttr<FinalAttr>())
4875 HasContextSensitiveKeywords = true;
4876 }
4877 }
4878
Douglas Gregor4419b672010-10-21 06:10:04 +00004879 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004880 // For macro expansions, just note where the beginning of the macro
4881 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004882 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004883 Annotated[Loc.int_data] = cursor;
4884 return CXChildVisit_Recurse;
4885 }
4886
Douglas Gregor4419b672010-10-21 06:10:04 +00004887 // Items in the preprocessing record are kept separate from items in
4888 // declarations, so we keep a separate token index.
4889 unsigned SavedTokIdx = TokIdx;
4890 TokIdx = PreprocessingTokIdx;
4891
4892 // Skip tokens up until we catch up to the beginning of the preprocessing
4893 // entry.
4894 while (MoreTokens()) {
4895 const unsigned I = NextToken();
4896 SourceLocation TokLoc = GetTokenLoc(I);
4897 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4898 case RangeBefore:
4899 AdvanceToken();
4900 continue;
4901 case RangeAfter:
4902 case RangeOverlap:
4903 break;
4904 }
4905 break;
4906 }
4907
4908 // Look at all of the tokens within this range.
4909 while (MoreTokens()) {
4910 const unsigned I = NextToken();
4911 SourceLocation TokLoc = GetTokenLoc(I);
4912 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4913 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004914 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004915 case RangeAfter:
4916 break;
4917 case RangeOverlap:
4918 Cursors[I] = cursor;
4919 AdvanceToken();
4920 continue;
4921 }
4922 break;
4923 }
4924
4925 // Save the preprocessing token index; restore the non-preprocessing
4926 // token index.
4927 PreprocessingTokIdx = TokIdx;
4928 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004929 return CXChildVisit_Recurse;
4930 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004931
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004932 if (cursorRange.isInvalid())
4933 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004934
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004935 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4936
Ted Kremeneka333c662010-05-12 05:29:33 +00004937 // Adjust the annotated range based specific declarations.
4938 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4939 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004940 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004941
4942 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004943 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004944 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4945 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4946 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4947 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4948 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004949 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004950
4951 if (StartLoc.isValid() && L.isValid() &&
4952 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4953 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004954 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004955
Ted Kremenek3f404602010-08-14 01:14:06 +00004956 // If the location of the cursor occurs within a macro instantiation, record
4957 // the spelling location of the cursor in our annotation map. We can then
4958 // paper over the token labelings during a post-processing step to try and
4959 // get cursor mappings for tokens that are the *arguments* of a macro
4960 // instantiation.
4961 if (L.isMacroID()) {
4962 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4963 // Only invalidate the old annotation if it isn't part of a preprocessing
4964 // directive. Here we assume that the default construction of CXCursor
4965 // results in CXCursor.kind being an initialized value (i.e., 0). If
4966 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004967
Ted Kremenek3f404602010-08-14 01:14:06 +00004968 CXCursor &oldC = Annotated[rawEncoding];
4969 if (!clang_isPreprocessing(oldC.kind))
4970 oldC = cursor;
4971 }
4972
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004973 const enum CXCursorKind K = clang_getCursorKind(parent);
4974 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004975 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4976 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004977
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004978 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004979
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004980 // Avoid having the cursor of an expression "overwrite" the annotation of the
4981 // variable declaration that it belongs to.
4982 // This can happen for C++ constructor expressions whose range generally
4983 // include the variable declaration, e.g.:
4984 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4985 if (clang_isExpression(cursorK)) {
4986 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004987 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004988 const unsigned I = NextToken();
4989 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4990 E->getLocStart() == D->getLocation() &&
4991 E->getLocStart() == GetTokenLoc(I)) {
4992 Cursors[I] = updateC;
4993 AdvanceToken();
4994 }
4995 }
4996 }
4997
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004998 // Visit children to get their cursor information.
4999 const unsigned BeforeChildren = NextToken();
5000 VisitChildren(cursor);
5001 const unsigned AfterChildren = NextToken();
5002
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005003 // Scan the tokens that are at the end of the cursor, but are not captured
5004 // but the child cursors.
5005 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005006
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005007 // Scan the tokens that are at the beginning of the cursor, but are not
5008 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005009 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5010 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5011 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005012
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005013 Cursors[I] = cursor;
5014 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005015
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005016 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005017}
5018
Ted Kremenek6db61092010-05-05 00:55:15 +00005019static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5020 CXCursor parent,
5021 CXClientData client_data) {
5022 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5023}
5024
Ted Kremenek6628a612011-03-18 22:51:30 +00005025namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005026
5027/// \brief Uses the macro expansions in the preprocessing record to find
5028/// and mark tokens that are macro arguments. This info is used by the
5029/// AnnotateTokensWorker.
5030class MarkMacroArgTokensVisitor {
5031 SourceManager &SM;
5032 CXToken *Tokens;
5033 unsigned NumTokens;
5034 unsigned CurIdx;
5035
5036public:
5037 MarkMacroArgTokensVisitor(SourceManager &SM,
5038 CXToken *tokens, unsigned numTokens)
5039 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5040
5041 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5042 if (cursor.kind != CXCursor_MacroExpansion)
5043 return CXChildVisit_Continue;
5044
5045 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5046 if (macroRange.getBegin() == macroRange.getEnd())
5047 return CXChildVisit_Continue; // it's not a function macro.
5048
5049 for (; CurIdx < NumTokens; ++CurIdx) {
5050 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5051 macroRange.getBegin()))
5052 break;
5053 }
5054
5055 if (CurIdx == NumTokens)
5056 return CXChildVisit_Break;
5057
5058 for (; CurIdx < NumTokens; ++CurIdx) {
5059 SourceLocation tokLoc = getTokenLoc(CurIdx);
5060 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5061 break;
5062
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005063 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005064 }
5065
5066 if (CurIdx == NumTokens)
5067 return CXChildVisit_Break;
5068
5069 return CXChildVisit_Continue;
5070 }
5071
5072private:
5073 SourceLocation getTokenLoc(unsigned tokI) {
5074 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5075 }
5076
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005077 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005078 // The third field is reserved and currently not used. Use it here
5079 // to mark macro arg expanded tokens with their expanded locations.
5080 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5081 }
5082};
5083
5084} // end anonymous namespace
5085
5086static CXChildVisitResult
5087MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5088 CXClientData client_data) {
5089 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5090 parent);
5091}
5092
5093namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005094 struct clang_annotateTokens_Data {
5095 CXTranslationUnit TU;
5096 ASTUnit *CXXUnit;
5097 CXToken *Tokens;
5098 unsigned NumTokens;
5099 CXCursor *Cursors;
5100 };
5101}
5102
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005103static void annotatePreprocessorTokens(CXTranslationUnit TU,
5104 SourceRange RegionOfInterest,
5105 AnnotateTokensData &Annotated) {
5106 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5107
5108 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5109 std::pair<FileID, unsigned> BeginLocInfo
5110 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5111 std::pair<FileID, unsigned> EndLocInfo
5112 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5113
5114 if (BeginLocInfo.first != EndLocInfo.first)
5115 return;
5116
5117 StringRef Buffer;
5118 bool Invalid = false;
5119 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5120 if (Buffer.empty() || Invalid)
5121 return;
5122
5123 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5124 CXXUnit->getASTContext().getLangOptions(),
5125 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5126 Buffer.end());
5127 Lex.SetCommentRetentionState(true);
5128
5129 // Lex tokens in raw mode until we hit the end of the range, to avoid
5130 // entering #includes or expanding macros.
5131 while (true) {
5132 Token Tok;
5133 Lex.LexFromRawLexer(Tok);
5134
5135 reprocess:
5136 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5137 // We have found a preprocessing directive. Gobble it up so that we
5138 // don't see it while preprocessing these tokens later, but keep track
5139 // of all of the token locations inside this preprocessing directive so
5140 // that we can annotate them appropriately.
5141 //
5142 // FIXME: Some simple tests here could identify macro definitions and
5143 // #undefs, to provide specific cursor kinds for those.
5144 SmallVector<SourceLocation, 32> Locations;
5145 do {
5146 Locations.push_back(Tok.getLocation());
5147 Lex.LexFromRawLexer(Tok);
5148 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5149
5150 using namespace cxcursor;
5151 CXCursor Cursor
5152 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5153 Locations.back()),
5154 TU);
5155 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5156 Annotated[Locations[I].getRawEncoding()] = Cursor;
5157 }
5158
5159 if (Tok.isAtStartOfLine())
5160 goto reprocess;
5161
5162 continue;
5163 }
5164
5165 if (Tok.is(tok::eof))
5166 break;
5167 }
5168}
5169
Ted Kremenekab979612010-11-11 08:05:23 +00005170// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005171static void clang_annotateTokensImpl(void *UserData) {
5172 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5173 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5174 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5175 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5176 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5177
5178 // Determine the region of interest, which contains all of the tokens.
5179 SourceRange RegionOfInterest;
5180 RegionOfInterest.setBegin(
5181 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5182 RegionOfInterest.setEnd(
5183 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5184 Tokens[NumTokens-1])));
5185
5186 // A mapping from the source locations found when re-lexing or traversing the
5187 // region of interest to the corresponding cursors.
5188 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005189
Ted Kremenek6628a612011-03-18 22:51:30 +00005190 // Relex the tokens within the source range to look for preprocessing
5191 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005192 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005193
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005194 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5195 // Search and mark tokens that are macro argument expansions.
5196 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5197 Tokens, NumTokens);
5198 CursorVisitor MacroArgMarker(TU,
5199 MarkMacroArgTokensVisitorDelegate, &Visitor,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00005200 true, RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005201 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5202 }
5203
Ted Kremenek6628a612011-03-18 22:51:30 +00005204 // Annotate all of the source locations in the region of interest that map to
5205 // a specific cursor.
5206 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5207 TU, RegionOfInterest);
5208
5209 // FIXME: We use a ridiculous stack size here because the data-recursion
5210 // algorithm uses a large stack frame than the non-data recursive version,
5211 // and AnnotationTokensWorker currently transforms the data-recursion
5212 // algorithm back into a traditional recursion by explicitly calling
5213 // VisitChildren(). We will need to remove this explicit recursive call.
5214 W.AnnotateTokens();
5215
5216 // If we ran into any entities that involve context-sensitive keywords,
5217 // take another pass through the tokens to mark them as such.
5218 if (W.hasContextSensitiveKeywords()) {
5219 for (unsigned I = 0; I != NumTokens; ++I) {
5220 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5221 continue;
5222
5223 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5224 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5225 if (ObjCPropertyDecl *Property
5226 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5227 if (Property->getPropertyAttributesAsWritten() != 0 &&
5228 llvm::StringSwitch<bool>(II->getName())
5229 .Case("readonly", true)
5230 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005231 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005232 .Case("readwrite", true)
5233 .Case("retain", true)
5234 .Case("copy", true)
5235 .Case("nonatomic", true)
5236 .Case("atomic", true)
5237 .Case("getter", true)
5238 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005239 .Case("strong", true)
5240 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005241 .Default(false))
5242 Tokens[I].int_data[0] = CXToken_Keyword;
5243 }
5244 continue;
5245 }
5246
5247 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5248 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5249 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5250 if (llvm::StringSwitch<bool>(II->getName())
5251 .Case("in", true)
5252 .Case("out", true)
5253 .Case("inout", true)
5254 .Case("oneway", true)
5255 .Case("bycopy", true)
5256 .Case("byref", true)
5257 .Default(false))
5258 Tokens[I].int_data[0] = CXToken_Keyword;
5259 continue;
5260 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005261
5262 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5263 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5264 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005265 continue;
5266 }
5267 }
5268 }
Ted Kremenekab979612010-11-11 08:05:23 +00005269}
5270
Ted Kremenek6db61092010-05-05 00:55:15 +00005271extern "C" {
5272
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005273void clang_annotateTokens(CXTranslationUnit TU,
5274 CXToken *Tokens, unsigned NumTokens,
5275 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005276
5277 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005278 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005279
Douglas Gregor4419b672010-10-21 06:10:04 +00005280 // Any token we don't specifically annotate will have a NULL cursor.
5281 CXCursor C = clang_getNullCursor();
5282 for (unsigned I = 0; I != NumTokens; ++I)
5283 Cursors[I] = C;
5284
Ted Kremeneka60ed472010-11-16 08:15:36 +00005285 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005286 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005287 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005288
Douglas Gregorbdf60622010-03-05 21:16:25 +00005289 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005290
5291 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005292 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005293 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005294 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005295 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5296 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005297}
Ted Kremenek6628a612011-03-18 22:51:30 +00005298
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005299} // end: extern "C"
5300
5301//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005302// Operations for querying linkage of a cursor.
5303//===----------------------------------------------------------------------===//
5304
5305extern "C" {
5306CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005307 if (!clang_isDeclaration(cursor.kind))
5308 return CXLinkage_Invalid;
5309
Ted Kremenek16b42592010-03-03 06:36:57 +00005310 Decl *D = cxcursor::getCursorDecl(cursor);
5311 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5312 switch (ND->getLinkage()) {
5313 case NoLinkage: return CXLinkage_NoLinkage;
5314 case InternalLinkage: return CXLinkage_Internal;
5315 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5316 case ExternalLinkage: return CXLinkage_External;
5317 };
5318
5319 return CXLinkage_Invalid;
5320}
5321} // end: extern "C"
5322
5323//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005324// Operations for querying language of a cursor.
5325//===----------------------------------------------------------------------===//
5326
5327static CXLanguageKind getDeclLanguage(const Decl *D) {
5328 switch (D->getKind()) {
5329 default:
5330 break;
5331 case Decl::ImplicitParam:
5332 case Decl::ObjCAtDefsField:
5333 case Decl::ObjCCategory:
5334 case Decl::ObjCCategoryImpl:
5335 case Decl::ObjCClass:
5336 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005337 case Decl::ObjCForwardProtocol:
5338 case Decl::ObjCImplementation:
5339 case Decl::ObjCInterface:
5340 case Decl::ObjCIvar:
5341 case Decl::ObjCMethod:
5342 case Decl::ObjCProperty:
5343 case Decl::ObjCPropertyImpl:
5344 case Decl::ObjCProtocol:
5345 return CXLanguage_ObjC;
5346 case Decl::CXXConstructor:
5347 case Decl::CXXConversion:
5348 case Decl::CXXDestructor:
5349 case Decl::CXXMethod:
5350 case Decl::CXXRecord:
5351 case Decl::ClassTemplate:
5352 case Decl::ClassTemplatePartialSpecialization:
5353 case Decl::ClassTemplateSpecialization:
5354 case Decl::Friend:
5355 case Decl::FriendTemplate:
5356 case Decl::FunctionTemplate:
5357 case Decl::LinkageSpec:
5358 case Decl::Namespace:
5359 case Decl::NamespaceAlias:
5360 case Decl::NonTypeTemplateParm:
5361 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005362 case Decl::TemplateTemplateParm:
5363 case Decl::TemplateTypeParm:
5364 case Decl::UnresolvedUsingTypename:
5365 case Decl::UnresolvedUsingValue:
5366 case Decl::Using:
5367 case Decl::UsingDirective:
5368 case Decl::UsingShadow:
5369 return CXLanguage_CPlusPlus;
5370 }
5371
5372 return CXLanguage_C;
5373}
5374
5375extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005376
5377enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5378 if (clang_isDeclaration(cursor.kind))
5379 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005380 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005381 return CXAvailability_Available;
5382
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005383 switch (D->getAvailability()) {
5384 case AR_Available:
5385 case AR_NotYetIntroduced:
5386 return CXAvailability_Available;
5387
5388 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005389 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005390
5391 case AR_Unavailable:
5392 return CXAvailability_NotAvailable;
5393 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005394 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005395
Douglas Gregor58ddb602010-08-23 23:00:57 +00005396 return CXAvailability_Available;
5397}
5398
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005399CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5400 if (clang_isDeclaration(cursor.kind))
5401 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5402
5403 return CXLanguage_Invalid;
5404}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005405
5406 /// \brief If the given cursor is the "templated" declaration
5407 /// descibing a class or function template, return the class or
5408 /// function template.
5409static Decl *maybeGetTemplateCursor(Decl *D) {
5410 if (!D)
5411 return 0;
5412
5413 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5414 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5415 return FunTmpl;
5416
5417 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5418 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5419 return ClassTmpl;
5420
5421 return D;
5422}
5423
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005424CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5425 if (clang_isDeclaration(cursor.kind)) {
5426 if (Decl *D = getCursorDecl(cursor)) {
5427 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005428 if (!DC)
5429 return clang_getNullCursor();
5430
5431 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5432 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005433 }
5434 }
5435
5436 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5437 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005438 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005439 }
5440
5441 return clang_getNullCursor();
5442}
5443
5444CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5445 if (clang_isDeclaration(cursor.kind)) {
5446 if (Decl *D = getCursorDecl(cursor)) {
5447 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005448 if (!DC)
5449 return clang_getNullCursor();
5450
5451 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5452 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005453 }
5454 }
5455
5456 // FIXME: Note that we can't easily compute the lexical context of a
5457 // statement or expression, so we return nothing.
5458 return clang_getNullCursor();
5459}
5460
Douglas Gregor9f592342010-10-01 20:25:15 +00005461void clang_getOverriddenCursors(CXCursor cursor,
5462 CXCursor **overridden,
5463 unsigned *num_overridden) {
5464 if (overridden)
5465 *overridden = 0;
5466 if (num_overridden)
5467 *num_overridden = 0;
5468 if (!overridden || !num_overridden)
5469 return;
5470
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005471 SmallVector<CXCursor, 8> Overridden;
5472 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005473
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005474 *num_overridden = Overridden.size();
5475 *overridden = new CXCursor [Overridden.size()];
5476 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005477}
5478
5479void clang_disposeOverriddenCursors(CXCursor *overridden) {
5480 delete [] overridden;
5481}
5482
Douglas Gregorecdcb882010-10-20 22:00:55 +00005483CXFile clang_getIncludedFile(CXCursor cursor) {
5484 if (cursor.kind != CXCursor_InclusionDirective)
5485 return 0;
5486
5487 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5488 return (void *)ID->getFile();
5489}
5490
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005491} // end: extern "C"
5492
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005493
5494//===----------------------------------------------------------------------===//
5495// C++ AST instrospection.
5496//===----------------------------------------------------------------------===//
5497
5498extern "C" {
5499unsigned clang_CXXMethod_isStatic(CXCursor C) {
5500 if (!clang_isDeclaration(C.kind))
5501 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005502
5503 CXXMethodDecl *Method = 0;
5504 Decl *D = cxcursor::getCursorDecl(C);
5505 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5506 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5507 else
5508 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5509 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005510}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005511
Douglas Gregor211924b2011-05-12 15:17:24 +00005512unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5513 if (!clang_isDeclaration(C.kind))
5514 return 0;
5515
5516 CXXMethodDecl *Method = 0;
5517 Decl *D = cxcursor::getCursorDecl(C);
5518 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5519 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5520 else
5521 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5522 return (Method && Method->isVirtual()) ? 1 : 0;
5523}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005524} // end: extern "C"
5525
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005526//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005527// Attribute introspection.
5528//===----------------------------------------------------------------------===//
5529
5530extern "C" {
5531CXType clang_getIBOutletCollectionType(CXCursor C) {
5532 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005533 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005534
5535 IBOutletCollectionAttr *A =
5536 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5537
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005538 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005539}
5540} // end: extern "C"
5541
5542//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005543// Inspecting memory usage.
5544//===----------------------------------------------------------------------===//
5545
Ted Kremenekf7870022011-04-20 16:41:07 +00005546typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005547
Ted Kremenekf7870022011-04-20 16:41:07 +00005548static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5549 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005550 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005551 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005552 entries.push_back(entry);
5553}
5554
5555extern "C" {
5556
Ted Kremenekf7870022011-04-20 16:41:07 +00005557const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005558 const char *str = "";
5559 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005560 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005561 str = "ASTContext: expressions, declarations, and types";
5562 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005563 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005564 str = "ASTContext: identifiers";
5565 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005566 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005567 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005568 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005569 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005570 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005571 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005572 case CXTUResourceUsage_SourceManagerContentCache:
5573 str = "SourceManager: content cache allocator";
5574 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005575 case CXTUResourceUsage_AST_SideTables:
5576 str = "ASTContext: side tables";
5577 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005578 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5579 str = "SourceManager: malloc'ed memory buffers";
5580 break;
5581 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5582 str = "SourceManager: mmap'ed memory buffers";
5583 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005584 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5585 str = "ExternalASTSource: malloc'ed memory buffers";
5586 break;
5587 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5588 str = "ExternalASTSource: mmap'ed memory buffers";
5589 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005590 case CXTUResourceUsage_Preprocessor:
5591 str = "Preprocessor: malloc'ed memory";
5592 break;
5593 case CXTUResourceUsage_PreprocessingRecord:
5594 str = "Preprocessor: PreprocessingRecord";
5595 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005596 case CXTUResourceUsage_SourceManager_DataStructures:
5597 str = "SourceManager: data structures and tables";
5598 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005599 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5600 str = "Preprocessor: header search tables";
5601 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005602 }
5603 return str;
5604}
5605
Ted Kremenekf7870022011-04-20 16:41:07 +00005606CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005607 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005608 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005609 return usage;
5610 }
5611
5612 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5613 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5614 ASTContext &astContext = astUnit->getASTContext();
5615
5616 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005617 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005618 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005619
5620 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005621 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005622 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5623
5624 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005625 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005626 (unsigned long) astContext.Selectors.getTotalMemory());
5627
Ted Kremenekba29bd22011-04-28 04:53:38 +00005628 // How much memory is used by ASTContext's side tables?
5629 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5630 (unsigned long) astContext.getSideTableAllocatedMemory());
5631
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005632 // How much memory is used for caching global code completion results?
5633 unsigned long completionBytes = 0;
5634 if (GlobalCodeCompletionAllocator *completionAllocator =
5635 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005636 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005637 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005638 createCXTUResourceUsageEntry(*entries,
5639 CXTUResourceUsage_GlobalCompletionResults,
5640 completionBytes);
5641
5642 // How much memory is being used by SourceManager's content cache?
5643 createCXTUResourceUsageEntry(*entries,
5644 CXTUResourceUsage_SourceManagerContentCache,
5645 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005646
5647 // How much memory is being used by the MemoryBuffer's in SourceManager?
5648 const SourceManager::MemoryBufferSizes &srcBufs =
5649 astUnit->getSourceManager().getMemoryBufferSizes();
5650
5651 createCXTUResourceUsageEntry(*entries,
5652 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5653 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005654 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005655 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5656 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005657 createCXTUResourceUsageEntry(*entries,
5658 CXTUResourceUsage_SourceManager_DataStructures,
5659 (unsigned long) astContext.getSourceManager()
5660 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005661
5662 // How much memory is being used by the ExternalASTSource?
5663 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5664 const ExternalASTSource::MemoryBufferSizes &sizes =
5665 esrc->getMemoryBufferSizes();
5666
5667 createCXTUResourceUsageEntry(*entries,
5668 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5669 (unsigned long) sizes.malloc_bytes);
5670 createCXTUResourceUsageEntry(*entries,
5671 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5672 (unsigned long) sizes.mmap_bytes);
5673 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005674
5675 // How much memory is being used by the Preprocessor?
5676 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005677 createCXTUResourceUsageEntry(*entries,
5678 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005679 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005680
5681 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5682 createCXTUResourceUsageEntry(*entries,
5683 CXTUResourceUsage_PreprocessingRecord,
5684 pRec->getTotalMemory());
5685 }
5686
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005687 createCXTUResourceUsageEntry(*entries,
5688 CXTUResourceUsage_Preprocessor_HeaderSearch,
5689 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005690
Ted Kremenekf7870022011-04-20 16:41:07 +00005691 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005692 (unsigned) entries->size(),
5693 entries->size() ? &(*entries)[0] : 0 };
5694 entries.take();
5695 return usage;
5696}
5697
Ted Kremenekf7870022011-04-20 16:41:07 +00005698void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005699 if (usage.data)
5700 delete (MemUsageEntries*) usage.data;
5701}
5702
5703} // end extern "C"
5704
Douglas Gregor6df78732011-05-05 20:27:22 +00005705void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5706 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5707 for (unsigned I = 0; I != Usage.numEntries; ++I)
5708 fprintf(stderr, " %s: %lu\n",
5709 clang_getTUResourceUsageName(Usage.entries[I].kind),
5710 Usage.entries[I].amount);
5711
5712 clang_disposeCXTUResourceUsage(Usage);
5713}
5714
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005715//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005716// Misc. utility functions.
5717//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005718
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005719/// Default to using an 8 MB stack size on "safety" threads.
5720static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005721
5722namespace clang {
5723
5724bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005725 void (*Fn)(void*), void *UserData,
5726 unsigned Size) {
5727 if (!Size)
5728 Size = GetSafetyThreadStackSize();
5729 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005730 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5731 return CRC.RunSafely(Fn, UserData);
5732}
5733
5734unsigned GetSafetyThreadStackSize() {
5735 return SafetyStackThreadSize;
5736}
5737
5738void SetSafetyThreadStackSize(unsigned Value) {
5739 SafetyStackThreadSize = Value;
5740}
5741
5742}
5743
Ted Kremenek04bb7162010-01-22 22:44:15 +00005744extern "C" {
5745
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005746CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005747 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005748}
5749
5750} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005751