blob: 4bf1c5286c48d6deff43ac3d8820033b36efb7bd [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;
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000195
196 /// \brief Whether we should visit the preprocessing record entries that are
197 /// #included inside the \arg RegionOfInterest.
198 bool VisitIncludedPreprocessingEntries;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000199
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200 /// \brief When valid, a source range to which the cursor should restrict
201 /// its search.
202 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000203
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000204 // FIXME: Eventually remove. This part of a hack to support proper
205 // iteration over all Decls contained lexically within an ObjC container.
206 DeclContext::decl_iterator *DI_current;
207 DeclContext::decl_iterator DE_current;
208
Ted Kremenekd1ded662010-11-15 23:31:32 +0000209 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000210 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
211 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000212
Douglas Gregorb1373d02010-01-20 20:59:29 +0000213 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000214 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215
216 /// \brief Determine whether this particular source range comes before, comes
217 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000219 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
221
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000222 class SetParentRAII {
223 CXCursor &Parent;
224 Decl *&StmtParent;
225 CXCursor OldParent;
226
227 public:
228 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
229 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
230 {
231 Parent = NewParent;
232 if (clang_isDeclaration(Parent.kind))
233 StmtParent = getCursorDecl(Parent);
234 }
235
236 ~SetParentRAII() {
237 Parent = OldParent;
238 if (clang_isDeclaration(Parent.kind))
239 StmtParent = getCursorDecl(Parent);
240 }
241 };
242
Steve Naroff89922f82009-08-31 00:59:03 +0000243public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000244 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
245 CXClientData ClientData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000246 bool VisitPreprocessorLast,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000247 bool VisitIncludedPreprocessingEntries = false,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000248 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000249 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
250 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor08e0bc12011-09-10 00:09:20 +0000251 VisitPreprocessorLast(VisitPreprocessorLast),
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000252 VisitIncludedPreprocessingEntries(VisitIncludedPreprocessingEntries),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000253 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000254 {
255 Parent.kind = CXCursor_NoDeclFound;
256 Parent.data[0] = 0;
257 Parent.data[1] = 0;
258 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000259 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000260 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000261
Ted Kremenekd1ded662010-11-15 23:31:32 +0000262 ~CursorVisitor() {
263 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000264 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000265 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
266 delete *I;
267 }
268 }
269
Ted Kremeneka60ed472010-11-16 08:15:36 +0000270 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
271 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000272
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000273 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000274
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000275 bool visitPreprocessedEntitiesInRegion();
276
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000277 bool shouldVisitIncludedPreprocessingEntries() const {
278 return VisitIncludedPreprocessingEntries;
279 }
280
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000281 template<typename InputIterator>
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000282 bool visitPreprocessedEntities(InputIterator First, InputIterator Last,
283 PreprocessingRecord &PPRec,
284 FileID FID = FileID());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000285
Douglas Gregorb1373d02010-01-20 20:59:29 +0000286 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000287
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000288 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000289 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000290 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000291 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000292 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000293 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000294 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000295 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
296 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000298 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000299 bool VisitClassTemplatePartialSpecializationDecl(
300 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000301 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000302 bool VisitEnumConstantDecl(EnumConstantDecl *D);
303 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
304 bool VisitFunctionDecl(FunctionDecl *ND);
305 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000306 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000307 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000308 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000309 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000310 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000311 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
312 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
313 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
314 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000315 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000316 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
317 bool VisitObjCImplDecl(ObjCImplDecl *D);
318 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
319 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000320 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
321 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
322 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000323 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000324 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000325 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000326 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000327 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000328 bool VisitUsingDecl(UsingDecl *D);
329 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
330 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000331
Douglas Gregor01829d32010-08-31 14:41:23 +0000332 // Name visitor
333 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000334 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000335 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000336
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000337 // Template visitors
338 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000339 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000340 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
341
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000342 // Type visitors
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000343#define ABSTRACT_TYPELOC(CLASS, PARENT)
344#define TYPELOC(CLASS, PARENT) \
345 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
346#include "clang/AST/TypeLocNodes.def"
347
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000348 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000349 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000350 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
351
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000352 // Data-recursive visitor functions.
353 bool IsInRegionOfInterest(CXCursor C);
354 bool RunVisitorWorkList(VisitorWorkList &WL);
355 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000356 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000357};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000358
Ted Kremenekab188932010-01-05 19:32:54 +0000359} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000360
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000361static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000362static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
363
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000364
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000366 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367}
368
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369/// \brief Visit the given cursor and, if requested by the visitor,
370/// its children.
371///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372/// \param Cursor the cursor to visit.
373///
374/// \param CheckRegionOfInterest if true, then the caller already checked that
375/// this cursor is within the region of interest.
376///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377/// \returns true if the visitation should be aborted, false if it
378/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000379bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380 if (clang_isInvalid(Cursor.kind))
381 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000382
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383 if (clang_isDeclaration(Cursor.kind)) {
384 Decl *D = getCursorDecl(Cursor);
385 assert(D && "Invalid declaration cursor");
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000386 // Ignore implicit declarations, unless it's an objc method because
387 // currently we should report implicit methods for properties when indexing.
388 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389 return false;
390 }
391
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392 // If we have a range of interest, and this cursor doesn't intersect with it,
393 // we're done.
394 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000395 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000396 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000397 return false;
398 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000399
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 switch (Visitor(Cursor, Parent, ClientData)) {
401 case CXChildVisit_Break:
402 return true;
403
404 case CXChildVisit_Continue:
405 return false;
406
407 case CXChildVisit_Recurse:
408 return VisitChildren(Cursor);
409 }
410
Douglas Gregorfd643772010-01-25 16:45:46 +0000411 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412}
413
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000414static bool visitPreprocessedEntitiesInRange(SourceRange R,
415 PreprocessingRecord &PPRec,
416 CursorVisitor &Visitor) {
417 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
418 FileID FID;
419
420 if (!Visitor.shouldVisitIncludedPreprocessingEntries()) {
421 // If the begin/end of the range lie in the same FileID, do the optimization
422 // where we skip preprocessed entities that do not come from the same FileID.
423 FID = SM.getFileID(R.getBegin());
424 if (FID != SM.getFileID(R.getEnd()))
425 FID = FileID();
426 }
427
428 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
429 Entities = PPRec.getPreprocessedEntitiesInRange(R);
430 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
431 PPRec, FID);
432}
433
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000434bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000435 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000436 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000437 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000438
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000439 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000440 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000441 SourceLocation B = MappedRange.getBegin();
442 SourceLocation E = MappedRange.getEnd();
443
444 if (AU->isInPreambleFileID(B)) {
445 if (SM.isLoadedSourceLocation(E))
446 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
447 PPRec, *this);
448
449 // Beginning of range lies in the preamble but it also extends beyond
450 // it into the main file. Split the range into 2 parts, one covering
451 // the preamble and another covering the main file. This allows subsequent
452 // calls to visitPreprocessedEntitiesInRange to accept a source range that
453 // lies in the same FileID, allowing it to skip preprocessed entities that
454 // do not come from the same FileID.
455 bool breaked =
456 visitPreprocessedEntitiesInRange(
457 SourceRange(B, AU->getEndOfPreambleFileID()),
458 PPRec, *this);
459 if (breaked) return true;
460 return visitPreprocessedEntitiesInRange(
461 SourceRange(AU->getStartOfMainFileID(), E),
462 PPRec, *this);
463 }
464
465 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000466 }
467
Douglas Gregor788f5a12010-03-20 00:41:21 +0000468 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000469 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
470
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000471 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000472 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
473 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000474
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000475 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000476}
477
478template<typename InputIterator>
479bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000480 InputIterator Last,
481 PreprocessingRecord &PPRec,
482 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000483 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000484 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
485 continue;
486
487 PreprocessedEntity *PPE = *First;
488 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000489 if (Visit(MakeMacroExpansionCursor(ME, TU)))
490 return true;
491
492 continue;
493 }
494
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000495 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000496 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
497 return true;
498
499 continue;
500 }
501
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000502 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000503 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
504 return true;
505
506 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000507 }
508 }
509
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000510 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000511}
512
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000514///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515/// \returns true if the visitation should be aborted, false if it
516/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000517bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000518 if (clang_isReference(Cursor.kind) &&
519 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000520 // By definition, references have no children.
521 return false;
522 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000523
524 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000526 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000527
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528 if (clang_isDeclaration(Cursor.kind)) {
529 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000530 if (!D)
531 return false;
532
Ted Kremenek539311e2010-02-18 18:47:01 +0000533 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000534 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000535
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000536 if (clang_isStatement(Cursor.kind)) {
537 if (Stmt *S = getCursorStmt(Cursor))
538 return Visit(S);
539
540 return false;
541 }
542
543 if (clang_isExpression(Cursor.kind)) {
544 if (Expr *E = getCursorExpr(Cursor))
545 return Visit(E);
546
547 return false;
548 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000549
Douglas Gregorb1373d02010-01-20 20:59:29 +0000550 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000551 CXTranslationUnit tu = getCursorTU(Cursor);
552 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000553
554 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
555 for (unsigned I = 0; I != 2; ++I) {
556 if (VisitOrder[I]) {
557 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
558 RegionOfInterest.isInvalid()) {
559 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
560 TLEnd = CXXUnit->top_level_end();
561 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000562 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000563 return true;
564 }
565 } else if (VisitDeclContext(
566 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000567 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000568 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000569 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000570
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000571 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000572 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
573 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000574 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000575
Douglas Gregor7b691f332010-01-20 21:13:59 +0000576 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000577 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000578
Douglas Gregorc314aa42011-03-02 19:17:03 +0000579 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
580 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
581 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
582 return Visit(BaseTSInfo->getTypeLoc());
583 }
584 }
585 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000586
587 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
588 IBOutletCollectionAttr *A =
589 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
590 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
591 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
592 A->getInterfaceLoc(), TU));
593 }
594
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000596 return false;
597}
598
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000599bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000600 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
601 if (Visit(TSInfo->getTypeLoc()))
602 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000603
Ted Kremenek664cffd2010-07-22 11:30:19 +0000604 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000605 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000606
607 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000608}
609
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000610llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
611 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000612 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000613 if (Range.isInvalid())
614 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000615
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000616 switch (CompareRegionOfInterest(Range)) {
617 case RangeBefore:
618 // This declaration comes before the region of interest; skip it.
619 return llvm::Optional<bool>();
620
621 case RangeAfter:
622 // This declaration comes after the region of interest; we're done.
623 return false;
624
625 case RangeOverlap:
626 // This declaration overlaps the region of interest; visit it.
627 break;
628 }
629 }
630 return true;
631}
632
633bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
634 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
635
636 // FIXME: Eventually remove. This part of a hack to support proper
637 // iteration over all Decls contained lexically within an ObjC container.
638 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
639 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
640
641 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000642 Decl *D = *I;
643 if (D->getLexicalDeclContext() != DC)
644 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000645 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000646 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
647 if (!V.hasValue())
648 continue;
649 if (!V.getValue())
650 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000651 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000652 return true;
653 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000654 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000655}
656
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000657bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
658 llvm_unreachable("Translation units are visited directly by Visit()");
659 return false;
660}
661
Richard Smith162e1c12011-04-15 14:24:37 +0000662bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
663 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
664 return Visit(TSInfo->getTypeLoc());
665
666 return false;
667}
668
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000669bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
670 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
671 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000672
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000673 return false;
674}
675
676bool CursorVisitor::VisitTagDecl(TagDecl *D) {
677 return VisitDeclContext(D);
678}
679
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000680bool CursorVisitor::VisitClassTemplateSpecializationDecl(
681 ClassTemplateSpecializationDecl *D) {
682 bool ShouldVisitBody = false;
683 switch (D->getSpecializationKind()) {
684 case TSK_Undeclared:
685 case TSK_ImplicitInstantiation:
686 // Nothing to visit
687 return false;
688
689 case TSK_ExplicitInstantiationDeclaration:
690 case TSK_ExplicitInstantiationDefinition:
691 break;
692
693 case TSK_ExplicitSpecialization:
694 ShouldVisitBody = true;
695 break;
696 }
697
698 // Visit the template arguments used in the specialization.
699 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
700 TypeLoc TL = SpecType->getTypeLoc();
701 if (TemplateSpecializationTypeLoc *TSTLoc
702 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
703 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
704 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
705 return true;
706 }
707 }
708
709 if (ShouldVisitBody && VisitCXXRecordDecl(D))
710 return true;
711
712 return false;
713}
714
Douglas Gregor74dbe642010-08-31 19:31:58 +0000715bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
716 ClassTemplatePartialSpecializationDecl *D) {
717 // FIXME: Visit the "outer" template parameter lists on the TagDecl
718 // before visiting these template parameters.
719 if (VisitTemplateParameters(D->getTemplateParameters()))
720 return true;
721
722 // Visit the partial specialization arguments.
723 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
724 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
725 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
726 return true;
727
728 return VisitCXXRecordDecl(D);
729}
730
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000731bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000732 // Visit the default argument.
733 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
734 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
735 if (Visit(DefArg->getTypeLoc()))
736 return true;
737
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000738 return false;
739}
740
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000741bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
742 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000743 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000744 return false;
745}
746
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000747bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
748 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
749 if (Visit(TSInfo->getTypeLoc()))
750 return true;
751
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000752 // Visit the nested-name-specifier, if present.
753 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
754 if (VisitNestedNameSpecifierLoc(QualifierLoc))
755 return true;
756
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000757 return false;
758}
759
Douglas Gregora67e03f2010-09-09 21:42:20 +0000760/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000761static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
762 CXXCtorInitializer const * const *X
763 = static_cast<CXXCtorInitializer const * const *>(Xp);
764 CXXCtorInitializer const * const *Y
765 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000766
767 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
768 return -1;
769 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
770 return 1;
771 else
772 return 0;
773}
774
Douglas Gregorb1373d02010-01-20 20:59:29 +0000775bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000776 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
777 // Visit the function declaration's syntactic components in the order
778 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000779 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000780 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
781
782 // If we have a function declared directly (without the use of a typedef),
783 // visit just the return type. Otherwise, just visit the function's type
784 // now.
785 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
786 (!FTL && Visit(TL)))
787 return true;
788
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000789 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000790 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
791 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000792 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000793
794 // Visit the declaration name.
795 if (VisitDeclarationNameInfo(ND->getNameInfo()))
796 return true;
797
798 // FIXME: Visit explicitly-specified template arguments!
799
800 // Visit the function parameters, if we have a function type.
801 if (FTL && VisitFunctionTypeLoc(*FTL, true))
802 return true;
803
804 // FIXME: Attributes?
805 }
806
Sean Hunt10620eb2011-05-06 20:44:56 +0000807 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000808 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
809 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000810 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000811 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
812 IEnd = Constructor->init_end();
813 I != IEnd; ++I) {
814 if (!(*I)->isWritten())
815 continue;
816
817 WrittenInits.push_back(*I);
818 }
819
820 // Sort the initializers in source order
821 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000822 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000823
824 // Visit the initializers in source order
825 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000826 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000827 if (Init->isAnyMemberInitializer()) {
828 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000829 Init->getMemberLocation(), TU)))
830 return true;
831 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
832 if (Visit(BaseInfo->getTypeLoc()))
833 return true;
834 }
835
836 // Visit the initializer value.
837 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000838 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000839 return true;
840 }
841 }
842
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000843 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000844 return true;
845 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000846
Douglas Gregorb1373d02010-01-20 20:59:29 +0000847 return false;
848}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000849
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000850bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
851 if (VisitDeclaratorDecl(D))
852 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000855 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 return false;
858}
859
860bool CursorVisitor::VisitVarDecl(VarDecl *D) {
861 if (VisitDeclaratorDecl(D))
862 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000863
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000864 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000865 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000867 return false;
868}
869
Douglas Gregor84b51d72010-09-01 20:16:53 +0000870bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
871 if (VisitDeclaratorDecl(D))
872 return true;
873
874 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
875 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000876 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000877
878 return false;
879}
880
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000881bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
882 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
883 // before visiting these template parameters.
884 if (VisitTemplateParameters(D->getTemplateParameters()))
885 return true;
886
887 return VisitFunctionDecl(D->getTemplatedDecl());
888}
889
Douglas Gregor39d6f072010-08-31 19:02:00 +0000890bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
891 // FIXME: Visit the "outer" template parameter lists on the TagDecl
892 // before visiting these template parameters.
893 if (VisitTemplateParameters(D->getTemplateParameters()))
894 return true;
895
896 return VisitCXXRecordDecl(D->getTemplatedDecl());
897}
898
Douglas Gregor84b51d72010-09-01 20:16:53 +0000899bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
900 if (VisitTemplateParameters(D->getTemplateParameters()))
901 return true;
902
903 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
904 VisitTemplateArgumentLoc(D->getDefaultArgument()))
905 return true;
906
907 return false;
908}
909
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000910bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000911 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
912 if (Visit(TSInfo->getTypeLoc()))
913 return true;
914
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000915 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000916 PEnd = ND->param_end();
917 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000918 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000919 return true;
920 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000921
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000922 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000923 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000924 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000925
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000926 return false;
927}
928
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000929namespace {
930 struct ContainerDeclsSort {
931 SourceManager &SM;
932 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
933 bool operator()(Decl *A, Decl *B) {
934 SourceLocation L_A = A->getLocStart();
935 SourceLocation L_B = B->getLocStart();
936 assert(L_A.isValid() && L_B.isValid());
937 return SM.isBeforeInTranslationUnit(L_A, L_B);
938 }
939 };
940}
941
Douglas Gregora59e3902010-01-21 23:27:09 +0000942bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000943 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
944 // an @implementation can lexically contain Decls that are not properly
945 // nested in the AST. When we identify such cases, we need to retrofit
946 // this nesting here.
947 if (!DI_current)
948 return VisitDeclContext(D);
949
950 // Scan the Decls that immediately come after the container
951 // in the current DeclContext. If any fall within the
952 // container's lexical region, stash them into a vector
953 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000954 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000955 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000956 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000957 if (EndLoc.isValid()) {
958 DeclContext::decl_iterator next = *DI_current;
959 while (++next != DE_current) {
960 Decl *D_next = *next;
961 if (!D_next)
962 break;
963 SourceLocation L = D_next->getLocStart();
964 if (!L.isValid())
965 break;
966 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
967 *DI_current = next;
968 DeclsInContainer.push_back(D_next);
969 continue;
970 }
971 break;
972 }
973 }
974
975 // The common case.
976 if (DeclsInContainer.empty())
977 return VisitDeclContext(D);
978
979 // Get all the Decls in the DeclContext, and sort them with the
980 // additional ones we've collected. Then visit them.
981 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
982 I!=E; ++I) {
983 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000984 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
985 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000986 continue;
987 DeclsInContainer.push_back(subDecl);
988 }
989
990 // Now sort the Decls so that they appear in lexical order.
991 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
992 ContainerDeclsSort(SM));
993
994 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000995 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000996 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000997 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000998 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
999 if (!V.hasValue())
1000 continue;
1001 if (!V.getValue())
1002 return false;
1003 if (Visit(Cursor, true))
1004 return true;
1005 }
1006 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001007}
1008
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001010 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1011 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001012 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001014 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1015 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1016 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001017 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001018 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001019
Douglas Gregora59e3902010-01-21 23:27:09 +00001020 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001021}
1022
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001023bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1024 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1025 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1026 E = PID->protocol_end(); I != E; ++I, ++PL)
1027 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1028 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001029
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001030 return VisitObjCContainerDecl(PID);
1031}
1032
Ted Kremenek23173d72010-05-18 21:09:07 +00001033bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001034 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001035 return true;
1036
Ted Kremenek23173d72010-05-18 21:09:07 +00001037 // FIXME: This implements a workaround with @property declarations also being
1038 // installed in the DeclContext for the @interface. Eventually this code
1039 // should be removed.
1040 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1041 if (!CDecl || !CDecl->IsClassExtension())
1042 return false;
1043
1044 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1045 if (!ID)
1046 return false;
1047
1048 IdentifierInfo *PropertyId = PD->getIdentifier();
1049 ObjCPropertyDecl *prevDecl =
1050 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1051
1052 if (!prevDecl)
1053 return false;
1054
1055 // Visit synthesized methods since they will be skipped when visiting
1056 // the @interface.
1057 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001058 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001059 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001060 return true;
1061
1062 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001063 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001064 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001065 return true;
1066
1067 return false;
1068}
1069
Douglas Gregorb1373d02010-01-20 20:59:29 +00001070bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001071 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001072 if (D->getSuperClass() &&
1073 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001074 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001075 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001076 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001077
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001078 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1079 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1080 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001081 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001082 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001083
Douglas Gregora59e3902010-01-21 23:27:09 +00001084 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001085}
1086
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001087bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1088 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001089}
1090
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001091bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001092 // 'ID' could be null when dealing with invalid code.
1093 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1094 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1095 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001096
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001097 return VisitObjCImplDecl(D);
1098}
1099
1100bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1101#if 0
1102 // Issue callbacks for super class.
1103 // FIXME: No source location information!
1104 if (D->getSuperClass() &&
1105 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001106 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001107 TU)))
1108 return true;
1109#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001110
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001111 return VisitObjCImplDecl(D);
1112}
1113
1114bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1115 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1116 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1117 E = D->protocol_end();
1118 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001119 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001120 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001121
1122 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001123}
1124
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001125bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001126 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1127 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001128 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001129 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001130}
1131
Douglas Gregora4ffd852010-11-17 01:03:52 +00001132bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1133 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1134 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1135
1136 return false;
1137}
1138
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001139bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1140 return VisitDeclContext(D);
1141}
1142
Douglas Gregor69319002010-08-31 23:48:11 +00001143bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001144 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001145 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1146 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001147 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001148
1149 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1150 D->getTargetNameLoc(), TU));
1151}
1152
Douglas Gregor7e242562010-09-01 19:52:22 +00001153bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001154 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001155 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1156 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001157 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001158 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001159
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001160 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1161 return true;
1162
Douglas Gregor7e242562010-09-01 19:52:22 +00001163 return VisitDeclarationNameInfo(D->getNameInfo());
1164}
1165
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001166bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001167 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001168 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1169 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001170 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001171
1172 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1173 D->getIdentLocation(), TU));
1174}
1175
Douglas Gregor7e242562010-09-01 19:52:22 +00001176bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001177 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001178 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1179 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001180 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001181 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001182
Douglas Gregor7e242562010-09-01 19:52:22 +00001183 return VisitDeclarationNameInfo(D->getNameInfo());
1184}
1185
1186bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1187 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001188 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001189 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1190 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001191 return true;
1192
Douglas Gregor7e242562010-09-01 19:52:22 +00001193 return false;
1194}
1195
Douglas Gregor01829d32010-08-31 14:41:23 +00001196bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1197 switch (Name.getName().getNameKind()) {
1198 case clang::DeclarationName::Identifier:
1199 case clang::DeclarationName::CXXLiteralOperatorName:
1200 case clang::DeclarationName::CXXOperatorName:
1201 case clang::DeclarationName::CXXUsingDirective:
1202 return false;
1203
1204 case clang::DeclarationName::CXXConstructorName:
1205 case clang::DeclarationName::CXXDestructorName:
1206 case clang::DeclarationName::CXXConversionFunctionName:
1207 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1208 return Visit(TSInfo->getTypeLoc());
1209 return false;
1210
1211 case clang::DeclarationName::ObjCZeroArgSelector:
1212 case clang::DeclarationName::ObjCOneArgSelector:
1213 case clang::DeclarationName::ObjCMultiArgSelector:
1214 // FIXME: Per-identifier location info?
1215 return false;
1216 }
1217
1218 return false;
1219}
1220
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001221bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1222 SourceRange Range) {
1223 // FIXME: This whole routine is a hack to work around the lack of proper
1224 // source information in nested-name-specifiers (PR5791). Since we do have
1225 // a beginning source location, we can visit the first component of the
1226 // nested-name-specifier, if it's a single-token component.
1227 if (!NNS)
1228 return false;
1229
1230 // Get the first component in the nested-name-specifier.
1231 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1232 NNS = Prefix;
1233
1234 switch (NNS->getKind()) {
1235 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001236 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1237 TU));
1238
Douglas Gregor14aba762011-02-24 02:36:08 +00001239 case NestedNameSpecifier::NamespaceAlias:
1240 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1241 Range.getBegin(), TU));
1242
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001243 case NestedNameSpecifier::TypeSpec: {
1244 // If the type has a form where we know that the beginning of the source
1245 // range matches up with a reference cursor. Visit the appropriate reference
1246 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001247 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001248 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1249 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1250 if (const TagType *Tag = dyn_cast<TagType>(T))
1251 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1252 if (const TemplateSpecializationType *TST
1253 = dyn_cast<TemplateSpecializationType>(T))
1254 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1255 break;
1256 }
1257
1258 case NestedNameSpecifier::TypeSpecWithTemplate:
1259 case NestedNameSpecifier::Global:
1260 case NestedNameSpecifier::Identifier:
1261 break;
1262 }
1263
1264 return false;
1265}
1266
Douglas Gregordc355712011-02-25 00:36:19 +00001267bool
1268CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001269 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001270 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1271 Qualifiers.push_back(Qualifier);
1272
1273 while (!Qualifiers.empty()) {
1274 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1275 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1276 switch (NNS->getKind()) {
1277 case NestedNameSpecifier::Namespace:
1278 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001279 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001280 TU)))
1281 return true;
1282
1283 break;
1284
1285 case NestedNameSpecifier::NamespaceAlias:
1286 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001287 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001288 TU)))
1289 return true;
1290
1291 break;
1292
1293 case NestedNameSpecifier::TypeSpec:
1294 case NestedNameSpecifier::TypeSpecWithTemplate:
1295 if (Visit(Q.getTypeLoc()))
1296 return true;
1297
1298 break;
1299
1300 case NestedNameSpecifier::Global:
1301 case NestedNameSpecifier::Identifier:
1302 break;
1303 }
1304 }
1305
1306 return false;
1307}
1308
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001309bool CursorVisitor::VisitTemplateParameters(
1310 const TemplateParameterList *Params) {
1311 if (!Params)
1312 return false;
1313
1314 for (TemplateParameterList::const_iterator P = Params->begin(),
1315 PEnd = Params->end();
1316 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001317 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001318 return true;
1319 }
1320
1321 return false;
1322}
1323
Douglas Gregor0b36e612010-08-31 20:37:03 +00001324bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1325 switch (Name.getKind()) {
1326 case TemplateName::Template:
1327 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1328
1329 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001330 // Visit the overloaded template set.
1331 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1332 return true;
1333
Douglas Gregor0b36e612010-08-31 20:37:03 +00001334 return false;
1335
1336 case TemplateName::DependentTemplate:
1337 // FIXME: Visit nested-name-specifier.
1338 return false;
1339
1340 case TemplateName::QualifiedTemplate:
1341 // FIXME: Visit nested-name-specifier.
1342 return Visit(MakeCursorTemplateRef(
1343 Name.getAsQualifiedTemplateName()->getDecl(),
1344 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001345
1346 case TemplateName::SubstTemplateTemplateParm:
1347 return Visit(MakeCursorTemplateRef(
1348 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1349 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001350
1351 case TemplateName::SubstTemplateTemplateParmPack:
1352 return Visit(MakeCursorTemplateRef(
1353 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1354 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001355 }
1356
1357 return false;
1358}
1359
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001360bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1361 switch (TAL.getArgument().getKind()) {
1362 case TemplateArgument::Null:
1363 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001364 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001365 return false;
1366
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001367 case TemplateArgument::Type:
1368 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1369 return Visit(TSInfo->getTypeLoc());
1370 return false;
1371
1372 case TemplateArgument::Declaration:
1373 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001374 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001375 return false;
1376
1377 case TemplateArgument::Expression:
1378 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001379 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001380 return false;
1381
1382 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001383 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001384 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1385 return true;
1386
Douglas Gregora7fc9012011-01-05 18:58:31 +00001387 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001388 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001389 }
1390
1391 return false;
1392}
1393
Ted Kremeneka0536d82010-05-07 01:04:29 +00001394bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1395 return VisitDeclContext(D);
1396}
1397
Douglas Gregor01829d32010-08-31 14:41:23 +00001398bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1399 return Visit(TL.getUnqualifiedLoc());
1400}
1401
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001402bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001403 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001404
1405 // Some builtin types (such as Objective-C's "id", "sel", and
1406 // "Class") have associated declarations. Create cursors for those.
1407 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001408 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001409
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001410 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001411 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001412 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001413#define BUILTIN_TYPE(Id, SingletonId)
1414#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1415#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1416#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1417#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1418#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001419 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001420
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001421 case BuiltinType::ObjCId:
1422 VisitType = Context.getObjCIdType();
1423 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001424
1425 case BuiltinType::ObjCClass:
1426 VisitType = Context.getObjCClassType();
1427 break;
1428
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001429 case BuiltinType::ObjCSel:
1430 VisitType = Context.getObjCSelType();
1431 break;
1432 }
1433
1434 if (!VisitType.isNull()) {
1435 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001436 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001437 TU));
1438 }
1439
1440 return false;
1441}
1442
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001443bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001444 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001445}
1446
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001447bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1448 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1449}
1450
1451bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001452 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001453 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001454
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1456}
1457
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001458bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001459 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001460}
1461
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001462bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1463 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1464 return true;
1465
John McCallc12c5bb2010-05-15 11:32:37 +00001466 return false;
1467}
1468
1469bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1470 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1471 return true;
1472
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001473 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1474 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1475 TU)))
1476 return true;
1477 }
1478
1479 return false;
1480}
1481
1482bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001483 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001484}
1485
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001486bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1487 return Visit(TL.getInnerLoc());
1488}
1489
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001490bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1491 return Visit(TL.getPointeeLoc());
1492}
1493
1494bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1495 return Visit(TL.getPointeeLoc());
1496}
1497
1498bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1499 return Visit(TL.getPointeeLoc());
1500}
1501
1502bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001503 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001504}
1505
1506bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001507 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001508}
1509
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001510bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1511 return Visit(TL.getModifiedLoc());
1512}
1513
Douglas Gregor01829d32010-08-31 14:41:23 +00001514bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1515 bool SkipResultType) {
1516 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001517 return true;
1518
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001519 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001520 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001521 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001522 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001523
1524 return false;
1525}
1526
1527bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1528 if (Visit(TL.getElementLoc()))
1529 return true;
1530
1531 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001532 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001533
1534 return false;
1535}
1536
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001537bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1538 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001539 // Visit the template name.
1540 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1541 TL.getTemplateNameLoc()))
1542 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001543
1544 // Visit the template arguments.
1545 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1546 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1547 return true;
1548
1549 return false;
1550}
1551
Douglas Gregor2332c112010-01-21 20:48:56 +00001552bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1553 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1554}
1555
1556bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1557 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1558 return Visit(TSInfo->getTypeLoc());
1559
1560 return false;
1561}
1562
Sean Huntca63c202011-05-24 22:41:36 +00001563bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1564 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1565 return Visit(TSInfo->getTypeLoc());
1566
1567 return false;
1568}
1569
Douglas Gregor2494dd02011-03-01 01:34:45 +00001570bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1571 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1572 return true;
1573
1574 return false;
1575}
1576
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001577bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1578 DependentTemplateSpecializationTypeLoc TL) {
1579 // Visit the nested-name-specifier, if there is one.
1580 if (TL.getQualifierLoc() &&
1581 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1582 return true;
1583
1584 // Visit the template arguments.
1585 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1586 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1587 return true;
1588
1589 return false;
1590}
1591
Douglas Gregor9e876872011-03-01 18:12:44 +00001592bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1593 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1594 return true;
1595
1596 return Visit(TL.getNamedTypeLoc());
1597}
1598
Douglas Gregor7536dd52010-12-20 02:24:11 +00001599bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1600 return Visit(TL.getPatternLoc());
1601}
1602
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001603bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1604 if (Expr *E = TL.getUnderlyingExpr())
1605 return Visit(MakeCXCursor(E, StmtParent, TU));
1606
1607 return false;
1608}
1609
1610bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1611 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1612}
1613
Eli Friedmanb001de72011-10-06 23:00:33 +00001614bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1615 return Visit(TL.getValueLoc());
1616}
1617
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001618#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1619bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1620 return Visit##PARENT##Loc(TL); \
1621}
1622
1623DEFAULT_TYPELOC_IMPL(Complex, Type)
1624DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1625DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1626DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1627DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1628DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1629DEFAULT_TYPELOC_IMPL(Vector, Type)
1630DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1631DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1632DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1633DEFAULT_TYPELOC_IMPL(Record, TagType)
1634DEFAULT_TYPELOC_IMPL(Enum, TagType)
1635DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1636DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1637DEFAULT_TYPELOC_IMPL(Auto, Type)
1638
Ted Kremenek3064ef92010-08-27 21:34:58 +00001639bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001640 // Visit the nested-name-specifier, if present.
1641 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1642 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1643 return true;
1644
John McCall5e1cdac2011-10-07 06:10:15 +00001645 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001646 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1647 E = D->bases_end(); I != E; ++I) {
1648 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1649 return true;
1650 }
1651 }
1652
1653 return VisitTagDecl(D);
1654}
1655
Ted Kremenek09dfa372010-02-18 05:46:33 +00001656bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001657 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1658 i != e; ++i)
1659 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001660 return true;
1661
1662 return false;
1663}
1664
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001665//===----------------------------------------------------------------------===//
1666// Data-recursive visitor methods.
1667//===----------------------------------------------------------------------===//
1668
Ted Kremenek28a71942010-11-13 00:36:47 +00001669namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001670#define DEF_JOB(NAME, DATA, KIND)\
1671class NAME : public VisitorJob {\
1672public:\
1673 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1674 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001675 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001676};
1677
1678DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1679DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001680DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001681DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001682DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001683 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001684DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001685#undef DEF_JOB
1686
1687class DeclVisit : public VisitorJob {
1688public:
1689 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1690 VisitorJob(parent, VisitorJob::DeclVisitKind,
1691 d, isFirst ? (void*) 1 : (void*) 0) {}
1692 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001693 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001694 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001695 Decl *get() const { return static_cast<Decl*>(data[0]); }
1696 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001697};
Ted Kremenek035dc412010-11-13 00:36:50 +00001698class TypeLocVisit : public VisitorJob {
1699public:
1700 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1701 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1702 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1703
1704 static bool classof(const VisitorJob *VJ) {
1705 return VJ->getKind() == TypeLocVisitKind;
1706 }
1707
Ted Kremenek82f3c502010-11-15 22:23:26 +00001708 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001709 QualType T = QualType::getFromOpaquePtr(data[0]);
1710 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001711 }
1712};
1713
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001714class LabelRefVisit : public VisitorJob {
1715public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001716 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1717 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001718 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001719
1720 static bool classof(const VisitorJob *VJ) {
1721 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1722 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001723 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001724 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001725 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001726};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001727
1728class NestedNameSpecifierLocVisit : public VisitorJob {
1729public:
1730 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1731 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1732 Qualifier.getNestedNameSpecifier(),
1733 Qualifier.getOpaqueData()) { }
1734
1735 static bool classof(const VisitorJob *VJ) {
1736 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1737 }
1738
1739 NestedNameSpecifierLoc get() const {
1740 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1741 data[1]);
1742 }
1743};
1744
Ted Kremenekf64d8032010-11-18 00:02:32 +00001745class DeclarationNameInfoVisit : public VisitorJob {
1746public:
1747 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1748 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1749 static bool classof(const VisitorJob *VJ) {
1750 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1751 }
1752 DeclarationNameInfo get() const {
1753 Stmt *S = static_cast<Stmt*>(data[0]);
1754 switch (S->getStmtClass()) {
1755 default:
1756 llvm_unreachable("Unhandled Stmt");
1757 case Stmt::CXXDependentScopeMemberExprClass:
1758 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1759 case Stmt::DependentScopeDeclRefExprClass:
1760 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1761 }
1762 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001763};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001764class MemberRefVisit : public VisitorJob {
1765public:
1766 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1767 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001768 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001769 static bool classof(const VisitorJob *VJ) {
1770 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1771 }
1772 FieldDecl *get() const {
1773 return static_cast<FieldDecl*>(data[0]);
1774 }
1775 SourceLocation getLoc() const {
1776 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1777 }
1778};
Ted Kremenek28a71942010-11-13 00:36:47 +00001779class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1780 VisitorWorkList &WL;
1781 CXCursor Parent;
1782public:
1783 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1784 : WL(wl), Parent(parent) {}
1785
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001786 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001787 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001788 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001789 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001790 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001791 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001792 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001793 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001794 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001795 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001796 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001797 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001798 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001799 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001800 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001801 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001802 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001803 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001804 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1805 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001806 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001807 void VisitIfStmt(IfStmt *If);
1808 void VisitInitListExpr(InitListExpr *IE);
1809 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001810 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001811 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001812 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1813 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001814 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001815 void VisitStmt(Stmt *S);
1816 void VisitSwitchStmt(SwitchStmt *S);
1817 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001818 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001819 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001820 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001821 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001822 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001823 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001824 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001825
Ted Kremenek28a71942010-11-13 00:36:47 +00001826private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001827 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001828 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001829 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001830 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001831 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001832 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001833 void AddTypeLoc(TypeSourceInfo *TI);
1834 void EnqueueChildren(Stmt *S);
1835};
1836} // end anonyous namespace
1837
Ted Kremenekf64d8032010-11-18 00:02:32 +00001838void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1839 // 'S' should always be non-null, since it comes from the
1840 // statement we are visiting.
1841 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1842}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001843
1844void
1845EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1846 if (Qualifier)
1847 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1848}
1849
Ted Kremenek28a71942010-11-13 00:36:47 +00001850void EnqueueVisitor::AddStmt(Stmt *S) {
1851 if (S)
1852 WL.push_back(StmtVisit(S, Parent));
1853}
Ted Kremenek035dc412010-11-13 00:36:50 +00001854void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001855 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001856 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001857}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001858void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001859 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001860 if (A)
1861 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001862 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001863}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001864void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1865 if (D)
1866 WL.push_back(MemberRefVisit(D, L, Parent));
1867}
Ted Kremenek28a71942010-11-13 00:36:47 +00001868void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1869 if (TI)
1870 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1871 }
1872void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001873 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001874 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001875 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001876 }
1877 if (size == WL.size())
1878 return;
1879 // Now reverse the entries we just added. This will match the DFS
1880 // ordering performed by the worklist.
1881 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1882 std::reverse(I, E);
1883}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001884void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1885 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1886}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001887void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1888 AddDecl(B->getBlockDecl());
1889}
Ted Kremenek28a71942010-11-13 00:36:47 +00001890void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1891 EnqueueChildren(E);
1892 AddTypeLoc(E->getTypeSourceInfo());
1893}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001894void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1895 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1896 E = S->body_rend(); I != E; ++I) {
1897 AddStmt(*I);
1898 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001899}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001900void EnqueueVisitor::
1901VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1902 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1903 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001904 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1905 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001906 if (!E->isImplicitAccess())
1907 AddStmt(E->getBase());
1908}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001909void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1910 // Enqueue the initializer or constructor arguments.
1911 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1912 AddStmt(E->getConstructorArg(I-1));
1913 // Enqueue the array size, if any.
1914 AddStmt(E->getArraySize());
1915 // Enqueue the allocated type.
1916 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1917 // Enqueue the placement arguments.
1918 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1919 AddStmt(E->getPlacementArg(I-1));
1920}
Ted Kremenek28a71942010-11-13 00:36:47 +00001921void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001922 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1923 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001924 AddStmt(CE->getCallee());
1925 AddStmt(CE->getArg(0));
1926}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001927void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1928 // Visit the name of the type being destroyed.
1929 AddTypeLoc(E->getDestroyedTypeInfo());
1930 // Visit the scope type that looks disturbingly like the nested-name-specifier
1931 // but isn't.
1932 AddTypeLoc(E->getScopeTypeInfo());
1933 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001934 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1935 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001936 // Visit base expression.
1937 AddStmt(E->getBase());
1938}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001939void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1940 AddTypeLoc(E->getTypeSourceInfo());
1941}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001942void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1943 EnqueueChildren(E);
1944 AddTypeLoc(E->getTypeSourceInfo());
1945}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001946void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1947 EnqueueChildren(E);
1948 if (E->isTypeOperand())
1949 AddTypeLoc(E->getTypeOperandSourceInfo());
1950}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001951
1952void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1953 *E) {
1954 EnqueueChildren(E);
1955 AddTypeLoc(E->getTypeSourceInfo());
1956}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001957void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1958 EnqueueChildren(E);
1959 if (E->isTypeOperand())
1960 AddTypeLoc(E->getTypeOperandSourceInfo());
1961}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001962void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001963 if (DR->hasExplicitTemplateArgs()) {
1964 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1965 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001966 WL.push_back(DeclRefExprParts(DR, Parent));
1967}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001968void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1969 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1970 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001971 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001972}
Ted Kremenek035dc412010-11-13 00:36:50 +00001973void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1974 unsigned size = WL.size();
1975 bool isFirst = true;
1976 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1977 D != DEnd; ++D) {
1978 AddDecl(*D, isFirst);
1979 isFirst = false;
1980 }
1981 if (size == WL.size())
1982 return;
1983 // Now reverse the entries we just added. This will match the DFS
1984 // ordering performed by the worklist.
1985 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1986 std::reverse(I, E);
1987}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001988void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1989 AddStmt(E->getInit());
1990 typedef DesignatedInitExpr::Designator Designator;
1991 for (DesignatedInitExpr::reverse_designators_iterator
1992 D = E->designators_rbegin(), DEnd = E->designators_rend();
1993 D != DEnd; ++D) {
1994 if (D->isFieldDesignator()) {
1995 if (FieldDecl *Field = D->getField())
1996 AddMemberRef(Field, D->getFieldLoc());
1997 continue;
1998 }
1999 if (D->isArrayDesignator()) {
2000 AddStmt(E->getArrayIndex(*D));
2001 continue;
2002 }
2003 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2004 AddStmt(E->getArrayRangeEnd(*D));
2005 AddStmt(E->getArrayRangeStart(*D));
2006 }
2007}
Ted Kremenek28a71942010-11-13 00:36:47 +00002008void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
2009 EnqueueChildren(E);
2010 AddTypeLoc(E->getTypeInfoAsWritten());
2011}
2012void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2013 AddStmt(FS->getBody());
2014 AddStmt(FS->getInc());
2015 AddStmt(FS->getCond());
2016 AddDecl(FS->getConditionVariable());
2017 AddStmt(FS->getInit());
2018}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002019void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2020 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2021}
Ted Kremenek28a71942010-11-13 00:36:47 +00002022void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2023 AddStmt(If->getElse());
2024 AddStmt(If->getThen());
2025 AddStmt(If->getCond());
2026 AddDecl(If->getConditionVariable());
2027}
2028void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2029 // We care about the syntactic form of the initializer list, only.
2030 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2031 IE = Syntactic;
2032 EnqueueChildren(IE);
2033}
2034void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002035 WL.push_back(MemberExprParts(M, Parent));
2036
2037 // If the base of the member access expression is an implicit 'this', don't
2038 // visit it.
2039 // FIXME: If we ever want to show these implicit accesses, this will be
2040 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002041 if (!M->isImplicitAccess())
2042 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002043}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002044void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2045 AddTypeLoc(E->getEncodedTypeSourceInfo());
2046}
Ted Kremenek28a71942010-11-13 00:36:47 +00002047void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2048 EnqueueChildren(M);
2049 AddTypeLoc(M->getClassReceiverTypeInfo());
2050}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002051void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2052 // Visit the components of the offsetof expression.
2053 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2054 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2055 const OffsetOfNode &Node = E->getComponent(I-1);
2056 switch (Node.getKind()) {
2057 case OffsetOfNode::Array:
2058 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2059 break;
2060 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002061 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002062 break;
2063 case OffsetOfNode::Identifier:
2064 case OffsetOfNode::Base:
2065 continue;
2066 }
2067 }
2068 // Visit the type into which we're computing the offset.
2069 AddTypeLoc(E->getTypeSourceInfo());
2070}
Ted Kremenek28a71942010-11-13 00:36:47 +00002071void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002072 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002073 WL.push_back(OverloadExprParts(E, Parent));
2074}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002075void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2076 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002077 EnqueueChildren(E);
2078 if (E->isArgumentType())
2079 AddTypeLoc(E->getArgumentTypeInfo());
2080}
Ted Kremenek28a71942010-11-13 00:36:47 +00002081void EnqueueVisitor::VisitStmt(Stmt *S) {
2082 EnqueueChildren(S);
2083}
2084void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2085 AddStmt(S->getBody());
2086 AddStmt(S->getCond());
2087 AddDecl(S->getConditionVariable());
2088}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002089
Ted Kremenek28a71942010-11-13 00:36:47 +00002090void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2091 AddStmt(W->getBody());
2092 AddStmt(W->getCond());
2093 AddDecl(W->getConditionVariable());
2094}
John Wiegley21ff2e52011-04-28 00:16:57 +00002095
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002096void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2097 AddTypeLoc(E->getQueriedTypeSourceInfo());
2098}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002099
2100void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002101 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002102 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002103}
2104
John Wiegley21ff2e52011-04-28 00:16:57 +00002105void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2106 AddTypeLoc(E->getQueriedTypeSourceInfo());
2107}
2108
John Wiegley55262202011-04-25 06:54:41 +00002109void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2110 EnqueueChildren(E);
2111}
2112
Ted Kremenek28a71942010-11-13 00:36:47 +00002113void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2114 VisitOverloadExpr(U);
2115 if (!U->isImplicitAccess())
2116 AddStmt(U->getBase());
2117}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002118void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2119 AddStmt(E->getSubExpr());
2120 AddTypeLoc(E->getWrittenTypeInfo());
2121}
Douglas Gregor94d96292011-01-19 20:34:17 +00002122void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2123 WL.push_back(SizeOfPackExprParts(E, Parent));
2124}
Ted Kremenek60458782010-11-12 21:34:16 +00002125
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002126void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002127 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002128}
2129
2130bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2131 if (RegionOfInterest.isValid()) {
2132 SourceRange Range = getRawCursorExtent(C);
2133 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2134 return false;
2135 }
2136 return true;
2137}
2138
2139bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2140 while (!WL.empty()) {
2141 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002142 VisitorJob LI = WL.back();
2143 WL.pop_back();
2144
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002145 // Set the Parent field, then back to its old value once we're done.
2146 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2147
2148 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002149 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002150 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002151 if (!D)
2152 continue;
2153
2154 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002155 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2156 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002157 return true;
2158
2159 continue;
2160 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002161 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002162 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002163 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2164 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2165 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2166 Arg != ArgEnd; ++Arg) {
2167 if (VisitTemplateArgumentLoc(*Arg))
2168 return true;
2169 }
2170 continue;
2171 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002172 case VisitorJob::TypeLocVisitKind: {
2173 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002174 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002175 return true;
2176 continue;
2177 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002178 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002179 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002180 if (LabelStmt *stmt = LS->getStmt()) {
2181 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2182 TU))) {
2183 return true;
2184 }
2185 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002186 continue;
2187 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002188
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002189 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2190 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2191 if (VisitNestedNameSpecifierLoc(V->get()))
2192 return true;
2193 continue;
2194 }
2195
Ted Kremenekf64d8032010-11-18 00:02:32 +00002196 case VisitorJob::DeclarationNameInfoVisitKind: {
2197 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2198 ->get()))
2199 return true;
2200 continue;
2201 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002202 case VisitorJob::MemberRefVisitKind: {
2203 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2204 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2205 return true;
2206 continue;
2207 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002208 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002209 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002210 if (!S)
2211 continue;
2212
Ted Kremenekf1107452010-11-12 18:26:56 +00002213 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002214 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002215 if (!IsInRegionOfInterest(Cursor))
2216 continue;
2217 switch (Visitor(Cursor, Parent, ClientData)) {
2218 case CXChildVisit_Break: return true;
2219 case CXChildVisit_Continue: break;
2220 case CXChildVisit_Recurse:
2221 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002222 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002223 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002224 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002225 }
2226 case VisitorJob::MemberExprPartsKind: {
2227 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002228 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002229
2230 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002231 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2232 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002233 return true;
2234
2235 // Visit the declaration name.
2236 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2237 return true;
2238
2239 // Visit the explicitly-specified template arguments, if any.
2240 if (M->hasExplicitTemplateArgs()) {
2241 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2242 *ArgEnd = Arg + M->getNumTemplateArgs();
2243 Arg != ArgEnd; ++Arg) {
2244 if (VisitTemplateArgumentLoc(*Arg))
2245 return true;
2246 }
2247 }
2248 continue;
2249 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002250 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002251 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002252 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002253 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2254 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002255 return true;
2256 // Visit declaration name.
2257 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2258 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002259 continue;
2260 }
Ted Kremenek60458782010-11-12 21:34:16 +00002261 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002262 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002263 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002264 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2265 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002266 return true;
2267 // Visit the declaration name.
2268 if (VisitDeclarationNameInfo(O->getNameInfo()))
2269 return true;
2270 // Visit the overloaded declaration reference.
2271 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2272 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002273 continue;
2274 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002275 case VisitorJob::SizeOfPackExprPartsKind: {
2276 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2277 NamedDecl *Pack = E->getPack();
2278 if (isa<TemplateTypeParmDecl>(Pack)) {
2279 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2280 E->getPackLoc(), TU)))
2281 return true;
2282
2283 continue;
2284 }
2285
2286 if (isa<TemplateTemplateParmDecl>(Pack)) {
2287 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2288 E->getPackLoc(), TU)))
2289 return true;
2290
2291 continue;
2292 }
2293
2294 // Non-type template parameter packs and function parameter packs are
2295 // treated like DeclRefExpr cursors.
2296 continue;
2297 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002298 }
2299 }
2300 return false;
2301}
2302
Ted Kremenekcdba6592010-11-18 00:42:18 +00002303bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002304 VisitorWorkList *WL = 0;
2305 if (!WorkListFreeList.empty()) {
2306 WL = WorkListFreeList.back();
2307 WL->clear();
2308 WorkListFreeList.pop_back();
2309 }
2310 else {
2311 WL = new VisitorWorkList();
2312 WorkListCache.push_back(WL);
2313 }
2314 EnqueueWorkList(*WL, S);
2315 bool result = RunVisitorWorkList(*WL);
2316 WorkListFreeList.push_back(WL);
2317 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002318}
2319
Francois Pichet48a8d142011-07-25 22:00:44 +00002320namespace {
2321typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2322RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2323 const DeclarationNameInfo &NI,
2324 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002325 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002326 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2327 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2328 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2329
2330 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2331
2332 RefNamePieces Pieces;
2333
2334 if (WantQualifier && QLoc.isValid())
2335 Pieces.push_back(QLoc);
2336
2337 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2338 Pieces.push_back(NI.getLoc());
2339
2340 if (WantTemplateArgs && TemplateArgs)
2341 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2342 TemplateArgs->RAngleLoc));
2343
2344 if (Kind == DeclarationName::CXXOperatorName) {
2345 Pieces.push_back(SourceLocation::getFromRawEncoding(
2346 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2347 Pieces.push_back(SourceLocation::getFromRawEncoding(
2348 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2349 }
2350
2351 if (WantSinglePiece) {
2352 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2353 Pieces.clear();
2354 Pieces.push_back(R);
2355 }
2356
2357 return Pieces;
2358}
2359}
2360
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002361//===----------------------------------------------------------------------===//
2362// Misc. API hooks.
2363//===----------------------------------------------------------------------===//
2364
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002365static llvm::sys::Mutex EnableMultithreadingMutex;
2366static bool EnabledMultithreading;
2367
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002368extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002369CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2370 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002371 // Disable pretty stack trace functionality, which will otherwise be a very
2372 // poor citizen of the world and set up all sorts of signal handlers.
2373 llvm::DisablePrettyStackTrace = true;
2374
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002375 // We use crash recovery to make some of our APIs more reliable, implicitly
2376 // enable it.
2377 llvm::CrashRecoveryContext::Enable();
2378
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002379 // Enable support for multithreading in LLVM.
2380 {
2381 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2382 if (!EnabledMultithreading) {
2383 llvm::llvm_start_multithreaded();
2384 EnabledMultithreading = true;
2385 }
2386 }
2387
Douglas Gregora030b7c2010-01-22 20:35:53 +00002388 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002389 if (excludeDeclarationsFromPCH)
2390 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002391 if (displayDiagnostics)
2392 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002393 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002394}
2395
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002396void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002397 if (CIdx)
2398 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002399}
2400
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002401void clang_toggleCrashRecovery(unsigned isEnabled) {
2402 if (isEnabled)
2403 llvm::CrashRecoveryContext::Enable();
2404 else
2405 llvm::CrashRecoveryContext::Disable();
2406}
2407
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002408CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002409 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002410 if (!CIdx)
2411 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002412
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002413 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002414 FileSystemOptions FileSystemOpts;
2415 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002416
David Blaikied6471f72011-09-25 23:23:43 +00002417 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002418 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002419 CXXIdx->getOnlyLocalDecls(),
2420 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002421 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002422}
2423
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002424unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002425 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002426 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002427}
2428
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002429CXTranslationUnit
2430clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2431 const char *source_filename,
2432 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002433 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002434 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002435 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002436 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002437 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002438 return clang_parseTranslationUnit(CIdx, source_filename,
2439 command_line_args, num_command_line_args,
2440 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002441 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002442}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002443
2444struct ParseTranslationUnitInfo {
2445 CXIndex CIdx;
2446 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002447 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002448 int num_command_line_args;
2449 struct CXUnsavedFile *unsaved_files;
2450 unsigned num_unsaved_files;
2451 unsigned options;
2452 CXTranslationUnit result;
2453};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002454static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002455 ParseTranslationUnitInfo *PTUI =
2456 static_cast<ParseTranslationUnitInfo*>(UserData);
2457 CXIndex CIdx = PTUI->CIdx;
2458 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002459 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002460 int num_command_line_args = PTUI->num_command_line_args;
2461 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2462 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2463 unsigned options = PTUI->options;
2464 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002465
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002466 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002467 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002468
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002469 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2470
Douglas Gregor44c181a2010-07-23 00:33:23 +00002471 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002472 // FIXME: Add a flag for modules.
2473 TranslationUnitKind TUKind
2474 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002475 bool CacheCodeCompetionResults
2476 = options & CXTranslationUnit_CacheCompletionResults;
2477
Douglas Gregor5352ac02010-01-28 00:27:43 +00002478 // Configure the diagnostics.
2479 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002480 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002481 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2482 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002483
Ted Kremenek25a11e12011-03-22 01:15:24 +00002484 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002485 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2486 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002487 DiagCleanup(Diags.getPtr());
2488
2489 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2490 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2491
2492 // Recover resources if we crash before exiting this function.
2493 llvm::CrashRecoveryContextCleanupRegistrar<
2494 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2495
Douglas Gregor4db64a42010-01-23 00:14:00 +00002496 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002497 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002498 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002499 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002500 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2501 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002502 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002503
Ted Kremenek25a11e12011-03-22 01:15:24 +00002504 llvm::OwningPtr<std::vector<const char *> >
2505 Args(new std::vector<const char*>());
2506
2507 // Recover resources if we crash before exiting this method.
2508 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2509 ArgsCleanup(Args.get());
2510
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002511 // Since the Clang C library is primarily used by batch tools dealing with
2512 // (often very broken) source code, where spell-checking can have a
2513 // significant negative impact on performance (particularly when
2514 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002515 // Only do this if we haven't found a spell-checking-related argument.
2516 bool FoundSpellCheckingArgument = false;
2517 for (int I = 0; I != num_command_line_args; ++I) {
2518 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2519 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2520 FoundSpellCheckingArgument = true;
2521 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002522 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002523 }
2524 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002525 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002526
Ted Kremenek25a11e12011-03-22 01:15:24 +00002527 Args->insert(Args->end(), command_line_args,
2528 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002529
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002530 // The 'source_filename' argument is optional. If the caller does not
2531 // specify it then it is assumed that the source file is specified
2532 // in the actual argument list.
2533 // Put the source file after command_line_args otherwise if '-x' flag is
2534 // present it will be unused.
2535 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002536 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002537
Douglas Gregor44c181a2010-07-23 00:33:23 +00002538 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002539 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002540 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002541 Args->push_back("-Xclang");
2542 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002543 NestedMacroExpansions
2544 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002545 }
2546
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002547 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002548 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002549 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2550 /* vector::data() not portable */,
2551 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002552 Diags,
2553 CXXIdx->getClangResourcesPath(),
2554 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002555 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002556 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002557 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002558 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002559 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002560 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002561 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002562 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002564 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002565 // Make sure to check that 'Unit' is non-NULL.
2566 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2567 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2568 DEnd = Unit->stored_diag_end();
2569 D != DEnd; ++D) {
2570 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2571 CXString Msg = clang_formatDiagnostic(&Diag,
2572 clang_defaultDiagnosticDisplayOptions());
2573 fprintf(stderr, "%s\n", clang_getCString(Msg));
2574 clang_disposeString(Msg);
2575 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002576#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002577 // On Windows, force a flush, since there may be multiple copies of
2578 // stderr and stdout in the file system, all with different buffers
2579 // but writing to the same device.
2580 fflush(stderr);
2581#endif
2582 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002583 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002584
Ted Kremeneka60ed472010-11-16 08:15:36 +00002585 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002586}
2587CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2588 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002589 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002590 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002591 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002592 unsigned num_unsaved_files,
2593 unsigned options) {
2594 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002595 num_command_line_args, unsaved_files,
2596 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002597 llvm::CrashRecoveryContext CRC;
2598
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002599 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002600 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2601 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2602 fprintf(stderr, " 'command_line_args' : [");
2603 for (int i = 0; i != num_command_line_args; ++i) {
2604 if (i)
2605 fprintf(stderr, ", ");
2606 fprintf(stderr, "'%s'", command_line_args[i]);
2607 }
2608 fprintf(stderr, "],\n");
2609 fprintf(stderr, " 'unsaved_files' : [");
2610 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2611 if (i)
2612 fprintf(stderr, ", ");
2613 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2614 unsaved_files[i].Length);
2615 }
2616 fprintf(stderr, "],\n");
2617 fprintf(stderr, " 'options' : %d,\n", options);
2618 fprintf(stderr, "}\n");
2619
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002620 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002621 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2622 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002623 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002624
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002625 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002626}
2627
Douglas Gregor19998442010-08-13 15:35:05 +00002628unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2629 return CXSaveTranslationUnit_None;
2630}
2631
2632int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2633 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002634 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002635 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002636
Douglas Gregor39c411f2011-07-06 16:43:36 +00002637 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002638 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2639 PrintLibclangResourceUsage(TU);
2640 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002641}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002642
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002643void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002644 if (CTUnit) {
2645 // If the translation unit has been marked as unsafe to free, just discard
2646 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002647 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002648 return;
2649
Ted Kremeneka60ed472010-11-16 08:15:36 +00002650 delete static_cast<ASTUnit *>(CTUnit->TUData);
2651 disposeCXStringPool(CTUnit->StringPool);
2652 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002653 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002654}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002655
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002656unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2657 return CXReparse_None;
2658}
2659
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002660struct ReparseTranslationUnitInfo {
2661 CXTranslationUnit TU;
2662 unsigned num_unsaved_files;
2663 struct CXUnsavedFile *unsaved_files;
2664 unsigned options;
2665 int result;
2666};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002667
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002668static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002669 ReparseTranslationUnitInfo *RTUI =
2670 static_cast<ReparseTranslationUnitInfo*>(UserData);
2671 CXTranslationUnit TU = RTUI->TU;
2672 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2673 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2674 unsigned options = RTUI->options;
2675 (void) options;
2676 RTUI->result = 1;
2677
Douglas Gregorabc563f2010-07-19 21:46:24 +00002678 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002679 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002680
Ted Kremeneka60ed472010-11-16 08:15:36 +00002681 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002682 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002683
Ted Kremenek25a11e12011-03-22 01:15:24 +00002684 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2685 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2686
2687 // Recover resources if we crash before exiting this function.
2688 llvm::CrashRecoveryContextCleanupRegistrar<
2689 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2690
Douglas Gregorabc563f2010-07-19 21:46:24 +00002691 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002692 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002693 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002694 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002695 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2696 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002697 }
2698
Ted Kremenek4ee99262011-03-22 20:16:19 +00002699 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2700 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002701 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002702}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002703
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002704int clang_reparseTranslationUnit(CXTranslationUnit TU,
2705 unsigned num_unsaved_files,
2706 struct CXUnsavedFile *unsaved_files,
2707 unsigned options) {
2708 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2709 options, 0 };
2710 llvm::CrashRecoveryContext CRC;
2711
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002712 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002713 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002714 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002715 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002716 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2717 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002718
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002719 return RTUI.result;
2720}
2721
Douglas Gregordf95a132010-08-09 20:45:32 +00002722
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002723CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002724 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002725 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002726
Ted Kremeneka60ed472010-11-16 08:15:36 +00002727 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002728 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002729}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002730
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002731CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002732 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002733 return Result;
2734}
2735
Ted Kremenekfb480492010-01-13 21:46:36 +00002736} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002737
Ted Kremenekfb480492010-01-13 21:46:36 +00002738//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002739// CXSourceLocation and CXSourceRange Operations.
2740//===----------------------------------------------------------------------===//
2741
Douglas Gregorb9790342010-01-22 21:44:22 +00002742extern "C" {
2743CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002744 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002745 return Result;
2746}
2747
2748unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002749 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2750 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2751 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002752}
2753
2754CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2755 CXFile file,
2756 unsigned line,
2757 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002758 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002759 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002760
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002761 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002762 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Argyrios Kyrtzidis57165be2011-10-10 21:57:15 +00002763 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002764 const FileEntry *File = static_cast<const FileEntry *>(file);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002765 SourceLocation SLoc = CXXUnit->getLocation(File, line, column);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002766 if (SLoc.isInvalid()) {
2767 if (Logging)
2768 llvm::errs() << "clang_getLocation(\"" << File->getName()
2769 << "\", " << line << ", " << column << ") = invalid\n";
2770 return clang_getNullLocation();
2771 }
2772
2773 if (Logging)
2774 llvm::errs() << "clang_getLocation(\"" << File->getName()
2775 << "\", " << line << ", " << column << ") = "
2776 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002777
2778 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2779}
2780
2781CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2782 CXFile file,
2783 unsigned offset) {
2784 if (!tu || !file)
2785 return clang_getNullLocation();
2786
Ted Kremeneka60ed472010-11-16 08:15:36 +00002787 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002788 SourceLocation SLoc
2789 = CXXUnit->getLocation(static_cast<const FileEntry *>(file), offset);
David Chisnall83889a72010-10-15 17:07:39 +00002790 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002791
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002792 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002793}
2794
Douglas Gregor5352ac02010-01-28 00:27:43 +00002795CXSourceRange clang_getNullRange() {
2796 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2797 return Result;
2798}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002799
Douglas Gregor5352ac02010-01-28 00:27:43 +00002800CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2801 if (begin.ptr_data[0] != end.ptr_data[0] ||
2802 begin.ptr_data[1] != end.ptr_data[1])
2803 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002804
2805 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002806 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002807 return Result;
2808}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002809
2810unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2811{
2812 return range1.ptr_data[0] == range2.ptr_data[0]
2813 && range1.ptr_data[1] == range2.ptr_data[1]
2814 && range1.begin_int_data == range2.begin_int_data
2815 && range1.end_int_data == range2.end_int_data;
2816}
Argyrios Kyrtzidisde5db642011-09-28 18:14:21 +00002817
2818int clang_Range_isNull(CXSourceRange range) {
2819 return clang_equalRanges(range, clang_getNullRange());
2820}
2821
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002822} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002823
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002824static void createNullLocation(CXFile *file, unsigned *line,
2825 unsigned *column, unsigned *offset) {
2826 if (file)
2827 *file = 0;
2828 if (line)
2829 *line = 0;
2830 if (column)
2831 *column = 0;
2832 if (offset)
2833 *offset = 0;
2834 return;
2835}
2836
2837extern "C" {
Chandler Carruth20174222011-08-31 16:53:37 +00002838void clang_getExpansionLocation(CXSourceLocation location,
2839 CXFile *file,
2840 unsigned *line,
2841 unsigned *column,
2842 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002843 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2844
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002845 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002846 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002847 return;
2848 }
2849
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002850 const SourceManager &SM =
2851 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth20174222011-08-31 16:53:37 +00002852 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002853
Chandler Carruthcea731a2011-07-14 16:07:57 +00002854 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002855 // This can manifest in invalid code.
Chandler Carruth20174222011-08-31 16:53:37 +00002856 FileID fileID = SM.getFileID(ExpansionLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002857 bool Invalid = false;
2858 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
Argyrios Kyrtzidisc705d252011-10-18 21:59:54 +00002859 if (Invalid || !sloc.isFile()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002860 createNullLocation(file, line, column, offset);
2861 return;
2862 }
2863
Douglas Gregor1db19de2010-01-19 21:36:55 +00002864 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002865 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002866 if (line)
Chandler Carruth20174222011-08-31 16:53:37 +00002867 *line = SM.getExpansionLineNumber(ExpansionLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002868 if (column)
Chandler Carruth20174222011-08-31 16:53:37 +00002869 *column = SM.getExpansionColumnNumber(ExpansionLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002870 if (offset)
Chandler Carruth20174222011-08-31 16:53:37 +00002871 *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2872}
2873
Argyrios Kyrtzidise6be34d2011-09-13 21:49:08 +00002874void clang_getPresumedLocation(CXSourceLocation location,
2875 CXString *filename,
2876 unsigned *line,
2877 unsigned *column) {
2878 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2879
2880 if (!location.ptr_data[0] || Loc.isInvalid()) {
2881 if (filename)
2882 *filename = createCXString("");
2883 if (line)
2884 *line = 0;
2885 if (column)
2886 *column = 0;
2887 }
2888 else {
2889 const SourceManager &SM =
2890 *static_cast<const SourceManager*>(location.ptr_data[0]);
2891 PresumedLoc PreLoc = SM.getPresumedLoc(Loc);
2892
2893 if (filename)
2894 *filename = createCXString(PreLoc.getFilename());
2895 if (line)
2896 *line = PreLoc.getLine();
2897 if (column)
2898 *column = PreLoc.getColumn();
2899 }
2900}
2901
Chandler Carruth20174222011-08-31 16:53:37 +00002902void clang_getInstantiationLocation(CXSourceLocation location,
2903 CXFile *file,
2904 unsigned *line,
2905 unsigned *column,
2906 unsigned *offset) {
2907 // Redirect to new API.
2908 clang_getExpansionLocation(location, file, line, column, offset);
Douglas Gregore69517c2010-01-26 03:07:15 +00002909}
2910
Douglas Gregora9b06d42010-11-09 06:24:54 +00002911void clang_getSpellingLocation(CXSourceLocation location,
2912 CXFile *file,
2913 unsigned *line,
2914 unsigned *column,
2915 unsigned *offset) {
2916 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2917
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002918 if (!location.ptr_data[0] || Loc.isInvalid())
2919 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002920
2921 const SourceManager &SM =
2922 *static_cast<const SourceManager*>(location.ptr_data[0]);
2923 SourceLocation SpellLoc = Loc;
2924 if (SpellLoc.isMacroID()) {
2925 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2926 if (SimpleSpellingLoc.isFileID() &&
2927 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2928 SpellLoc = SimpleSpellingLoc;
2929 else
Chandler Carruth40278532011-07-25 16:49:02 +00002930 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002931 }
2932
2933 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2934 FileID FID = LocInfo.first;
2935 unsigned FileOffset = LocInfo.second;
2936
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002937 if (FID.isInvalid())
2938 return createNullLocation(file, line, column, offset);
2939
Douglas Gregora9b06d42010-11-09 06:24:54 +00002940 if (file)
2941 *file = (void *)SM.getFileEntryForID(FID);
2942 if (line)
2943 *line = SM.getLineNumber(FID, FileOffset);
2944 if (column)
2945 *column = SM.getColumnNumber(FID, FileOffset);
2946 if (offset)
2947 *offset = FileOffset;
2948}
2949
Douglas Gregor1db19de2010-01-19 21:36:55 +00002950CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002951 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002952 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002953 return Result;
2954}
2955
2956CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002957 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002958 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002959 return Result;
2960}
2961
Douglas Gregorb9790342010-01-22 21:44:22 +00002962} // end: extern "C"
2963
Douglas Gregor1db19de2010-01-19 21:36:55 +00002964//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002965// CXFile Operations.
2966//===----------------------------------------------------------------------===//
2967
2968extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002969CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002970 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002971 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002972
Steve Naroff88145032009-10-27 14:35:18 +00002973 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002974 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002975}
2976
2977time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002978 if (!SFile)
2979 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002980
Steve Naroff88145032009-10-27 14:35:18 +00002981 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2982 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002983}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002984
Douglas Gregorb9790342010-01-22 21:44:22 +00002985CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2986 if (!tu)
2987 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002988
Ted Kremeneka60ed472010-11-16 08:15:36 +00002989 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002990
Douglas Gregorb9790342010-01-22 21:44:22 +00002991 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002992 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002993}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002994
Douglas Gregordd3e5542011-05-04 00:14:37 +00002995unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2996 if (!tu || !file)
2997 return 0;
2998
2999 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
3000 FileEntry *FEnt = static_cast<FileEntry *>(file);
3001 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3002 .isFileMultipleIncludeGuarded(FEnt);
3003}
3004
Ted Kremenekfb480492010-01-13 21:46:36 +00003005} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00003006
Ted Kremenekfb480492010-01-13 21:46:36 +00003007//===----------------------------------------------------------------------===//
3008// CXCursor Operations.
3009//===----------------------------------------------------------------------===//
3010
Ted Kremenekfb480492010-01-13 21:46:36 +00003011static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00003012 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00003013 return getDeclFromExpr(CE->getSubExpr());
3014
Ted Kremenekfb480492010-01-13 21:46:36 +00003015 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
3016 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003017 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3018 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00003019 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3020 return ME->getMemberDecl();
3021 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
3022 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00003023 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00003024 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00003025
Ted Kremenekfb480492010-01-13 21:46:36 +00003026 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3027 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00003028 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00003029 if (!CE->isElidable())
3030 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00003031 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3032 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003033
Douglas Gregordb1314e2010-10-01 21:11:22 +00003034 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3035 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00003036 if (SubstNonTypeTemplateParmPackExpr *NTTP
3037 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3038 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00003039 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3040 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3041 isa<ParmVarDecl>(SizeOfPack->getPack()))
3042 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00003043
Ted Kremenekfb480492010-01-13 21:46:36 +00003044 return 0;
3045}
3046
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003047static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00003048 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3049 return getLocationFromExpr(CE->getSubExpr());
3050
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003051 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3052 return /*FIXME:*/Msg->getLeftLoc();
3053 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3054 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003055 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3056 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003057 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3058 return Member->getMemberLoc();
3059 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3060 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003061 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3062 return SizeOfPack->getPackLoc();
3063
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003064 return E->getLocStart();
3065}
3066
Ted Kremenekfb480492010-01-13 21:46:36 +00003067extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003068
3069unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003070 CXCursorVisitor visitor,
3071 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00003072 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3073 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003074 return CursorVis.VisitChildren(parent);
3075}
3076
David Chisnall3387c652010-11-03 14:12:26 +00003077#ifndef __has_feature
3078#define __has_feature(x) 0
3079#endif
3080#if __has_feature(blocks)
3081typedef enum CXChildVisitResult
3082 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3083
3084static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3085 CXClientData client_data) {
3086 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3087 return block(cursor, parent);
3088}
3089#else
3090// If we are compiled with a compiler that doesn't have native blocks support,
3091// define and call the block manually, so the
3092typedef struct _CXChildVisitResult
3093{
3094 void *isa;
3095 int flags;
3096 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003097 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3098 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003099} *CXCursorVisitorBlock;
3100
3101static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3102 CXClientData client_data) {
3103 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3104 return block->invoke(block, cursor, parent);
3105}
3106#endif
3107
3108
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003109unsigned clang_visitChildrenWithBlock(CXCursor parent,
3110 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003111 return clang_visitChildren(parent, visitWithBlock, block);
3112}
3113
Douglas Gregor78205d42010-01-20 21:45:58 +00003114static CXString getDeclSpelling(Decl *D) {
3115 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003116 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003117 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003118 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3119 return createCXString(Property->getIdentifier()->getName());
3120
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003121 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003122 }
3123
Douglas Gregor78205d42010-01-20 21:45:58 +00003124 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003125 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003126
Douglas Gregor78205d42010-01-20 21:45:58 +00003127 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3128 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3129 // and returns different names. NamedDecl returns the class name and
3130 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003131 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003132
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003133 if (isa<UsingDirectiveDecl>(D))
3134 return createCXString("");
3135
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003136 llvm::SmallString<1024> S;
3137 llvm::raw_svector_ostream os(S);
3138 ND->printName(os);
3139
3140 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003141}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003142
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003143CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003144 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003145 return clang_getTranslationUnitSpelling(
3146 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003147
Steve Narofff334b4e2009-09-02 18:26:48 +00003148 if (clang_isReference(C.kind)) {
3149 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003150 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003151 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003152 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003153 }
3154 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003155 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003156 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003157 }
3158 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003159 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003160 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003161 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003162 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003163 case CXCursor_CXXBaseSpecifier: {
3164 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3165 return createCXString(B->getType().getAsString());
3166 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003167 case CXCursor_TypeRef: {
3168 TypeDecl *Type = getCursorTypeRef(C).first;
3169 assert(Type && "Missing type decl");
3170
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003171 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3172 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003173 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003174 case CXCursor_TemplateRef: {
3175 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003176 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003177
3178 return createCXString(Template->getNameAsString());
3179 }
Douglas Gregor69319002010-08-31 23:48:11 +00003180
3181 case CXCursor_NamespaceRef: {
3182 NamedDecl *NS = getCursorNamespaceRef(C).first;
3183 assert(NS && "Missing namespace decl");
3184
3185 return createCXString(NS->getNameAsString());
3186 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003187
Douglas Gregora67e03f2010-09-09 21:42:20 +00003188 case CXCursor_MemberRef: {
3189 FieldDecl *Field = getCursorMemberRef(C).first;
3190 assert(Field && "Missing member decl");
3191
3192 return createCXString(Field->getNameAsString());
3193 }
3194
Douglas Gregor36897b02010-09-10 00:22:18 +00003195 case CXCursor_LabelRef: {
3196 LabelStmt *Label = getCursorLabelRef(C).first;
3197 assert(Label && "Missing label");
3198
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003199 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003200 }
3201
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003202 case CXCursor_OverloadedDeclRef: {
3203 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3204 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3205 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3206 return createCXString(ND->getNameAsString());
3207 return createCXString("");
3208 }
3209 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3210 return createCXString(E->getName().getAsString());
3211 OverloadedTemplateStorage *Ovl
3212 = Storage.get<OverloadedTemplateStorage*>();
3213 if (Ovl->size() == 0)
3214 return createCXString("");
3215 return createCXString((*Ovl->begin())->getNameAsString());
3216 }
3217
Daniel Dunbaracca7252009-11-30 20:42:49 +00003218 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003219 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003220 }
3221 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003222
3223 if (clang_isExpression(C.kind)) {
3224 Decl *D = getDeclFromExpr(getCursorExpr(C));
3225 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003226 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003227 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003228 }
3229
Douglas Gregor36897b02010-09-10 00:22:18 +00003230 if (clang_isStatement(C.kind)) {
3231 Stmt *S = getCursorStmt(C);
3232 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003233 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003234
3235 return createCXString("");
3236 }
3237
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003238 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003239 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003240 ->getNameStart());
3241
Douglas Gregor572feb22010-03-18 18:04:21 +00003242 if (C.kind == CXCursor_MacroDefinition)
3243 return createCXString(getCursorMacroDefinition(C)->getName()
3244 ->getNameStart());
3245
Douglas Gregorecdcb882010-10-20 22:00:55 +00003246 if (C.kind == CXCursor_InclusionDirective)
3247 return createCXString(getCursorInclusionDirective(C)->getFileName());
3248
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003249 if (clang_isDeclaration(C.kind))
3250 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003251
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003252 if (C.kind == CXCursor_AnnotateAttr) {
3253 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3254 return createCXString(AA->getAnnotation());
3255 }
3256
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003257 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003258}
3259
Douglas Gregor358559d2010-10-02 22:49:11 +00003260CXString clang_getCursorDisplayName(CXCursor C) {
3261 if (!clang_isDeclaration(C.kind))
3262 return clang_getCursorSpelling(C);
3263
3264 Decl *D = getCursorDecl(C);
3265 if (!D)
3266 return createCXString("");
3267
Douglas Gregor30c42402011-09-27 22:38:19 +00003268 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003269 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3270 D = FunTmpl->getTemplatedDecl();
3271
3272 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3273 llvm::SmallString<64> Str;
3274 llvm::raw_svector_ostream OS(Str);
3275 OS << Function->getNameAsString();
3276 if (Function->getPrimaryTemplate())
3277 OS << "<>";
3278 OS << "(";
3279 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3280 if (I)
3281 OS << ", ";
3282 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3283 }
3284
3285 if (Function->isVariadic()) {
3286 if (Function->getNumParams())
3287 OS << ", ";
3288 OS << "...";
3289 }
3290 OS << ")";
3291 return createCXString(OS.str());
3292 }
3293
3294 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3295 llvm::SmallString<64> Str;
3296 llvm::raw_svector_ostream OS(Str);
3297 OS << ClassTemplate->getNameAsString();
3298 OS << "<";
3299 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3300 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3301 if (I)
3302 OS << ", ";
3303
3304 NamedDecl *Param = Params->getParam(I);
3305 if (Param->getIdentifier()) {
3306 OS << Param->getIdentifier()->getName();
3307 continue;
3308 }
3309
3310 // There is no parameter name, which makes this tricky. Try to come up
3311 // with something useful that isn't too long.
3312 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3313 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3314 else if (NonTypeTemplateParmDecl *NTTP
3315 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3316 OS << NTTP->getType().getAsString(Policy);
3317 else
3318 OS << "template<...> class";
3319 }
3320
3321 OS << ">";
3322 return createCXString(OS.str());
3323 }
3324
3325 if (ClassTemplateSpecializationDecl *ClassSpec
3326 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3327 // If the type was explicitly written, use that.
3328 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3329 return createCXString(TSInfo->getType().getAsString(Policy));
3330
3331 llvm::SmallString<64> Str;
3332 llvm::raw_svector_ostream OS(Str);
3333 OS << ClassSpec->getNameAsString();
3334 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003335 ClassSpec->getTemplateArgs().data(),
3336 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003337 Policy);
3338 return createCXString(OS.str());
3339 }
3340
3341 return clang_getCursorSpelling(C);
3342}
3343
Ted Kremeneke68fff62010-02-17 00:41:32 +00003344CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003345 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003346 case CXCursor_FunctionDecl:
3347 return createCXString("FunctionDecl");
3348 case CXCursor_TypedefDecl:
3349 return createCXString("TypedefDecl");
3350 case CXCursor_EnumDecl:
3351 return createCXString("EnumDecl");
3352 case CXCursor_EnumConstantDecl:
3353 return createCXString("EnumConstantDecl");
3354 case CXCursor_StructDecl:
3355 return createCXString("StructDecl");
3356 case CXCursor_UnionDecl:
3357 return createCXString("UnionDecl");
3358 case CXCursor_ClassDecl:
3359 return createCXString("ClassDecl");
3360 case CXCursor_FieldDecl:
3361 return createCXString("FieldDecl");
3362 case CXCursor_VarDecl:
3363 return createCXString("VarDecl");
3364 case CXCursor_ParmDecl:
3365 return createCXString("ParmDecl");
3366 case CXCursor_ObjCInterfaceDecl:
3367 return createCXString("ObjCInterfaceDecl");
3368 case CXCursor_ObjCCategoryDecl:
3369 return createCXString("ObjCCategoryDecl");
3370 case CXCursor_ObjCProtocolDecl:
3371 return createCXString("ObjCProtocolDecl");
3372 case CXCursor_ObjCPropertyDecl:
3373 return createCXString("ObjCPropertyDecl");
3374 case CXCursor_ObjCIvarDecl:
3375 return createCXString("ObjCIvarDecl");
3376 case CXCursor_ObjCInstanceMethodDecl:
3377 return createCXString("ObjCInstanceMethodDecl");
3378 case CXCursor_ObjCClassMethodDecl:
3379 return createCXString("ObjCClassMethodDecl");
3380 case CXCursor_ObjCImplementationDecl:
3381 return createCXString("ObjCImplementationDecl");
3382 case CXCursor_ObjCCategoryImplDecl:
3383 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003384 case CXCursor_CXXMethod:
3385 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003386 case CXCursor_UnexposedDecl:
3387 return createCXString("UnexposedDecl");
3388 case CXCursor_ObjCSuperClassRef:
3389 return createCXString("ObjCSuperClassRef");
3390 case CXCursor_ObjCProtocolRef:
3391 return createCXString("ObjCProtocolRef");
3392 case CXCursor_ObjCClassRef:
3393 return createCXString("ObjCClassRef");
3394 case CXCursor_TypeRef:
3395 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003396 case CXCursor_TemplateRef:
3397 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003398 case CXCursor_NamespaceRef:
3399 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003400 case CXCursor_MemberRef:
3401 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003402 case CXCursor_LabelRef:
3403 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003404 case CXCursor_OverloadedDeclRef:
3405 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003406 case CXCursor_IntegerLiteral:
3407 return createCXString("IntegerLiteral");
3408 case CXCursor_FloatingLiteral:
3409 return createCXString("FloatingLiteral");
3410 case CXCursor_ImaginaryLiteral:
3411 return createCXString("ImaginaryLiteral");
3412 case CXCursor_StringLiteral:
3413 return createCXString("StringLiteral");
3414 case CXCursor_CharacterLiteral:
3415 return createCXString("CharacterLiteral");
3416 case CXCursor_ParenExpr:
3417 return createCXString("ParenExpr");
3418 case CXCursor_UnaryOperator:
3419 return createCXString("UnaryOperator");
3420 case CXCursor_ArraySubscriptExpr:
3421 return createCXString("ArraySubscriptExpr");
3422 case CXCursor_BinaryOperator:
3423 return createCXString("BinaryOperator");
3424 case CXCursor_CompoundAssignOperator:
3425 return createCXString("CompoundAssignOperator");
3426 case CXCursor_ConditionalOperator:
3427 return createCXString("ConditionalOperator");
3428 case CXCursor_CStyleCastExpr:
3429 return createCXString("CStyleCastExpr");
3430 case CXCursor_CompoundLiteralExpr:
3431 return createCXString("CompoundLiteralExpr");
3432 case CXCursor_InitListExpr:
3433 return createCXString("InitListExpr");
3434 case CXCursor_AddrLabelExpr:
3435 return createCXString("AddrLabelExpr");
3436 case CXCursor_StmtExpr:
3437 return createCXString("StmtExpr");
3438 case CXCursor_GenericSelectionExpr:
3439 return createCXString("GenericSelectionExpr");
3440 case CXCursor_GNUNullExpr:
3441 return createCXString("GNUNullExpr");
3442 case CXCursor_CXXStaticCastExpr:
3443 return createCXString("CXXStaticCastExpr");
3444 case CXCursor_CXXDynamicCastExpr:
3445 return createCXString("CXXDynamicCastExpr");
3446 case CXCursor_CXXReinterpretCastExpr:
3447 return createCXString("CXXReinterpretCastExpr");
3448 case CXCursor_CXXConstCastExpr:
3449 return createCXString("CXXConstCastExpr");
3450 case CXCursor_CXXFunctionalCastExpr:
3451 return createCXString("CXXFunctionalCastExpr");
3452 case CXCursor_CXXTypeidExpr:
3453 return createCXString("CXXTypeidExpr");
3454 case CXCursor_CXXBoolLiteralExpr:
3455 return createCXString("CXXBoolLiteralExpr");
3456 case CXCursor_CXXNullPtrLiteralExpr:
3457 return createCXString("CXXNullPtrLiteralExpr");
3458 case CXCursor_CXXThisExpr:
3459 return createCXString("CXXThisExpr");
3460 case CXCursor_CXXThrowExpr:
3461 return createCXString("CXXThrowExpr");
3462 case CXCursor_CXXNewExpr:
3463 return createCXString("CXXNewExpr");
3464 case CXCursor_CXXDeleteExpr:
3465 return createCXString("CXXDeleteExpr");
3466 case CXCursor_UnaryExpr:
3467 return createCXString("UnaryExpr");
3468 case CXCursor_ObjCStringLiteral:
3469 return createCXString("ObjCStringLiteral");
3470 case CXCursor_ObjCEncodeExpr:
3471 return createCXString("ObjCEncodeExpr");
3472 case CXCursor_ObjCSelectorExpr:
3473 return createCXString("ObjCSelectorExpr");
3474 case CXCursor_ObjCProtocolExpr:
3475 return createCXString("ObjCProtocolExpr");
3476 case CXCursor_ObjCBridgedCastExpr:
3477 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003478 case CXCursor_BlockExpr:
3479 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003480 case CXCursor_PackExpansionExpr:
3481 return createCXString("PackExpansionExpr");
3482 case CXCursor_SizeOfPackExpr:
3483 return createCXString("SizeOfPackExpr");
3484 case CXCursor_UnexposedExpr:
3485 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003486 case CXCursor_DeclRefExpr:
3487 return createCXString("DeclRefExpr");
3488 case CXCursor_MemberRefExpr:
3489 return createCXString("MemberRefExpr");
3490 case CXCursor_CallExpr:
3491 return createCXString("CallExpr");
3492 case CXCursor_ObjCMessageExpr:
3493 return createCXString("ObjCMessageExpr");
3494 case CXCursor_UnexposedStmt:
3495 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003496 case CXCursor_DeclStmt:
3497 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003498 case CXCursor_LabelStmt:
3499 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003500 case CXCursor_CompoundStmt:
3501 return createCXString("CompoundStmt");
3502 case CXCursor_CaseStmt:
3503 return createCXString("CaseStmt");
3504 case CXCursor_DefaultStmt:
3505 return createCXString("DefaultStmt");
3506 case CXCursor_IfStmt:
3507 return createCXString("IfStmt");
3508 case CXCursor_SwitchStmt:
3509 return createCXString("SwitchStmt");
3510 case CXCursor_WhileStmt:
3511 return createCXString("WhileStmt");
3512 case CXCursor_DoStmt:
3513 return createCXString("DoStmt");
3514 case CXCursor_ForStmt:
3515 return createCXString("ForStmt");
3516 case CXCursor_GotoStmt:
3517 return createCXString("GotoStmt");
3518 case CXCursor_IndirectGotoStmt:
3519 return createCXString("IndirectGotoStmt");
3520 case CXCursor_ContinueStmt:
3521 return createCXString("ContinueStmt");
3522 case CXCursor_BreakStmt:
3523 return createCXString("BreakStmt");
3524 case CXCursor_ReturnStmt:
3525 return createCXString("ReturnStmt");
3526 case CXCursor_AsmStmt:
3527 return createCXString("AsmStmt");
3528 case CXCursor_ObjCAtTryStmt:
3529 return createCXString("ObjCAtTryStmt");
3530 case CXCursor_ObjCAtCatchStmt:
3531 return createCXString("ObjCAtCatchStmt");
3532 case CXCursor_ObjCAtFinallyStmt:
3533 return createCXString("ObjCAtFinallyStmt");
3534 case CXCursor_ObjCAtThrowStmt:
3535 return createCXString("ObjCAtThrowStmt");
3536 case CXCursor_ObjCAtSynchronizedStmt:
3537 return createCXString("ObjCAtSynchronizedStmt");
3538 case CXCursor_ObjCAutoreleasePoolStmt:
3539 return createCXString("ObjCAutoreleasePoolStmt");
3540 case CXCursor_ObjCForCollectionStmt:
3541 return createCXString("ObjCForCollectionStmt");
3542 case CXCursor_CXXCatchStmt:
3543 return createCXString("CXXCatchStmt");
3544 case CXCursor_CXXTryStmt:
3545 return createCXString("CXXTryStmt");
3546 case CXCursor_CXXForRangeStmt:
3547 return createCXString("CXXForRangeStmt");
3548 case CXCursor_SEHTryStmt:
3549 return createCXString("SEHTryStmt");
3550 case CXCursor_SEHExceptStmt:
3551 return createCXString("SEHExceptStmt");
3552 case CXCursor_SEHFinallyStmt:
3553 return createCXString("SEHFinallyStmt");
3554 case CXCursor_NullStmt:
3555 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003556 case CXCursor_InvalidFile:
3557 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003558 case CXCursor_InvalidCode:
3559 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003560 case CXCursor_NoDeclFound:
3561 return createCXString("NoDeclFound");
3562 case CXCursor_NotImplemented:
3563 return createCXString("NotImplemented");
3564 case CXCursor_TranslationUnit:
3565 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003566 case CXCursor_UnexposedAttr:
3567 return createCXString("UnexposedAttr");
3568 case CXCursor_IBActionAttr:
3569 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003570 case CXCursor_IBOutletAttr:
3571 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003572 case CXCursor_IBOutletCollectionAttr:
3573 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003574 case CXCursor_CXXFinalAttr:
3575 return createCXString("attribute(final)");
3576 case CXCursor_CXXOverrideAttr:
3577 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003578 case CXCursor_AnnotateAttr:
3579 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003580 case CXCursor_PreprocessingDirective:
3581 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003582 case CXCursor_MacroDefinition:
3583 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003584 case CXCursor_MacroExpansion:
3585 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003586 case CXCursor_InclusionDirective:
3587 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003588 case CXCursor_Namespace:
3589 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003590 case CXCursor_LinkageSpec:
3591 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003592 case CXCursor_CXXBaseSpecifier:
3593 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003594 case CXCursor_Constructor:
3595 return createCXString("CXXConstructor");
3596 case CXCursor_Destructor:
3597 return createCXString("CXXDestructor");
3598 case CXCursor_ConversionFunction:
3599 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003600 case CXCursor_TemplateTypeParameter:
3601 return createCXString("TemplateTypeParameter");
3602 case CXCursor_NonTypeTemplateParameter:
3603 return createCXString("NonTypeTemplateParameter");
3604 case CXCursor_TemplateTemplateParameter:
3605 return createCXString("TemplateTemplateParameter");
3606 case CXCursor_FunctionTemplate:
3607 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003608 case CXCursor_ClassTemplate:
3609 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003610 case CXCursor_ClassTemplatePartialSpecialization:
3611 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003612 case CXCursor_NamespaceAlias:
3613 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003614 case CXCursor_UsingDirective:
3615 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003616 case CXCursor_UsingDeclaration:
3617 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003618 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003619 return createCXString("TypeAliasDecl");
3620 case CXCursor_ObjCSynthesizeDecl:
3621 return createCXString("ObjCSynthesizeDecl");
3622 case CXCursor_ObjCDynamicDecl:
3623 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003624 case CXCursor_CXXAccessSpecifier:
3625 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003626 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003627
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003628 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003629 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003630}
Steve Naroff89922f82009-08-31 00:59:03 +00003631
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003632struct GetCursorData {
3633 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003634 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003635 CXCursor &BestCursor;
3636
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003637 GetCursorData(SourceManager &SM,
3638 SourceLocation tokenBegin, CXCursor &outputCursor)
3639 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3640 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3641 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003642};
3643
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003644static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3645 CXCursor parent,
3646 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003647 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3648 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003649
3650 // If we point inside a macro argument we should provide info of what the
3651 // token is so use the actual cursor, don't replace it with a macro expansion
3652 // cursor.
3653 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3654 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003655
3656 if (clang_isDeclaration(cursor.kind)) {
3657 // Avoid having the implicit methods override the property decls.
3658 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3659 if (MD->isImplicit())
3660 return CXChildVisit_Break;
3661 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003662
3663 if (clang_isExpression(cursor.kind) &&
3664 clang_isDeclaration(BestCursor->kind)) {
3665 Decl *D = getCursorDecl(*BestCursor);
3666
3667 // Avoid having the cursor of an expression replace the declaration cursor
3668 // when the expression source range overlaps the declaration range.
3669 // This can happen for C++ constructor expressions whose range generally
3670 // include the variable declaration, e.g.:
3671 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3672 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3673 D->getLocation() == Data->TokenBeginLoc)
3674 return CXChildVisit_Break;
3675 }
3676
Douglas Gregor93798e22010-11-05 21:11:19 +00003677 // If our current best cursor is the construction of a temporary object,
3678 // don't replace that cursor with a type reference, because we want
3679 // clang_getCursor() to point at the constructor.
3680 if (clang_isExpression(BestCursor->kind) &&
3681 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003682 cursor.kind == CXCursor_TypeRef) {
3683 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3684 // as having the actual point on the type reference.
3685 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003686 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003687 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003688
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003689 *BestCursor = cursor;
3690 return CXChildVisit_Recurse;
3691}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003692
Douglas Gregorb9790342010-01-22 21:44:22 +00003693CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3694 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003695 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003696
Ted Kremeneka60ed472010-11-16 08:15:36 +00003697 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003698 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3699
Ted Kremeneka297de22010-01-25 22:34:44 +00003700 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003701 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003702
Douglas Gregor40749ee2010-11-03 00:35:38 +00003703 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003704 if (Logging) {
3705 CXFile SearchFile;
3706 unsigned SearchLine, SearchColumn;
3707 CXFile ResultFile;
3708 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003709 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3710 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003711 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3712
Chandler Carruth20174222011-08-31 16:53:37 +00003713 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3714 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3715 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003716 SearchFileName = clang_getFileName(SearchFile);
3717 ResultFileName = clang_getFileName(ResultFile);
3718 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003719 USR = clang_getCursorUSR(Result);
3720 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003721 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3722 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003723 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3724 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003725 clang_disposeString(SearchFileName);
3726 clang_disposeString(ResultFileName);
3727 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003728 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003729
3730 CXCursor Definition = clang_getCursorDefinition(Result);
3731 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3732 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3733 CXString DefinitionKindSpelling
3734 = clang_getCursorKindSpelling(Definition.kind);
3735 CXFile DefinitionFile;
3736 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003737 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3738 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003739 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3740 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3741 clang_getCString(DefinitionKindSpelling),
3742 clang_getCString(DefinitionFileName),
3743 DefinitionLine, DefinitionColumn);
3744 clang_disposeString(DefinitionFileName);
3745 clang_disposeString(DefinitionKindSpelling);
3746 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003747 }
3748
Ted Kremeneke68fff62010-02-17 00:41:32 +00003749 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003750}
3751
Ted Kremenek73885552009-11-17 19:28:59 +00003752CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003753 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003754}
3755
3756unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003757 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003758}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003759
Douglas Gregor9ce55842010-11-20 00:09:34 +00003760unsigned clang_hashCursor(CXCursor C) {
3761 unsigned Index = 0;
3762 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3763 Index = 1;
3764
3765 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3766 std::make_pair(C.kind, C.data[Index]));
3767}
3768
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003769unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003770 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3771}
3772
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003773unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003774 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3775}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003776
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003777unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003778 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3779}
3780
Douglas Gregor97b98722010-01-19 23:20:36 +00003781unsigned clang_isExpression(enum CXCursorKind K) {
3782 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3783}
3784
3785unsigned clang_isStatement(enum CXCursorKind K) {
3786 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3787}
3788
Douglas Gregor8be80e12011-07-06 03:00:34 +00003789unsigned clang_isAttribute(enum CXCursorKind K) {
3790 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3791}
3792
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003793unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3794 return K == CXCursor_TranslationUnit;
3795}
3796
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003797unsigned clang_isPreprocessing(enum CXCursorKind K) {
3798 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3799}
3800
Ted Kremenekad6eff62010-03-08 21:17:29 +00003801unsigned clang_isUnexposed(enum CXCursorKind K) {
3802 switch (K) {
3803 case CXCursor_UnexposedDecl:
3804 case CXCursor_UnexposedExpr:
3805 case CXCursor_UnexposedStmt:
3806 case CXCursor_UnexposedAttr:
3807 return true;
3808 default:
3809 return false;
3810 }
3811}
3812
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003813CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003814 return C.kind;
3815}
3816
Douglas Gregor98258af2010-01-18 22:46:11 +00003817CXSourceLocation clang_getCursorLocation(CXCursor C) {
3818 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003819 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003820 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003821 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3822 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003823 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003824 }
3825
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003826 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003827 std::pair<ObjCProtocolDecl *, SourceLocation> P
3828 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003829 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003830 }
3831
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003833 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3834 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003835 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003836 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003837
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003838 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003839 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003840 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003841 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003842
3843 case CXCursor_TemplateRef: {
3844 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3845 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3846 }
3847
Douglas Gregor69319002010-08-31 23:48:11 +00003848 case CXCursor_NamespaceRef: {
3849 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3850 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3851 }
3852
Douglas Gregora67e03f2010-09-09 21:42:20 +00003853 case CXCursor_MemberRef: {
3854 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3855 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3856 }
3857
Ted Kremenek3064ef92010-08-27 21:34:58 +00003858 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003859 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3860 if (!BaseSpec)
3861 return clang_getNullLocation();
3862
3863 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3864 return cxloc::translateSourceLocation(getCursorContext(C),
3865 TSInfo->getTypeLoc().getBeginLoc());
3866
3867 return cxloc::translateSourceLocation(getCursorContext(C),
3868 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003869 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003870
Douglas Gregor36897b02010-09-10 00:22:18 +00003871 case CXCursor_LabelRef: {
3872 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3873 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3874 }
3875
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003876 case CXCursor_OverloadedDeclRef:
3877 return cxloc::translateSourceLocation(getCursorContext(C),
3878 getCursorOverloadedDeclRef(C).second);
3879
Douglas Gregorf46034a2010-01-18 23:41:10 +00003880 default:
3881 // FIXME: Need a way to enumerate all non-reference cases.
3882 llvm_unreachable("Missed a reference kind");
3883 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003884 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003885
3886 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003888 getLocationFromExpr(getCursorExpr(C)));
3889
Douglas Gregor36897b02010-09-10 00:22:18 +00003890 if (clang_isStatement(C.kind))
3891 return cxloc::translateSourceLocation(getCursorContext(C),
3892 getCursorStmt(C)->getLocStart());
3893
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003894 if (C.kind == CXCursor_PreprocessingDirective) {
3895 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3896 return cxloc::translateSourceLocation(getCursorContext(C), L);
3897 }
Douglas Gregor48072312010-03-18 15:23:44 +00003898
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003899 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003900 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003901 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003902 return cxloc::translateSourceLocation(getCursorContext(C), L);
3903 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003904
3905 if (C.kind == CXCursor_MacroDefinition) {
3906 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3907 return cxloc::translateSourceLocation(getCursorContext(C), L);
3908 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003909
3910 if (C.kind == CXCursor_InclusionDirective) {
3911 SourceLocation L
3912 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3913 return cxloc::translateSourceLocation(getCursorContext(C), L);
3914 }
3915
Ted Kremenek9a700d22010-05-12 06:16:13 +00003916 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003917 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003918
Douglas Gregorf46034a2010-01-18 23:41:10 +00003919 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003920 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003921 // FIXME: Multiple variables declared in a single declaration
3922 // currently lack the information needed to correctly determine their
3923 // ranges when accounting for the type-specifier. We use context
3924 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3925 // and if so, whether it is the first decl.
3926 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3927 if (!cxcursor::isFirstInDeclGroup(C))
3928 Loc = VD->getLocation();
3929 }
3930
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003931 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003932}
Douglas Gregora7bde202010-01-19 00:34:46 +00003933
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003934} // end extern "C"
3935
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003936CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3937 assert(TU);
3938
3939 // Guard against an invalid SourceLocation, or we may assert in one
3940 // of the following calls.
3941 if (SLoc.isInvalid())
3942 return clang_getNullCursor();
3943
3944 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3945
3946 // Translate the given source location to make it point at the beginning of
3947 // the token under the cursor.
3948 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3949 CXXUnit->getASTContext().getLangOptions());
3950
3951 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3952 if (SLoc.isValid()) {
3953 // FIXME: Would be great to have a "hint" cursor, then walk from that
3954 // hint cursor upward until we find a cursor whose source range encloses
3955 // the region of interest, rather than starting from the translation unit.
3956 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
3957 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3958 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3959 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00003960 /*VisitIncludedPreprocessingEntries=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003961 SourceLocation(SLoc));
3962 CursorVis.VisitChildren(Parent);
3963 }
3964
3965 return Result;
3966}
3967
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003968static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003969 if (clang_isReference(C.kind)) {
3970 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003971 case CXCursor_ObjCSuperClassRef:
3972 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003973
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003974 case CXCursor_ObjCProtocolRef:
3975 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003976
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003977 case CXCursor_ObjCClassRef:
3978 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003979
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003980 case CXCursor_TypeRef:
3981 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003982
3983 case CXCursor_TemplateRef:
3984 return getCursorTemplateRef(C).second;
3985
Douglas Gregor69319002010-08-31 23:48:11 +00003986 case CXCursor_NamespaceRef:
3987 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003988
3989 case CXCursor_MemberRef:
3990 return getCursorMemberRef(C).second;
3991
Ted Kremenek3064ef92010-08-27 21:34:58 +00003992 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003993 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003994
Douglas Gregor36897b02010-09-10 00:22:18 +00003995 case CXCursor_LabelRef:
3996 return getCursorLabelRef(C).second;
3997
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003998 case CXCursor_OverloadedDeclRef:
3999 return getCursorOverloadedDeclRef(C).second;
4000
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004001 default:
4002 // FIXME: Need a way to enumerate all non-reference cases.
4003 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00004004 }
4005 }
Douglas Gregor97b98722010-01-19 23:20:36 +00004006
4007 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004008 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00004009
4010 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004011 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004012
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00004013 if (clang_isAttribute(C.kind))
4014 return getCursorAttr(C)->getRange();
4015
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004016 if (C.kind == CXCursor_PreprocessingDirective)
4017 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00004018
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004019 if (C.kind == CXCursor_MacroExpansion) {
4020 ASTUnit *TU = getCursorASTUnit(C);
4021 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4022 return TU->mapRangeFromPreamble(Range);
4023 }
Douglas Gregor572feb22010-03-18 18:04:21 +00004024
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004025 if (C.kind == CXCursor_MacroDefinition) {
4026 ASTUnit *TU = getCursorASTUnit(C);
4027 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4028 return TU->mapRangeFromPreamble(Range);
4029 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004030
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004031 if (C.kind == CXCursor_InclusionDirective) {
4032 ASTUnit *TU = getCursorASTUnit(C);
4033 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4034 return TU->mapRangeFromPreamble(Range);
4035 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00004036
Ted Kremenek007a7c92010-11-01 23:26:51 +00004037 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4038 Decl *D = cxcursor::getCursorDecl(C);
4039 SourceRange R = D->getSourceRange();
4040 // FIXME: Multiple variables declared in a single declaration
4041 // currently lack the information needed to correctly determine their
4042 // ranges when accounting for the type-specifier. We use context
4043 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4044 // and if so, whether it is the first decl.
4045 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4046 if (!cxcursor::isFirstInDeclGroup(C))
4047 R.setBegin(VD->getLocation());
4048 }
4049 return R;
4050 }
Douglas Gregor66537982010-11-17 17:14:07 +00004051 return SourceRange();
4052}
4053
4054/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4055/// the decl-specifier-seq for declarations.
4056static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4057 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4058 Decl *D = cxcursor::getCursorDecl(C);
4059 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004060
Douglas Gregor2494dd02011-03-01 01:34:45 +00004061 // Adjust the start of the location for declarations preceded by
4062 // declaration specifiers.
4063 SourceLocation StartLoc;
4064 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4065 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4066 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4067 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4068 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4069 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4070 }
4071
4072 if (StartLoc.isValid() && R.getBegin().isValid() &&
4073 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4074 R.setBegin(StartLoc);
4075
4076 // FIXME: Multiple variables declared in a single declaration
4077 // currently lack the information needed to correctly determine their
4078 // ranges when accounting for the type-specifier. We use context
4079 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4080 // and if so, whether it is the first decl.
4081 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4082 if (!cxcursor::isFirstInDeclGroup(C))
4083 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004084 }
4085
4086 return R;
4087 }
4088
4089 return getRawCursorExtent(C);
4090}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004091
4092extern "C" {
4093
4094CXSourceRange clang_getCursorExtent(CXCursor C) {
4095 SourceRange R = getRawCursorExtent(C);
4096 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004097 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004098
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004099 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004100}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004101
4102CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004103 if (clang_isInvalid(C.kind))
4104 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004105
Ted Kremeneka60ed472010-11-16 08:15:36 +00004106 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004107 if (clang_isDeclaration(C.kind)) {
4108 Decl *D = getCursorDecl(C);
4109 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004110 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004111 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004112 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004113 if (ObjCForwardProtocolDecl *Protocols
4114 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004115 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004116 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004117 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4118 return MakeCXCursor(Property, tu);
4119
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004120 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004121 }
4122
Douglas Gregor97b98722010-01-19 23:20:36 +00004123 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004124 Expr *E = getCursorExpr(C);
4125 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004126 if (D) {
4127 CXCursor declCursor = MakeCXCursor(D, tu);
4128 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4129 declCursor);
4130 return declCursor;
4131 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004132
4133 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004134 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004135
Douglas Gregor97b98722010-01-19 23:20:36 +00004136 return clang_getNullCursor();
4137 }
4138
Douglas Gregor36897b02010-09-10 00:22:18 +00004139 if (clang_isStatement(C.kind)) {
4140 Stmt *S = getCursorStmt(C);
4141 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004142 if (LabelDecl *label = Goto->getLabel())
4143 if (LabelStmt *labelS = label->getStmt())
4144 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004145
4146 return clang_getNullCursor();
4147 }
4148
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004149 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004150 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004151 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004152 }
4153
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004154 if (!clang_isReference(C.kind))
4155 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004156
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004157 switch (C.kind) {
4158 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004159 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004160
4161 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004162 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004163
4164 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004165 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004166
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004167 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004168 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004169
4170 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004171 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004172
Douglas Gregor69319002010-08-31 23:48:11 +00004173 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004174 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004175
Douglas Gregora67e03f2010-09-09 21:42:20 +00004176 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004177 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004178
Ted Kremenek3064ef92010-08-27 21:34:58 +00004179 case CXCursor_CXXBaseSpecifier: {
4180 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4181 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004182 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004183 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004184
Douglas Gregor36897b02010-09-10 00:22:18 +00004185 case CXCursor_LabelRef:
4186 // FIXME: We end up faking the "parent" declaration here because we
4187 // don't want to make CXCursor larger.
4188 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004189 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4190 .getTranslationUnitDecl(),
4191 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004192
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004193 case CXCursor_OverloadedDeclRef:
4194 return C;
4195
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004196 default:
4197 // We would prefer to enumerate all non-reference cursor kinds here.
4198 llvm_unreachable("Unhandled reference cursor kind");
4199 break;
4200 }
4201 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004202
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004203 return clang_getNullCursor();
4204}
4205
Douglas Gregorb6998662010-01-19 19:34:47 +00004206CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004207 if (clang_isInvalid(C.kind))
4208 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004209
Ted Kremeneka60ed472010-11-16 08:15:36 +00004210 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004211
Douglas Gregorb6998662010-01-19 19:34:47 +00004212 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004213 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004214 C = clang_getCursorReferenced(C);
4215 WasReference = true;
4216 }
4217
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004218 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004219 return clang_getCursorReferenced(C);
4220
Douglas Gregorb6998662010-01-19 19:34:47 +00004221 if (!clang_isDeclaration(C.kind))
4222 return clang_getNullCursor();
4223
4224 Decl *D = getCursorDecl(C);
4225 if (!D)
4226 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004227
Douglas Gregorb6998662010-01-19 19:34:47 +00004228 switch (D->getKind()) {
4229 // Declaration kinds that don't really separate the notions of
4230 // declaration and definition.
4231 case Decl::Namespace:
4232 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004233 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004234 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004235 case Decl::TemplateTypeParm:
4236 case Decl::EnumConstant:
4237 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004238 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004239 case Decl::ObjCIvar:
4240 case Decl::ObjCAtDefsField:
4241 case Decl::ImplicitParam:
4242 case Decl::ParmVar:
4243 case Decl::NonTypeTemplateParm:
4244 case Decl::TemplateTemplateParm:
4245 case Decl::ObjCCategoryImpl:
4246 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004247 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004248 case Decl::LinkageSpec:
4249 case Decl::ObjCPropertyImpl:
4250 case Decl::FileScopeAsm:
4251 case Decl::StaticAssert:
4252 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004253 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004254 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004255 return C;
4256
4257 // Declaration kinds that don't make any sense here, but are
4258 // nonetheless harmless.
4259 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004260 break;
4261
4262 // Declaration kinds for which the definition is not resolvable.
4263 case Decl::UnresolvedUsingTypename:
4264 case Decl::UnresolvedUsingValue:
4265 break;
4266
4267 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004268 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004269 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004270
4271 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004272 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004273
4274 case Decl::Enum:
4275 case Decl::Record:
4276 case Decl::CXXRecord:
4277 case Decl::ClassTemplateSpecialization:
4278 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004279 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004280 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004281 return clang_getNullCursor();
4282
4283 case Decl::Function:
4284 case Decl::CXXMethod:
4285 case Decl::CXXConstructor:
4286 case Decl::CXXDestructor:
4287 case Decl::CXXConversion: {
4288 const FunctionDecl *Def = 0;
4289 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004290 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004291 return clang_getNullCursor();
4292 }
4293
4294 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004295 // Ask the variable if it has a definition.
4296 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004297 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004298 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004299 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004300
Douglas Gregorb6998662010-01-19 19:34:47 +00004301 case Decl::FunctionTemplate: {
4302 const FunctionDecl *Def = 0;
4303 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004304 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004305 return clang_getNullCursor();
4306 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004307
Douglas Gregorb6998662010-01-19 19:34:47 +00004308 case Decl::ClassTemplate: {
4309 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004310 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004311 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004312 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004313 return clang_getNullCursor();
4314 }
4315
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004316 case Decl::Using:
4317 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004318 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004319
4320 case Decl::UsingShadow:
4321 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004322 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004323 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004324
4325 case Decl::ObjCMethod: {
4326 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4327 if (Method->isThisDeclarationADefinition())
4328 return C;
4329
4330 // Dig out the method definition in the associated
4331 // @implementation, if we have it.
4332 // FIXME: The ASTs should make finding the definition easier.
4333 if (ObjCInterfaceDecl *Class
4334 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4335 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4336 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4337 Method->isInstanceMethod()))
4338 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004339 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004340
4341 return clang_getNullCursor();
4342 }
4343
4344 case Decl::ObjCCategory:
4345 if (ObjCCategoryImplDecl *Impl
4346 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004347 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004348 return clang_getNullCursor();
4349
4350 case Decl::ObjCProtocol:
4351 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4352 return C;
4353 return clang_getNullCursor();
4354
4355 case Decl::ObjCInterface:
4356 // There are two notions of a "definition" for an Objective-C
4357 // class: the interface and its implementation. When we resolved a
4358 // reference to an Objective-C class, produce the @interface as
4359 // the definition; when we were provided with the interface,
4360 // produce the @implementation as the definition.
4361 if (WasReference) {
4362 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4363 return C;
4364 } else if (ObjCImplementationDecl *Impl
4365 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004366 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004367 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004368
Douglas Gregorb6998662010-01-19 19:34:47 +00004369 case Decl::ObjCProperty:
4370 // FIXME: We don't really know where to find the
4371 // ObjCPropertyImplDecls that implement this property.
4372 return clang_getNullCursor();
4373
4374 case Decl::ObjCCompatibleAlias:
4375 if (ObjCInterfaceDecl *Class
4376 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4377 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004378 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004379
Douglas Gregorb6998662010-01-19 19:34:47 +00004380 return clang_getNullCursor();
4381
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004382 case Decl::ObjCForwardProtocol:
4383 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004384 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004385
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004386 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004387 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004388 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004389
4390 case Decl::Friend:
4391 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004392 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004393 return clang_getNullCursor();
4394
4395 case Decl::FriendTemplate:
4396 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004397 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004398 return clang_getNullCursor();
4399 }
4400
4401 return clang_getNullCursor();
4402}
4403
4404unsigned clang_isCursorDefinition(CXCursor C) {
4405 if (!clang_isDeclaration(C.kind))
4406 return 0;
4407
4408 return clang_getCursorDefinition(C) == C;
4409}
4410
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004411CXCursor clang_getCanonicalCursor(CXCursor C) {
4412 if (!clang_isDeclaration(C.kind))
4413 return C;
4414
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004415 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004416 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4417 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4418 return MakeCXCursor(CatD, getCursorTU(C));
4419
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004420 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4421 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4422 return MakeCXCursor(IFD, getCursorTU(C));
4423
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004424 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004425 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004426
4427 return C;
4428}
4429
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004430unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004431 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004432 return 0;
4433
4434 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4435 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4436 return E->getNumDecls();
4437
4438 if (OverloadedTemplateStorage *S
4439 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4440 return S->size();
4441
4442 Decl *D = Storage.get<Decl*>();
4443 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004444 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004445 if (isa<ObjCClassDecl>(D))
4446 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004447 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4448 return Protocols->protocol_size();
4449
4450 return 0;
4451}
4452
4453CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004454 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004455 return clang_getNullCursor();
4456
4457 if (index >= clang_getNumOverloadedDecls(cursor))
4458 return clang_getNullCursor();
4459
Ted Kremeneka60ed472010-11-16 08:15:36 +00004460 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004461 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4462 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004463 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004464
4465 if (OverloadedTemplateStorage *S
4466 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004467 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004468
4469 Decl *D = Storage.get<Decl*>();
4470 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4471 // FIXME: This is, unfortunately, linear time.
4472 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4473 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004474 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004475 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004476 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004477 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004478 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004479 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004480
4481 return clang_getNullCursor();
4482}
4483
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004484void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004485 const char **startBuf,
4486 const char **endBuf,
4487 unsigned *startLine,
4488 unsigned *startColumn,
4489 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004490 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004491 assert(getCursorDecl(C) && "CXCursor has null decl");
4492 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004493 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4494 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004495
Steve Naroff4ade6d62009-09-23 17:52:52 +00004496 SourceManager &SM = FD->getASTContext().getSourceManager();
4497 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4498 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4499 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4500 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4501 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4502 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4503}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004504
Douglas Gregor430d7a12011-07-25 17:48:11 +00004505
4506CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4507 unsigned PieceIndex) {
4508 RefNamePieces Pieces;
4509
4510 switch (C.kind) {
4511 case CXCursor_MemberRefExpr:
4512 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4513 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4514 E->getQualifierLoc().getSourceRange());
4515 break;
4516
4517 case CXCursor_DeclRefExpr:
4518 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4519 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4520 E->getQualifierLoc().getSourceRange(),
4521 E->getExplicitTemplateArgsOpt());
4522 break;
4523
4524 case CXCursor_CallExpr:
4525 if (CXXOperatorCallExpr *OCE =
4526 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4527 Expr *Callee = OCE->getCallee();
4528 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4529 Callee = ICE->getSubExpr();
4530
4531 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4532 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4533 DRE->getQualifierLoc().getSourceRange());
4534 }
4535 break;
4536
4537 default:
4538 break;
4539 }
4540
4541 if (Pieces.empty()) {
4542 if (PieceIndex == 0)
4543 return clang_getCursorExtent(C);
4544 } else if (PieceIndex < Pieces.size()) {
4545 SourceRange R = Pieces[PieceIndex];
4546 if (R.isValid())
4547 return cxloc::translateSourceRange(getCursorContext(C), R);
4548 }
4549
4550 return clang_getNullRange();
4551}
4552
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004553void clang_enableStackTraces(void) {
4554 llvm::sys::PrintStackTraceOnErrorSignal();
4555}
4556
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004557void clang_executeOnThread(void (*fn)(void*), void *user_data,
4558 unsigned stack_size) {
4559 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4560}
4561
Ted Kremenekfb480492010-01-13 21:46:36 +00004562} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004563
Ted Kremenekfb480492010-01-13 21:46:36 +00004564//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004565// Token-based Operations.
4566//===----------------------------------------------------------------------===//
4567
4568/* CXToken layout:
4569 * int_data[0]: a CXTokenKind
4570 * int_data[1]: starting token location
4571 * int_data[2]: token length
4572 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004573 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004574 * otherwise unused.
4575 */
4576extern "C" {
4577
4578CXTokenKind clang_getTokenKind(CXToken CXTok) {
4579 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4580}
4581
4582CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4583 switch (clang_getTokenKind(CXTok)) {
4584 case CXToken_Identifier:
4585 case CXToken_Keyword:
4586 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004587 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4588 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004589
4590 case CXToken_Literal: {
4591 // We have stashed the starting pointer in the ptr_data field. Use it.
4592 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004593 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004594 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004595
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004596 case CXToken_Punctuation:
4597 case CXToken_Comment:
4598 break;
4599 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004600
4601 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004602 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004603 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004604 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004605 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004606
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004607 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4608 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004609 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004610 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004611 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004612 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4613 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004614 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004615
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004616 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004617}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004618
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004619CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004620 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004621 if (!CXXUnit)
4622 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004623
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004624 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4625 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4626}
4627
4628CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004629 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004630 if (!CXXUnit)
4631 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004632
4633 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004634 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4635}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004636
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004637static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4638 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004639 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4640 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004641 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004642 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004643 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004644
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004645 // Cannot tokenize across files.
4646 if (BeginLocInfo.first != EndLocInfo.first)
4647 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004648
4649 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004650 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004651 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004652 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004653 if (Invalid)
4654 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004655
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004656 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4657 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004658 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004659 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004660
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004661 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004662 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004663 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004664 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004665 do {
4666 // Lex the next token
4667 Lex.LexFromRawLexer(Tok);
4668 if (Tok.is(tok::eof))
4669 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004670
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004671 // Initialize the CXToken.
4672 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004673
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004674 // - Common fields
4675 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4676 CXTok.int_data[2] = Tok.getLength();
4677 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004678
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004679 // - Kind-specific fields
4680 if (Tok.isLiteral()) {
4681 CXTok.int_data[0] = CXToken_Literal;
4682 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004683 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004684 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004685 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004686 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004687
David Chisnall096428b2010-10-13 21:44:48 +00004688 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004689 CXTok.int_data[0] = CXToken_Keyword;
4690 }
4691 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004692 CXTok.int_data[0] = Tok.is(tok::identifier)
4693 ? CXToken_Identifier
4694 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004695 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004696 CXTok.ptr_data = II;
4697 } else if (Tok.is(tok::comment)) {
4698 CXTok.int_data[0] = CXToken_Comment;
4699 CXTok.ptr_data = 0;
4700 } else {
4701 CXTok.int_data[0] = CXToken_Punctuation;
4702 CXTok.ptr_data = 0;
4703 }
4704 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004705 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004706 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004707}
4708
4709void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4710 CXToken **Tokens, unsigned *NumTokens) {
4711 if (Tokens)
4712 *Tokens = 0;
4713 if (NumTokens)
4714 *NumTokens = 0;
4715
4716 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4717 if (!CXXUnit || !Tokens || !NumTokens)
4718 return;
4719
4720 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4721
4722 SourceRange R = cxloc::translateCXSourceRange(Range);
4723 if (R.isInvalid())
4724 return;
4725
4726 SmallVector<CXToken, 32> CXTokens;
4727 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004728
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004729 if (CXTokens.empty())
4730 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004731
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004732 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4733 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4734 *NumTokens = CXTokens.size();
4735}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004736
Ted Kremenek6db61092010-05-05 00:55:15 +00004737void clang_disposeTokens(CXTranslationUnit TU,
4738 CXToken *Tokens, unsigned NumTokens) {
4739 free(Tokens);
4740}
4741
4742} // end: extern "C"
4743
4744//===----------------------------------------------------------------------===//
4745// Token annotation APIs.
4746//===----------------------------------------------------------------------===//
4747
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004748typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004749static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4750 CXCursor parent,
4751 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004752namespace {
4753class AnnotateTokensWorker {
4754 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004755 CXToken *Tokens;
4756 CXCursor *Cursors;
4757 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004758 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004759 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004760 CursorVisitor AnnotateVis;
4761 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004762 bool HasContextSensitiveKeywords;
4763
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004764 bool MoreTokens() const { return TokIdx < NumTokens; }
4765 unsigned NextToken() const { return TokIdx; }
4766 void AdvanceToken() { ++TokIdx; }
4767 SourceLocation GetTokenLoc(unsigned tokI) {
4768 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4769 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004770 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004771 return Tokens[tokI].int_data[3] != 0;
4772 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004773 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004774 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4775 }
4776
4777 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004778 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4779 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004780
Ted Kremenek6db61092010-05-05 00:55:15 +00004781public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004782 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004783 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004784 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004785 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004786 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004787 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004788 AnnotateTokensVisitor, this,
4789 /*VisitPreprocessorLast=*/true,
4790 /*VisitIncludedPreprocessingEntries=*/false,
4791 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004792 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4793 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004794
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004795 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004796 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004797 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004798 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004799 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004800 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004801
4802 /// \brief Determine whether the annotator saw any cursors that have
4803 /// context-sensitive keywords.
4804 bool hasContextSensitiveKeywords() const {
4805 return HasContextSensitiveKeywords;
4806 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004807};
4808}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004809
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004810void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4811 // Walk the AST within the region of interest, annotating tokens
4812 // along the way.
4813 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004814
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004815 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4816 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004817 if (Pos != Annotated.end() &&
4818 (clang_isInvalid(Cursors[I].kind) ||
4819 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004820 Cursors[I] = Pos->second;
4821 }
4822
4823 // Finish up annotating any tokens left.
4824 if (!MoreTokens())
4825 return;
4826
4827 const CXCursor &C = clang_getNullCursor();
4828 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4829 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4830 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004831 }
4832}
4833
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004834/// \brief It annotates and advances tokens with a cursor until the comparison
4835//// between the cursor location and the source range is the same as
4836/// \arg compResult.
4837///
4838/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4839/// Pass RangeOverlap to annotate tokens inside a range.
4840void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4841 RangeComparisonResult compResult,
4842 SourceRange range) {
4843 while (MoreTokens()) {
4844 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004845 if (isFunctionMacroToken(I))
4846 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004847
4848 SourceLocation TokLoc = GetTokenLoc(I);
4849 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4850 Cursors[I] = updateC;
4851 AdvanceToken();
4852 continue;
4853 }
4854 break;
4855 }
4856}
4857
4858/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004859void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4860 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004861 RangeComparisonResult compResult,
4862 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004863 assert(MoreTokens());
4864 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004865 "Should be called only for macro arg tokens");
4866
4867 // This works differently than annotateAndAdvanceTokens; because expanded
4868 // macro arguments can have arbitrary translation-unit source order, we do not
4869 // advance the token index one by one until a token fails the range test.
4870 // We only advance once past all of the macro arg tokens if all of them
4871 // pass the range test. If one of them fails we keep the token index pointing
4872 // at the start of the macro arg tokens so that the failing token will be
4873 // annotated by a subsequent annotation try.
4874
4875 bool atLeastOneCompFail = false;
4876
4877 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004878 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4879 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004880 if (TokLoc.isFileID())
4881 continue; // not macro arg token, it's parens or comma.
4882 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4883 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4884 Cursors[I] = updateC;
4885 } else
4886 atLeastOneCompFail = true;
4887 }
4888
4889 if (!atLeastOneCompFail)
4890 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4891}
4892
Ted Kremenek6db61092010-05-05 00:55:15 +00004893enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004894AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004895 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004896 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004897 if (cursorRange.isInvalid())
4898 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004899
4900 if (!HasContextSensitiveKeywords) {
4901 // Objective-C properties can have context-sensitive keywords.
4902 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4903 if (ObjCPropertyDecl *Property
4904 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4905 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4906 }
4907 // Objective-C methods can have context-sensitive keywords.
4908 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4909 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4910 if (ObjCMethodDecl *Method
4911 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4912 if (Method->getObjCDeclQualifier())
4913 HasContextSensitiveKeywords = true;
4914 else {
4915 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4916 PEnd = Method->param_end();
4917 P != PEnd; ++P) {
4918 if ((*P)->getObjCDeclQualifier()) {
4919 HasContextSensitiveKeywords = true;
4920 break;
4921 }
4922 }
4923 }
4924 }
4925 }
4926 // C++ methods can have context-sensitive keywords.
4927 else if (cursor.kind == CXCursor_CXXMethod) {
4928 if (CXXMethodDecl *Method
4929 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4930 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4931 HasContextSensitiveKeywords = true;
4932 }
4933 }
4934 // C++ classes can have context-sensitive keywords.
4935 else if (cursor.kind == CXCursor_StructDecl ||
4936 cursor.kind == CXCursor_ClassDecl ||
4937 cursor.kind == CXCursor_ClassTemplate ||
4938 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4939 if (Decl *D = getCursorDecl(cursor))
4940 if (D->hasAttr<FinalAttr>())
4941 HasContextSensitiveKeywords = true;
4942 }
4943 }
4944
Douglas Gregor4419b672010-10-21 06:10:04 +00004945 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004946 // For macro expansions, just note where the beginning of the macro
4947 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004948 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004949 Annotated[Loc.int_data] = cursor;
4950 return CXChildVisit_Recurse;
4951 }
4952
Douglas Gregor4419b672010-10-21 06:10:04 +00004953 // Items in the preprocessing record are kept separate from items in
4954 // declarations, so we keep a separate token index.
4955 unsigned SavedTokIdx = TokIdx;
4956 TokIdx = PreprocessingTokIdx;
4957
4958 // Skip tokens up until we catch up to the beginning of the preprocessing
4959 // entry.
4960 while (MoreTokens()) {
4961 const unsigned I = NextToken();
4962 SourceLocation TokLoc = GetTokenLoc(I);
4963 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4964 case RangeBefore:
4965 AdvanceToken();
4966 continue;
4967 case RangeAfter:
4968 case RangeOverlap:
4969 break;
4970 }
4971 break;
4972 }
4973
4974 // Look at all of the tokens within this range.
4975 while (MoreTokens()) {
4976 const unsigned I = NextToken();
4977 SourceLocation TokLoc = GetTokenLoc(I);
4978 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4979 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004980 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004981 case RangeAfter:
4982 break;
4983 case RangeOverlap:
4984 Cursors[I] = cursor;
4985 AdvanceToken();
4986 continue;
4987 }
4988 break;
4989 }
4990
4991 // Save the preprocessing token index; restore the non-preprocessing
4992 // token index.
4993 PreprocessingTokIdx = TokIdx;
4994 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004995 return CXChildVisit_Recurse;
4996 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004997
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004998 if (cursorRange.isInvalid())
4999 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00005000
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005001 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5002
Ted Kremeneka333c662010-05-12 05:29:33 +00005003 // Adjust the annotated range based specific declarations.
5004 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5005 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00005006 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00005007
5008 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00005009 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00005010 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5011 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
5012 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
5013 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5014 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00005015 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00005016
5017 if (StartLoc.isValid() && L.isValid() &&
5018 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5019 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00005020 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00005021
Ted Kremenek3f404602010-08-14 01:14:06 +00005022 // If the location of the cursor occurs within a macro instantiation, record
5023 // the spelling location of the cursor in our annotation map. We can then
5024 // paper over the token labelings during a post-processing step to try and
5025 // get cursor mappings for tokens that are the *arguments* of a macro
5026 // instantiation.
5027 if (L.isMacroID()) {
5028 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5029 // Only invalidate the old annotation if it isn't part of a preprocessing
5030 // directive. Here we assume that the default construction of CXCursor
5031 // results in CXCursor.kind being an initialized value (i.e., 0). If
5032 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00005033
Ted Kremenek3f404602010-08-14 01:14:06 +00005034 CXCursor &oldC = Annotated[rawEncoding];
5035 if (!clang_isPreprocessing(oldC.kind))
5036 oldC = cursor;
5037 }
5038
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005039 const enum CXCursorKind K = clang_getCursorKind(parent);
5040 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00005041 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5042 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005043
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005044 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005045
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005046 // Avoid having the cursor of an expression "overwrite" the annotation of the
5047 // variable declaration that it belongs to.
5048 // This can happen for C++ constructor expressions whose range generally
5049 // include the variable declaration, e.g.:
5050 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5051 if (clang_isExpression(cursorK)) {
5052 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005053 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005054 const unsigned I = NextToken();
5055 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5056 E->getLocStart() == D->getLocation() &&
5057 E->getLocStart() == GetTokenLoc(I)) {
5058 Cursors[I] = updateC;
5059 AdvanceToken();
5060 }
5061 }
5062 }
5063
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005064 // Visit children to get their cursor information.
5065 const unsigned BeforeChildren = NextToken();
5066 VisitChildren(cursor);
5067 const unsigned AfterChildren = NextToken();
5068
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005069 // Scan the tokens that are at the end of the cursor, but are not captured
5070 // but the child cursors.
5071 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005072
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005073 // Scan the tokens that are at the beginning of the cursor, but are not
5074 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005075 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5076 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5077 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005078
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005079 Cursors[I] = cursor;
5080 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005081
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005082 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005083}
5084
Ted Kremenek6db61092010-05-05 00:55:15 +00005085static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5086 CXCursor parent,
5087 CXClientData client_data) {
5088 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5089}
5090
Ted Kremenek6628a612011-03-18 22:51:30 +00005091namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005092
5093/// \brief Uses the macro expansions in the preprocessing record to find
5094/// and mark tokens that are macro arguments. This info is used by the
5095/// AnnotateTokensWorker.
5096class MarkMacroArgTokensVisitor {
5097 SourceManager &SM;
5098 CXToken *Tokens;
5099 unsigned NumTokens;
5100 unsigned CurIdx;
5101
5102public:
5103 MarkMacroArgTokensVisitor(SourceManager &SM,
5104 CXToken *tokens, unsigned numTokens)
5105 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5106
5107 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5108 if (cursor.kind != CXCursor_MacroExpansion)
5109 return CXChildVisit_Continue;
5110
5111 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5112 if (macroRange.getBegin() == macroRange.getEnd())
5113 return CXChildVisit_Continue; // it's not a function macro.
5114
5115 for (; CurIdx < NumTokens; ++CurIdx) {
5116 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5117 macroRange.getBegin()))
5118 break;
5119 }
5120
5121 if (CurIdx == NumTokens)
5122 return CXChildVisit_Break;
5123
5124 for (; CurIdx < NumTokens; ++CurIdx) {
5125 SourceLocation tokLoc = getTokenLoc(CurIdx);
5126 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5127 break;
5128
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005129 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005130 }
5131
5132 if (CurIdx == NumTokens)
5133 return CXChildVisit_Break;
5134
5135 return CXChildVisit_Continue;
5136 }
5137
5138private:
5139 SourceLocation getTokenLoc(unsigned tokI) {
5140 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5141 }
5142
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005143 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005144 // The third field is reserved and currently not used. Use it here
5145 // to mark macro arg expanded tokens with their expanded locations.
5146 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5147 }
5148};
5149
5150} // end anonymous namespace
5151
5152static CXChildVisitResult
5153MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5154 CXClientData client_data) {
5155 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5156 parent);
5157}
5158
5159namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005160 struct clang_annotateTokens_Data {
5161 CXTranslationUnit TU;
5162 ASTUnit *CXXUnit;
5163 CXToken *Tokens;
5164 unsigned NumTokens;
5165 CXCursor *Cursors;
5166 };
5167}
5168
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005169static void annotatePreprocessorTokens(CXTranslationUnit TU,
5170 SourceRange RegionOfInterest,
5171 AnnotateTokensData &Annotated) {
5172 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5173
5174 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5175 std::pair<FileID, unsigned> BeginLocInfo
5176 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5177 std::pair<FileID, unsigned> EndLocInfo
5178 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5179
5180 if (BeginLocInfo.first != EndLocInfo.first)
5181 return;
5182
5183 StringRef Buffer;
5184 bool Invalid = false;
5185 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5186 if (Buffer.empty() || Invalid)
5187 return;
5188
5189 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5190 CXXUnit->getASTContext().getLangOptions(),
5191 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5192 Buffer.end());
5193 Lex.SetCommentRetentionState(true);
5194
5195 // Lex tokens in raw mode until we hit the end of the range, to avoid
5196 // entering #includes or expanding macros.
5197 while (true) {
5198 Token Tok;
5199 Lex.LexFromRawLexer(Tok);
5200
5201 reprocess:
5202 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5203 // We have found a preprocessing directive. Gobble it up so that we
5204 // don't see it while preprocessing these tokens later, but keep track
5205 // of all of the token locations inside this preprocessing directive so
5206 // that we can annotate them appropriately.
5207 //
5208 // FIXME: Some simple tests here could identify macro definitions and
5209 // #undefs, to provide specific cursor kinds for those.
5210 SmallVector<SourceLocation, 32> Locations;
5211 do {
5212 Locations.push_back(Tok.getLocation());
5213 Lex.LexFromRawLexer(Tok);
5214 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5215
5216 using namespace cxcursor;
5217 CXCursor Cursor
5218 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5219 Locations.back()),
5220 TU);
5221 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5222 Annotated[Locations[I].getRawEncoding()] = Cursor;
5223 }
5224
5225 if (Tok.isAtStartOfLine())
5226 goto reprocess;
5227
5228 continue;
5229 }
5230
5231 if (Tok.is(tok::eof))
5232 break;
5233 }
5234}
5235
Ted Kremenekab979612010-11-11 08:05:23 +00005236// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005237static void clang_annotateTokensImpl(void *UserData) {
5238 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5239 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5240 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5241 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5242 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5243
5244 // Determine the region of interest, which contains all of the tokens.
5245 SourceRange RegionOfInterest;
5246 RegionOfInterest.setBegin(
5247 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5248 RegionOfInterest.setEnd(
5249 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5250 Tokens[NumTokens-1])));
5251
5252 // A mapping from the source locations found when re-lexing or traversing the
5253 // region of interest to the corresponding cursors.
5254 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005255
Ted Kremenek6628a612011-03-18 22:51:30 +00005256 // Relex the tokens within the source range to look for preprocessing
5257 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005258 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005259
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005260 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5261 // Search and mark tokens that are macro argument expansions.
5262 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5263 Tokens, NumTokens);
5264 CursorVisitor MacroArgMarker(TU,
5265 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005266 /*VisitPreprocessorLast=*/true,
5267 /*VisitIncludedPreprocessingEntries=*/false,
5268 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005269 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5270 }
5271
Ted Kremenek6628a612011-03-18 22:51:30 +00005272 // Annotate all of the source locations in the region of interest that map to
5273 // a specific cursor.
5274 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5275 TU, RegionOfInterest);
5276
5277 // FIXME: We use a ridiculous stack size here because the data-recursion
5278 // algorithm uses a large stack frame than the non-data recursive version,
5279 // and AnnotationTokensWorker currently transforms the data-recursion
5280 // algorithm back into a traditional recursion by explicitly calling
5281 // VisitChildren(). We will need to remove this explicit recursive call.
5282 W.AnnotateTokens();
5283
5284 // If we ran into any entities that involve context-sensitive keywords,
5285 // take another pass through the tokens to mark them as such.
5286 if (W.hasContextSensitiveKeywords()) {
5287 for (unsigned I = 0; I != NumTokens; ++I) {
5288 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5289 continue;
5290
5291 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5292 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5293 if (ObjCPropertyDecl *Property
5294 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5295 if (Property->getPropertyAttributesAsWritten() != 0 &&
5296 llvm::StringSwitch<bool>(II->getName())
5297 .Case("readonly", true)
5298 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005299 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005300 .Case("readwrite", true)
5301 .Case("retain", true)
5302 .Case("copy", true)
5303 .Case("nonatomic", true)
5304 .Case("atomic", true)
5305 .Case("getter", true)
5306 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005307 .Case("strong", true)
5308 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005309 .Default(false))
5310 Tokens[I].int_data[0] = CXToken_Keyword;
5311 }
5312 continue;
5313 }
5314
5315 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5316 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5317 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5318 if (llvm::StringSwitch<bool>(II->getName())
5319 .Case("in", true)
5320 .Case("out", true)
5321 .Case("inout", true)
5322 .Case("oneway", true)
5323 .Case("bycopy", true)
5324 .Case("byref", true)
5325 .Default(false))
5326 Tokens[I].int_data[0] = CXToken_Keyword;
5327 continue;
5328 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005329
5330 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5331 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5332 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005333 continue;
5334 }
5335 }
5336 }
Ted Kremenekab979612010-11-11 08:05:23 +00005337}
5338
Ted Kremenek6db61092010-05-05 00:55:15 +00005339extern "C" {
5340
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005341void clang_annotateTokens(CXTranslationUnit TU,
5342 CXToken *Tokens, unsigned NumTokens,
5343 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005344
5345 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005346 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005347
Douglas Gregor4419b672010-10-21 06:10:04 +00005348 // Any token we don't specifically annotate will have a NULL cursor.
5349 CXCursor C = clang_getNullCursor();
5350 for (unsigned I = 0; I != NumTokens; ++I)
5351 Cursors[I] = C;
5352
Ted Kremeneka60ed472010-11-16 08:15:36 +00005353 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005354 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005355 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005356
Douglas Gregorbdf60622010-03-05 21:16:25 +00005357 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005358
5359 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005360 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005361 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005362 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005363 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5364 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005365}
Ted Kremenek6628a612011-03-18 22:51:30 +00005366
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005367} // end: extern "C"
5368
5369//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005370// Operations for querying linkage of a cursor.
5371//===----------------------------------------------------------------------===//
5372
5373extern "C" {
5374CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005375 if (!clang_isDeclaration(cursor.kind))
5376 return CXLinkage_Invalid;
5377
Ted Kremenek16b42592010-03-03 06:36:57 +00005378 Decl *D = cxcursor::getCursorDecl(cursor);
5379 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5380 switch (ND->getLinkage()) {
5381 case NoLinkage: return CXLinkage_NoLinkage;
5382 case InternalLinkage: return CXLinkage_Internal;
5383 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5384 case ExternalLinkage: return CXLinkage_External;
5385 };
5386
5387 return CXLinkage_Invalid;
5388}
5389} // end: extern "C"
5390
5391//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005392// Operations for querying language of a cursor.
5393//===----------------------------------------------------------------------===//
5394
5395static CXLanguageKind getDeclLanguage(const Decl *D) {
5396 switch (D->getKind()) {
5397 default:
5398 break;
5399 case Decl::ImplicitParam:
5400 case Decl::ObjCAtDefsField:
5401 case Decl::ObjCCategory:
5402 case Decl::ObjCCategoryImpl:
5403 case Decl::ObjCClass:
5404 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005405 case Decl::ObjCForwardProtocol:
5406 case Decl::ObjCImplementation:
5407 case Decl::ObjCInterface:
5408 case Decl::ObjCIvar:
5409 case Decl::ObjCMethod:
5410 case Decl::ObjCProperty:
5411 case Decl::ObjCPropertyImpl:
5412 case Decl::ObjCProtocol:
5413 return CXLanguage_ObjC;
5414 case Decl::CXXConstructor:
5415 case Decl::CXXConversion:
5416 case Decl::CXXDestructor:
5417 case Decl::CXXMethod:
5418 case Decl::CXXRecord:
5419 case Decl::ClassTemplate:
5420 case Decl::ClassTemplatePartialSpecialization:
5421 case Decl::ClassTemplateSpecialization:
5422 case Decl::Friend:
5423 case Decl::FriendTemplate:
5424 case Decl::FunctionTemplate:
5425 case Decl::LinkageSpec:
5426 case Decl::Namespace:
5427 case Decl::NamespaceAlias:
5428 case Decl::NonTypeTemplateParm:
5429 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005430 case Decl::TemplateTemplateParm:
5431 case Decl::TemplateTypeParm:
5432 case Decl::UnresolvedUsingTypename:
5433 case Decl::UnresolvedUsingValue:
5434 case Decl::Using:
5435 case Decl::UsingDirective:
5436 case Decl::UsingShadow:
5437 return CXLanguage_CPlusPlus;
5438 }
5439
5440 return CXLanguage_C;
5441}
5442
5443extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005444
5445enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5446 if (clang_isDeclaration(cursor.kind))
5447 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005448 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005449 return CXAvailability_Available;
5450
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005451 switch (D->getAvailability()) {
5452 case AR_Available:
5453 case AR_NotYetIntroduced:
5454 return CXAvailability_Available;
5455
5456 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005457 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005458
5459 case AR_Unavailable:
5460 return CXAvailability_NotAvailable;
5461 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005462 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005463
Douglas Gregor58ddb602010-08-23 23:00:57 +00005464 return CXAvailability_Available;
5465}
5466
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005467CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5468 if (clang_isDeclaration(cursor.kind))
5469 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5470
5471 return CXLanguage_Invalid;
5472}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005473
5474 /// \brief If the given cursor is the "templated" declaration
5475 /// descibing a class or function template, return the class or
5476 /// function template.
5477static Decl *maybeGetTemplateCursor(Decl *D) {
5478 if (!D)
5479 return 0;
5480
5481 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5482 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5483 return FunTmpl;
5484
5485 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5486 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5487 return ClassTmpl;
5488
5489 return D;
5490}
5491
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005492CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5493 if (clang_isDeclaration(cursor.kind)) {
5494 if (Decl *D = getCursorDecl(cursor)) {
5495 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005496 if (!DC)
5497 return clang_getNullCursor();
5498
5499 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5500 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005501 }
5502 }
5503
5504 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5505 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005506 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005507 }
5508
5509 return clang_getNullCursor();
5510}
5511
5512CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5513 if (clang_isDeclaration(cursor.kind)) {
5514 if (Decl *D = getCursorDecl(cursor)) {
5515 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005516 if (!DC)
5517 return clang_getNullCursor();
5518
5519 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5520 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005521 }
5522 }
5523
5524 // FIXME: Note that we can't easily compute the lexical context of a
5525 // statement or expression, so we return nothing.
5526 return clang_getNullCursor();
5527}
5528
Douglas Gregor9f592342010-10-01 20:25:15 +00005529void clang_getOverriddenCursors(CXCursor cursor,
5530 CXCursor **overridden,
5531 unsigned *num_overridden) {
5532 if (overridden)
5533 *overridden = 0;
5534 if (num_overridden)
5535 *num_overridden = 0;
5536 if (!overridden || !num_overridden)
5537 return;
5538
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005539 SmallVector<CXCursor, 8> Overridden;
5540 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005541
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005542 *num_overridden = Overridden.size();
5543 *overridden = new CXCursor [Overridden.size()];
5544 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005545}
5546
5547void clang_disposeOverriddenCursors(CXCursor *overridden) {
5548 delete [] overridden;
5549}
5550
Douglas Gregorecdcb882010-10-20 22:00:55 +00005551CXFile clang_getIncludedFile(CXCursor cursor) {
5552 if (cursor.kind != CXCursor_InclusionDirective)
5553 return 0;
5554
5555 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5556 return (void *)ID->getFile();
5557}
5558
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005559} // end: extern "C"
5560
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005561
5562//===----------------------------------------------------------------------===//
5563// C++ AST instrospection.
5564//===----------------------------------------------------------------------===//
5565
5566extern "C" {
5567unsigned clang_CXXMethod_isStatic(CXCursor C) {
5568 if (!clang_isDeclaration(C.kind))
5569 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005570
5571 CXXMethodDecl *Method = 0;
5572 Decl *D = cxcursor::getCursorDecl(C);
5573 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5574 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5575 else
5576 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5577 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005578}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005579
Douglas Gregor211924b2011-05-12 15:17:24 +00005580unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5581 if (!clang_isDeclaration(C.kind))
5582 return 0;
5583
5584 CXXMethodDecl *Method = 0;
5585 Decl *D = cxcursor::getCursorDecl(C);
5586 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5587 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5588 else
5589 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5590 return (Method && Method->isVirtual()) ? 1 : 0;
5591}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005592} // end: extern "C"
5593
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005594//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005595// Attribute introspection.
5596//===----------------------------------------------------------------------===//
5597
5598extern "C" {
5599CXType clang_getIBOutletCollectionType(CXCursor C) {
5600 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005601 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005602
5603 IBOutletCollectionAttr *A =
5604 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5605
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005606 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005607}
5608} // end: extern "C"
5609
5610//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005611// Inspecting memory usage.
5612//===----------------------------------------------------------------------===//
5613
Ted Kremenekf7870022011-04-20 16:41:07 +00005614typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005615
Ted Kremenekf7870022011-04-20 16:41:07 +00005616static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5617 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005618 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005619 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005620 entries.push_back(entry);
5621}
5622
5623extern "C" {
5624
Ted Kremenekf7870022011-04-20 16:41:07 +00005625const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005626 const char *str = "";
5627 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005628 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005629 str = "ASTContext: expressions, declarations, and types";
5630 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005631 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005632 str = "ASTContext: identifiers";
5633 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005634 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005635 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005636 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005637 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005638 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005639 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005640 case CXTUResourceUsage_SourceManagerContentCache:
5641 str = "SourceManager: content cache allocator";
5642 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005643 case CXTUResourceUsage_AST_SideTables:
5644 str = "ASTContext: side tables";
5645 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005646 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5647 str = "SourceManager: malloc'ed memory buffers";
5648 break;
5649 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5650 str = "SourceManager: mmap'ed memory buffers";
5651 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005652 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5653 str = "ExternalASTSource: malloc'ed memory buffers";
5654 break;
5655 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5656 str = "ExternalASTSource: mmap'ed memory buffers";
5657 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005658 case CXTUResourceUsage_Preprocessor:
5659 str = "Preprocessor: malloc'ed memory";
5660 break;
5661 case CXTUResourceUsage_PreprocessingRecord:
5662 str = "Preprocessor: PreprocessingRecord";
5663 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005664 case CXTUResourceUsage_SourceManager_DataStructures:
5665 str = "SourceManager: data structures and tables";
5666 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005667 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5668 str = "Preprocessor: header search tables";
5669 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005670 }
5671 return str;
5672}
5673
Ted Kremenekf7870022011-04-20 16:41:07 +00005674CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005675 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005676 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005677 return usage;
5678 }
5679
5680 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5681 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5682 ASTContext &astContext = astUnit->getASTContext();
5683
5684 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005685 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005686 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005687
5688 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005689 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005690 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5691
5692 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005693 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005694 (unsigned long) astContext.Selectors.getTotalMemory());
5695
Ted Kremenekba29bd22011-04-28 04:53:38 +00005696 // How much memory is used by ASTContext's side tables?
5697 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5698 (unsigned long) astContext.getSideTableAllocatedMemory());
5699
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005700 // How much memory is used for caching global code completion results?
5701 unsigned long completionBytes = 0;
5702 if (GlobalCodeCompletionAllocator *completionAllocator =
5703 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005704 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005705 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005706 createCXTUResourceUsageEntry(*entries,
5707 CXTUResourceUsage_GlobalCompletionResults,
5708 completionBytes);
5709
5710 // How much memory is being used by SourceManager's content cache?
5711 createCXTUResourceUsageEntry(*entries,
5712 CXTUResourceUsage_SourceManagerContentCache,
5713 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005714
5715 // How much memory is being used by the MemoryBuffer's in SourceManager?
5716 const SourceManager::MemoryBufferSizes &srcBufs =
5717 astUnit->getSourceManager().getMemoryBufferSizes();
5718
5719 createCXTUResourceUsageEntry(*entries,
5720 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5721 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005722 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005723 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5724 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005725 createCXTUResourceUsageEntry(*entries,
5726 CXTUResourceUsage_SourceManager_DataStructures,
5727 (unsigned long) astContext.getSourceManager()
5728 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005729
5730 // How much memory is being used by the ExternalASTSource?
5731 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5732 const ExternalASTSource::MemoryBufferSizes &sizes =
5733 esrc->getMemoryBufferSizes();
5734
5735 createCXTUResourceUsageEntry(*entries,
5736 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5737 (unsigned long) sizes.malloc_bytes);
5738 createCXTUResourceUsageEntry(*entries,
5739 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5740 (unsigned long) sizes.mmap_bytes);
5741 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005742
5743 // How much memory is being used by the Preprocessor?
5744 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005745 createCXTUResourceUsageEntry(*entries,
5746 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005747 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005748
5749 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5750 createCXTUResourceUsageEntry(*entries,
5751 CXTUResourceUsage_PreprocessingRecord,
5752 pRec->getTotalMemory());
5753 }
5754
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005755 createCXTUResourceUsageEntry(*entries,
5756 CXTUResourceUsage_Preprocessor_HeaderSearch,
5757 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005758
Ted Kremenekf7870022011-04-20 16:41:07 +00005759 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005760 (unsigned) entries->size(),
5761 entries->size() ? &(*entries)[0] : 0 };
5762 entries.take();
5763 return usage;
5764}
5765
Ted Kremenekf7870022011-04-20 16:41:07 +00005766void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005767 if (usage.data)
5768 delete (MemUsageEntries*) usage.data;
5769}
5770
5771} // end extern "C"
5772
Douglas Gregor6df78732011-05-05 20:27:22 +00005773void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5774 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5775 for (unsigned I = 0; I != Usage.numEntries; ++I)
5776 fprintf(stderr, " %s: %lu\n",
5777 clang_getTUResourceUsageName(Usage.entries[I].kind),
5778 Usage.entries[I].amount);
5779
5780 clang_disposeCXTUResourceUsage(Usage);
5781}
5782
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005783//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005784// Misc. utility functions.
5785//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005786
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005787/// Default to using an 8 MB stack size on "safety" threads.
5788static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005789
5790namespace clang {
5791
5792bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005793 void (*Fn)(void*), void *UserData,
5794 unsigned Size) {
5795 if (!Size)
5796 Size = GetSafetyThreadStackSize();
5797 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005798 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5799 return CRC.RunSafely(Fn, UserData);
5800}
5801
5802unsigned GetSafetyThreadStackSize() {
5803 return SafetyStackThreadSize;
5804}
5805
5806void SetSafetyThreadStackSize(unsigned Value) {
5807 SafetyStackThreadSize = Value;
5808}
5809
5810}
5811
Ted Kremenek04bb7162010-01-22 22:44:15 +00005812extern "C" {
5813
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005814CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005815 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005816}
5817
5818} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005819