blob: 8c2111d4ad9f7f5753ac0913e741b58977f13875 [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"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
37#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000038#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000039#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000040#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000042#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000043#include "llvm/Support/Mutex.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000047#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000048
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Ted Kremeneka60ed472010-11-16 08:15:36 +000053static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
54 if (!TU)
55 return 0;
56 CXTranslationUnit D = new CXTranslationUnitImpl();
57 D->TUData = TU;
58 D->StringPool = createCXStringPool();
59 return D;
60}
61
Douglas Gregor33e9abd2010-01-22 19:49:59 +000062/// \brief The result of comparing two source ranges.
63enum RangeComparisonResult {
64 /// \brief Either the ranges overlap or one of the ranges is invalid.
65 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000066
Douglas Gregor33e9abd2010-01-22 19:49:59 +000067 /// \brief The first range ends before the second range starts.
68 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000069
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070 /// \brief The first range starts after the second range ends.
71 RangeAfter
72};
73
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076static RangeComparisonResult RangeCompare(SourceManager &SM,
77 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 SourceRange R2) {
79 assert(R1.isValid() && "First range is invalid?");
80 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000081 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000082 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000085 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 return RangeAfter;
87 return RangeOverlap;
88}
89
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000090/// \brief Determine if a source location falls within, before, or after a
91/// a given source range.
92static RangeComparisonResult LocationCompare(SourceManager &SM,
93 SourceLocation L, SourceRange R) {
94 assert(R.isValid() && "First range is invalid?");
95 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000096 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
99 return RangeBefore;
100 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
101 return RangeAfter;
102 return RangeOverlap;
103}
104
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105/// \brief Translate a Clang source range into a CIndex source range.
106///
107/// Clang internally represents ranges where the end location points to the
108/// start of the token at the end. However, for external clients it is more
109/// useful to have a CXSourceRange be a proper half-open interval. This routine
110/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000111CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000113 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000115 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000117 if (EndLoc.isValid() && EndLoc.isMacroID())
118 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000119 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000120 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000121 EndLoc = EndLoc.getFileLocWithOffset(Length);
122 }
123
124 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
125 R.getBegin().getRawEncoding(),
126 EndLoc.getRawEncoding() };
127 return Result;
128}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000129
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
133
Steve Naroff89922f82009-08-31 00:59:03 +0000134namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135
136class VisitorJob {
137public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000138 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000139 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000140 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000141 ExplicitTemplateArgsVisitKind,
142 NestedNameSpecifierVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000143 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000144 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000145 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000146protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000147 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000148 CXCursor parent;
149 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000150 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
151 : parent(C), K(k) {
152 data[0] = d1;
153 data[1] = d2;
154 data[2] = d3;
155 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000156public:
157 Kind getKind() const { return K; }
158 const CXCursor &getParent() const { return parent; }
159 static bool classof(VisitorJob *VJ) { return true; }
160};
161
162typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
163
Douglas Gregorb1373d02010-01-20 20:59:29 +0000164// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000165class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000166 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000167{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000169 CXTranslationUnit TU;
170 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000171
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The declaration that serves at the parent of any statement or
176 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000177 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000179 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000180 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000181
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000183 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000184
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000185 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
186 // to the visitor. Declarations with a PCH level greater than this value will
187 // be suppressed.
188 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000189
190 /// \brief When valid, a source range to which the cursor should restrict
191 /// its search.
192 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000194 // FIXME: Eventually remove. This part of a hack to support proper
195 // iteration over all Decls contained lexically within an ObjC container.
196 DeclContext::decl_iterator *DI_current;
197 DeclContext::decl_iterator DE_current;
198
Ted Kremenekd1ded662010-11-15 23:31:32 +0000199 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
200 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
201 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
206 /// \brief Determine whether this particular source range comes before, comes
207 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000209 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
211
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000212 class SetParentRAII {
213 CXCursor &Parent;
214 Decl *&StmtParent;
215 CXCursor OldParent;
216
217 public:
218 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
219 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
220 {
221 Parent = NewParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225
226 ~SetParentRAII() {
227 Parent = OldParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231 };
232
Steve Naroff89922f82009-08-31 00:59:03 +0000233public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000234 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
235 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000238 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
239 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000240 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
241 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 {
243 Parent.kind = CXCursor_NoDeclFound;
244 Parent.data[0] = 0;
245 Parent.data[1] = 0;
246 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000249
Ted Kremenekd1ded662010-11-15 23:31:32 +0000250 ~CursorVisitor() {
251 // Free the pre-allocated worklists for data-recursion.
252 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
253 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
254 delete *I;
255 }
256 }
257
Ted Kremeneka60ed472010-11-16 08:15:36 +0000258 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
259 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000260
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000261 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000262
263 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
264 getPreprocessedEntities();
265
Douglas Gregorb1373d02010-01-20 20:59:29 +0000266 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000267
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000268 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000269 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000270 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000271 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000272 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000274 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
275 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000276 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000277 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000278 bool VisitClassTemplatePartialSpecializationDecl(
279 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000280 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000281 bool VisitEnumConstantDecl(EnumConstantDecl *D);
282 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
283 bool VisitFunctionDecl(FunctionDecl *ND);
284 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000285 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000286 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000287 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000288 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000289 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
291 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
292 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
293 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000294 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000295 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
296 bool VisitObjCImplDecl(ObjCImplDecl *D);
297 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
298 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000299 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
300 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
301 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000302 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000303 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000304 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000305 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000306 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000307 bool VisitUsingDecl(UsingDecl *D);
308 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
309 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000310
Douglas Gregor01829d32010-08-31 14:41:23 +0000311 // Name visitor
312 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000313 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000314 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000315
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000316 // Template visitors
317 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000318 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000319 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
320
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000321 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000322 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000324 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000325 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
326 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000327 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000329 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000331 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000332 bool VisitPointerTypeLoc(PointerTypeLoc TL);
333 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
334 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
335 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
336 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000337 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000339 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000340 // FIXME: Implement visitors here when the unimplemented TypeLocs get
341 // implemented
342 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000343 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000344 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000345 bool VisitDependentNameTypeLoc(DependentNameTypeLoc TL);
Douglas Gregor9e876872011-03-01 18:12:44 +0000346 bool VisitElaboratedTypeLoc(ElaboratedTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000347
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000348 // Data-recursive visitor functions.
349 bool IsInRegionOfInterest(CXCursor C);
350 bool RunVisitorWorkList(VisitorWorkList &WL);
351 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000352 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000353};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000354
Ted Kremenekab188932010-01-05 19:32:54 +0000355} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000357static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000358static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
359
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000360
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000362 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000363}
364
Douglas Gregorb1373d02010-01-20 20:59:29 +0000365/// \brief Visit the given cursor and, if requested by the visitor,
366/// its children.
367///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368/// \param Cursor the cursor to visit.
369///
370/// \param CheckRegionOfInterest if true, then the caller already checked that
371/// this cursor is within the region of interest.
372///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373/// \returns true if the visitation should be aborted, false if it
374/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000375bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 if (clang_isInvalid(Cursor.kind))
377 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000378
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379 if (clang_isDeclaration(Cursor.kind)) {
380 Decl *D = getCursorDecl(Cursor);
381 assert(D && "Invalid declaration cursor");
382 if (D->getPCHLevel() > MaxPCHLevel)
383 return false;
384
385 if (D->isImplicit())
386 return false;
387 }
388
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000389 // If we have a range of interest, and this cursor doesn't intersect with it,
390 // we're done.
391 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000392 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000393 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000394 return false;
395 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000396
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397 switch (Visitor(Cursor, Parent, ClientData)) {
398 case CXChildVisit_Break:
399 return true;
400
401 case CXChildVisit_Continue:
402 return false;
403
404 case CXChildVisit_Recurse:
405 return VisitChildren(Cursor);
406 }
407
Douglas Gregorfd643772010-01-25 16:45:46 +0000408 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000409}
410
Douglas Gregor788f5a12010-03-20 00:41:21 +0000411std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
412CursorVisitor::getPreprocessedEntities() {
413 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000414 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000415
416 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000417 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
418
419 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
420 // If we would only look at local declarations but we have a region of
421 // interest, check whether that region of interest is in the main file.
422 // If not, we should traverse all declarations.
423 // FIXME: My kingdom for a proper binary search approach to finding
424 // cursors!
425 std::pair<FileID, unsigned> Location
426 = AU->getSourceManager().getDecomposedInstantiationLoc(
427 RegionOfInterest.getBegin());
428 if (Location.first != AU->getSourceManager().getMainFileID())
429 OnlyLocalDecls = false;
430 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000431
Douglas Gregor89d99802010-11-30 06:16:57 +0000432 PreprocessingRecord::iterator StartEntity, EndEntity;
433 if (OnlyLocalDecls) {
434 StartEntity = AU->pp_entity_begin();
435 EndEntity = AU->pp_entity_end();
436 } else {
437 StartEntity = PPRec.begin();
438 EndEntity = PPRec.end();
439 }
440
Douglas Gregor788f5a12010-03-20 00:41:21 +0000441 // There is no region of interest; we have to walk everything.
442 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000443 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000444
445 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000446 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000447 std::pair<FileID, unsigned> Begin
448 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
449 std::pair<FileID, unsigned> End
450 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
451
452 // The region of interest spans files; we have to walk everything.
453 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000454 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000455
456 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000457 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000458 if (ByFileMap.empty()) {
459 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000460 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000461 std::pair<FileID, unsigned> P
462 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000463
Douglas Gregor788f5a12010-03-20 00:41:21 +0000464 ByFileMap[P.first].push_back(*E);
465 }
466 }
467
468 return std::make_pair(ByFileMap[Begin.first].begin(),
469 ByFileMap[Begin.first].end());
470}
471
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000473///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000474/// \returns true if the visitation should be aborted, false if it
475/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000477 if (clang_isReference(Cursor.kind)) {
478 // By definition, references have no children.
479 return false;
480 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481
482 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000484 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000485
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 if (clang_isDeclaration(Cursor.kind)) {
487 Decl *D = getCursorDecl(Cursor);
488 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000489 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000490 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000491
Douglas Gregora59e3902010-01-21 23:27:09 +0000492 if (clang_isStatement(Cursor.kind))
493 return Visit(getCursorStmt(Cursor));
494 if (clang_isExpression(Cursor.kind))
495 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000496
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000498 CXTranslationUnit tu = getCursorTU(Cursor);
499 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000500 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
501 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000502 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
503 TLEnd = CXXUnit->top_level_end();
504 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000505 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000506 return true;
507 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 } else if (VisitDeclContext(
509 CXXUnit->getASTContext().getTranslationUnitDecl()))
510 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000511
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000513 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000514 // FIXME: Once we have the ability to deserialize a preprocessing record,
515 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000516 PreprocessingRecord::iterator E, EEnd;
517 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000519 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000520 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000521
Douglas Gregor0396f462010-03-19 05:22:59 +0000522 continue;
523 }
524
525 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000526 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000527 return true;
528
529 continue;
530 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000531
532 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000533 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000534 return true;
535
536 continue;
537 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000538 }
539 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000540 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000542
Douglas Gregorb1373d02010-01-20 20:59:29 +0000543 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000544 return false;
545}
546
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000547bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000548 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
549 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000550
Ted Kremenek664cffd2010-07-22 11:30:19 +0000551 if (Stmt *Body = B->getBody())
552 return Visit(MakeCXCursor(Body, StmtParent, TU));
553
554 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000555}
556
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000557llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
558 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000559 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000560 if (Range.isInvalid())
561 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000562
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000563 switch (CompareRegionOfInterest(Range)) {
564 case RangeBefore:
565 // This declaration comes before the region of interest; skip it.
566 return llvm::Optional<bool>();
567
568 case RangeAfter:
569 // This declaration comes after the region of interest; we're done.
570 return false;
571
572 case RangeOverlap:
573 // This declaration overlaps the region of interest; visit it.
574 break;
575 }
576 }
577 return true;
578}
579
580bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
581 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
582
583 // FIXME: Eventually remove. This part of a hack to support proper
584 // iteration over all Decls contained lexically within an ObjC container.
585 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
586 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
587
588 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000589 Decl *D = *I;
590 if (D->getLexicalDeclContext() != DC)
591 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000592 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000593 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
594 if (!V.hasValue())
595 continue;
596 if (!V.getValue())
597 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000598 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000599 return true;
600 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000601 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000602}
603
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000604bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
605 llvm_unreachable("Translation units are visited directly by Visit()");
606 return false;
607}
608
609bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
610 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
611 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000612
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000613 return false;
614}
615
616bool CursorVisitor::VisitTagDecl(TagDecl *D) {
617 return VisitDeclContext(D);
618}
619
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000620bool CursorVisitor::VisitClassTemplateSpecializationDecl(
621 ClassTemplateSpecializationDecl *D) {
622 bool ShouldVisitBody = false;
623 switch (D->getSpecializationKind()) {
624 case TSK_Undeclared:
625 case TSK_ImplicitInstantiation:
626 // Nothing to visit
627 return false;
628
629 case TSK_ExplicitInstantiationDeclaration:
630 case TSK_ExplicitInstantiationDefinition:
631 break;
632
633 case TSK_ExplicitSpecialization:
634 ShouldVisitBody = true;
635 break;
636 }
637
638 // Visit the template arguments used in the specialization.
639 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
640 TypeLoc TL = SpecType->getTypeLoc();
641 if (TemplateSpecializationTypeLoc *TSTLoc
642 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
643 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
644 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
645 return true;
646 }
647 }
648
649 if (ShouldVisitBody && VisitCXXRecordDecl(D))
650 return true;
651
652 return false;
653}
654
Douglas Gregor74dbe642010-08-31 19:31:58 +0000655bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
656 ClassTemplatePartialSpecializationDecl *D) {
657 // FIXME: Visit the "outer" template parameter lists on the TagDecl
658 // before visiting these template parameters.
659 if (VisitTemplateParameters(D->getTemplateParameters()))
660 return true;
661
662 // Visit the partial specialization arguments.
663 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
664 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
665 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
666 return true;
667
668 return VisitCXXRecordDecl(D);
669}
670
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000671bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000672 // Visit the default argument.
673 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
674 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
675 if (Visit(DefArg->getTypeLoc()))
676 return true;
677
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000678 return false;
679}
680
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000681bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
682 if (Expr *Init = D->getInitExpr())
683 return Visit(MakeCXCursor(Init, StmtParent, TU));
684 return false;
685}
686
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000687bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
688 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
689 if (Visit(TSInfo->getTypeLoc()))
690 return true;
691
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000692 // Visit the nested-name-specifier, if present.
693 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
694 if (VisitNestedNameSpecifierLoc(QualifierLoc))
695 return true;
696
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000697 return false;
698}
699
Douglas Gregora67e03f2010-09-09 21:42:20 +0000700/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000701static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
702 CXXCtorInitializer const * const *X
703 = static_cast<CXXCtorInitializer const * const *>(Xp);
704 CXXCtorInitializer const * const *Y
705 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000706
707 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
708 return -1;
709 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
710 return 1;
711 else
712 return 0;
713}
714
Douglas Gregorb1373d02010-01-20 20:59:29 +0000715bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000716 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
717 // Visit the function declaration's syntactic components in the order
718 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000719 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000720 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
721
722 // If we have a function declared directly (without the use of a typedef),
723 // visit just the return type. Otherwise, just visit the function's type
724 // now.
725 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
726 (!FTL && Visit(TL)))
727 return true;
728
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000729 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000730 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
731 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000732 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000733
734 // Visit the declaration name.
735 if (VisitDeclarationNameInfo(ND->getNameInfo()))
736 return true;
737
738 // FIXME: Visit explicitly-specified template arguments!
739
740 // Visit the function parameters, if we have a function type.
741 if (FTL && VisitFunctionTypeLoc(*FTL, true))
742 return true;
743
744 // FIXME: Attributes?
745 }
746
Douglas Gregora67e03f2010-09-09 21:42:20 +0000747 if (ND->isThisDeclarationADefinition()) {
748 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
749 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000750 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000751 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
752 IEnd = Constructor->init_end();
753 I != IEnd; ++I) {
754 if (!(*I)->isWritten())
755 continue;
756
757 WrittenInits.push_back(*I);
758 }
759
760 // Sort the initializers in source order
761 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000762 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000763
764 // Visit the initializers in source order
765 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000766 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000767 if (Init->isAnyMemberInitializer()) {
768 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000769 Init->getMemberLocation(), TU)))
770 return true;
771 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
772 if (Visit(BaseInfo->getTypeLoc()))
773 return true;
774 }
775
776 // Visit the initializer value.
777 if (Expr *Initializer = Init->getInit())
778 if (Visit(MakeCXCursor(Initializer, ND, TU)))
779 return true;
780 }
781 }
782
783 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
784 return true;
785 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregorb1373d02010-01-20 20:59:29 +0000787 return false;
788}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000789
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000790bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
791 if (VisitDeclaratorDecl(D))
792 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000793
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000794 if (Expr *BitWidth = D->getBitWidth())
795 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 return false;
798}
799
800bool CursorVisitor::VisitVarDecl(VarDecl *D) {
801 if (VisitDeclaratorDecl(D))
802 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000803
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000804 if (Expr *Init = D->getInit())
805 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000807 return false;
808}
809
Douglas Gregor84b51d72010-09-01 20:16:53 +0000810bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
811 if (VisitDeclaratorDecl(D))
812 return true;
813
814 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
815 if (Expr *DefArg = D->getDefaultArgument())
816 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
817
818 return false;
819}
820
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000821bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
822 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
823 // before visiting these template parameters.
824 if (VisitTemplateParameters(D->getTemplateParameters()))
825 return true;
826
827 return VisitFunctionDecl(D->getTemplatedDecl());
828}
829
Douglas Gregor39d6f072010-08-31 19:02:00 +0000830bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
831 // FIXME: Visit the "outer" template parameter lists on the TagDecl
832 // before visiting these template parameters.
833 if (VisitTemplateParameters(D->getTemplateParameters()))
834 return true;
835
836 return VisitCXXRecordDecl(D->getTemplatedDecl());
837}
838
Douglas Gregor84b51d72010-09-01 20:16:53 +0000839bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
840 if (VisitTemplateParameters(D->getTemplateParameters()))
841 return true;
842
843 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
844 VisitTemplateArgumentLoc(D->getDefaultArgument()))
845 return true;
846
847 return false;
848}
849
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000850bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000851 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
852 if (Visit(TSInfo->getTypeLoc()))
853 return true;
854
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000855 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856 PEnd = ND->param_end();
857 P != PEnd; ++P) {
858 if (Visit(MakeCXCursor(*P, TU)))
859 return true;
860 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000861
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000862 if (ND->isThisDeclarationADefinition() &&
863 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
864 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000865
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000866 return false;
867}
868
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000869namespace {
870 struct ContainerDeclsSort {
871 SourceManager &SM;
872 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
873 bool operator()(Decl *A, Decl *B) {
874 SourceLocation L_A = A->getLocStart();
875 SourceLocation L_B = B->getLocStart();
876 assert(L_A.isValid() && L_B.isValid());
877 return SM.isBeforeInTranslationUnit(L_A, L_B);
878 }
879 };
880}
881
Douglas Gregora59e3902010-01-21 23:27:09 +0000882bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000883 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
884 // an @implementation can lexically contain Decls that are not properly
885 // nested in the AST. When we identify such cases, we need to retrofit
886 // this nesting here.
887 if (!DI_current)
888 return VisitDeclContext(D);
889
890 // Scan the Decls that immediately come after the container
891 // in the current DeclContext. If any fall within the
892 // container's lexical region, stash them into a vector
893 // for later processing.
894 llvm::SmallVector<Decl *, 24> DeclsInContainer;
895 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000896 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000897 if (EndLoc.isValid()) {
898 DeclContext::decl_iterator next = *DI_current;
899 while (++next != DE_current) {
900 Decl *D_next = *next;
901 if (!D_next)
902 break;
903 SourceLocation L = D_next->getLocStart();
904 if (!L.isValid())
905 break;
906 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
907 *DI_current = next;
908 DeclsInContainer.push_back(D_next);
909 continue;
910 }
911 break;
912 }
913 }
914
915 // The common case.
916 if (DeclsInContainer.empty())
917 return VisitDeclContext(D);
918
919 // Get all the Decls in the DeclContext, and sort them with the
920 // additional ones we've collected. Then visit them.
921 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
922 I!=E; ++I) {
923 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000924 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
925 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000926 continue;
927 DeclsInContainer.push_back(subDecl);
928 }
929
930 // Now sort the Decls so that they appear in lexical order.
931 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
932 ContainerDeclsSort(SM));
933
934 // Now visit the decls.
935 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
936 E = DeclsInContainer.end(); I != E; ++I) {
937 CXCursor Cursor = MakeCXCursor(*I, TU);
938 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
939 if (!V.hasValue())
940 continue;
941 if (!V.getValue())
942 return false;
943 if (Visit(Cursor, true))
944 return true;
945 }
946 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000947}
948
Douglas Gregorb1373d02010-01-20 20:59:29 +0000949bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000950 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
951 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000952 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000953
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000954 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
955 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
956 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000957 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000958 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000959
Douglas Gregora59e3902010-01-21 23:27:09 +0000960 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000961}
962
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000963bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
964 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
965 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
966 E = PID->protocol_end(); I != E; ++I, ++PL)
967 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
968 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000969
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000970 return VisitObjCContainerDecl(PID);
971}
972
Ted Kremenek23173d72010-05-18 21:09:07 +0000973bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000974 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000975 return true;
976
Ted Kremenek23173d72010-05-18 21:09:07 +0000977 // FIXME: This implements a workaround with @property declarations also being
978 // installed in the DeclContext for the @interface. Eventually this code
979 // should be removed.
980 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
981 if (!CDecl || !CDecl->IsClassExtension())
982 return false;
983
984 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
985 if (!ID)
986 return false;
987
988 IdentifierInfo *PropertyId = PD->getIdentifier();
989 ObjCPropertyDecl *prevDecl =
990 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
991
992 if (!prevDecl)
993 return false;
994
995 // Visit synthesized methods since they will be skipped when visiting
996 // the @interface.
997 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000998 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000999 if (Visit(MakeCXCursor(MD, TU)))
1000 return true;
1001
1002 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001003 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001004 if (Visit(MakeCXCursor(MD, TU)))
1005 return true;
1006
1007 return false;
1008}
1009
Douglas Gregorb1373d02010-01-20 20:59:29 +00001010bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001011 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001012 if (D->getSuperClass() &&
1013 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001015 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001016 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001017
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001018 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1019 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1020 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001021 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001022 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001023
Douglas Gregora59e3902010-01-21 23:27:09 +00001024 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001025}
1026
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001027bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1028 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001029}
1030
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001031bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001032 // 'ID' could be null when dealing with invalid code.
1033 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1034 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1035 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001036
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001037 return VisitObjCImplDecl(D);
1038}
1039
1040bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1041#if 0
1042 // Issue callbacks for super class.
1043 // FIXME: No source location information!
1044 if (D->getSuperClass() &&
1045 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001046 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001047 TU)))
1048 return true;
1049#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001050
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001051 return VisitObjCImplDecl(D);
1052}
1053
1054bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1055 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1056 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1057 E = D->protocol_end();
1058 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001059 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001060 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061
1062 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001063}
1064
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001065bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1066 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1067 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1068 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001069
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001070 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001071}
1072
Douglas Gregora4ffd852010-11-17 01:03:52 +00001073bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1074 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1075 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1076
1077 return false;
1078}
1079
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001080bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1081 return VisitDeclContext(D);
1082}
1083
Douglas Gregor69319002010-08-31 23:48:11 +00001084bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001085 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001086 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1087 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001088 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001089
1090 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1091 D->getTargetNameLoc(), TU));
1092}
1093
Douglas Gregor7e242562010-09-01 19:52:22 +00001094bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001095 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001096 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1097 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001098 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001099 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001100
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001101 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1102 return true;
1103
Douglas Gregor7e242562010-09-01 19:52:22 +00001104 return VisitDeclarationNameInfo(D->getNameInfo());
1105}
1106
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001107bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001108 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001109 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1110 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001111 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001112
1113 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1114 D->getIdentLocation(), TU));
1115}
1116
Douglas Gregor7e242562010-09-01 19:52:22 +00001117bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001119 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1120 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001122 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001123
Douglas Gregor7e242562010-09-01 19:52:22 +00001124 return VisitDeclarationNameInfo(D->getNameInfo());
1125}
1126
1127bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1128 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001129 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001130 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1131 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001132 return true;
1133
Douglas Gregor7e242562010-09-01 19:52:22 +00001134 return false;
1135}
1136
Douglas Gregor01829d32010-08-31 14:41:23 +00001137bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1138 switch (Name.getName().getNameKind()) {
1139 case clang::DeclarationName::Identifier:
1140 case clang::DeclarationName::CXXLiteralOperatorName:
1141 case clang::DeclarationName::CXXOperatorName:
1142 case clang::DeclarationName::CXXUsingDirective:
1143 return false;
1144
1145 case clang::DeclarationName::CXXConstructorName:
1146 case clang::DeclarationName::CXXDestructorName:
1147 case clang::DeclarationName::CXXConversionFunctionName:
1148 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1149 return Visit(TSInfo->getTypeLoc());
1150 return false;
1151
1152 case clang::DeclarationName::ObjCZeroArgSelector:
1153 case clang::DeclarationName::ObjCOneArgSelector:
1154 case clang::DeclarationName::ObjCMultiArgSelector:
1155 // FIXME: Per-identifier location info?
1156 return false;
1157 }
1158
1159 return false;
1160}
1161
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001162bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1163 SourceRange Range) {
1164 // FIXME: This whole routine is a hack to work around the lack of proper
1165 // source information in nested-name-specifiers (PR5791). Since we do have
1166 // a beginning source location, we can visit the first component of the
1167 // nested-name-specifier, if it's a single-token component.
1168 if (!NNS)
1169 return false;
1170
1171 // Get the first component in the nested-name-specifier.
1172 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1173 NNS = Prefix;
1174
1175 switch (NNS->getKind()) {
1176 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001177 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1178 TU));
1179
Douglas Gregor14aba762011-02-24 02:36:08 +00001180 case NestedNameSpecifier::NamespaceAlias:
1181 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1182 Range.getBegin(), TU));
1183
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001184 case NestedNameSpecifier::TypeSpec: {
1185 // If the type has a form where we know that the beginning of the source
1186 // range matches up with a reference cursor. Visit the appropriate reference
1187 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001188 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001189 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1190 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1191 if (const TagType *Tag = dyn_cast<TagType>(T))
1192 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1193 if (const TemplateSpecializationType *TST
1194 = dyn_cast<TemplateSpecializationType>(T))
1195 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1196 break;
1197 }
1198
1199 case NestedNameSpecifier::TypeSpecWithTemplate:
1200 case NestedNameSpecifier::Global:
1201 case NestedNameSpecifier::Identifier:
1202 break;
1203 }
1204
1205 return false;
1206}
1207
Douglas Gregordc355712011-02-25 00:36:19 +00001208bool
1209CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1210 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1211 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1212 Qualifiers.push_back(Qualifier);
1213
1214 while (!Qualifiers.empty()) {
1215 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1216 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1217 switch (NNS->getKind()) {
1218 case NestedNameSpecifier::Namespace:
1219 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001220 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001221 TU)))
1222 return true;
1223
1224 break;
1225
1226 case NestedNameSpecifier::NamespaceAlias:
1227 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001228 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001229 TU)))
1230 return true;
1231
1232 break;
1233
1234 case NestedNameSpecifier::TypeSpec:
1235 case NestedNameSpecifier::TypeSpecWithTemplate:
1236 if (Visit(Q.getTypeLoc()))
1237 return true;
1238
1239 break;
1240
1241 case NestedNameSpecifier::Global:
1242 case NestedNameSpecifier::Identifier:
1243 break;
1244 }
1245 }
1246
1247 return false;
1248}
1249
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001250bool CursorVisitor::VisitTemplateParameters(
1251 const TemplateParameterList *Params) {
1252 if (!Params)
1253 return false;
1254
1255 for (TemplateParameterList::const_iterator P = Params->begin(),
1256 PEnd = Params->end();
1257 P != PEnd; ++P) {
1258 if (Visit(MakeCXCursor(*P, TU)))
1259 return true;
1260 }
1261
1262 return false;
1263}
1264
Douglas Gregor0b36e612010-08-31 20:37:03 +00001265bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1266 switch (Name.getKind()) {
1267 case TemplateName::Template:
1268 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1269
1270 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001271 // Visit the overloaded template set.
1272 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1273 return true;
1274
Douglas Gregor0b36e612010-08-31 20:37:03 +00001275 return false;
1276
1277 case TemplateName::DependentTemplate:
1278 // FIXME: Visit nested-name-specifier.
1279 return false;
1280
1281 case TemplateName::QualifiedTemplate:
1282 // FIXME: Visit nested-name-specifier.
1283 return Visit(MakeCursorTemplateRef(
1284 Name.getAsQualifiedTemplateName()->getDecl(),
1285 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001286
1287 case TemplateName::SubstTemplateTemplateParmPack:
1288 return Visit(MakeCursorTemplateRef(
1289 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1290 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001291 }
1292
1293 return false;
1294}
1295
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001296bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1297 switch (TAL.getArgument().getKind()) {
1298 case TemplateArgument::Null:
1299 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001300 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301 return false;
1302
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001303 case TemplateArgument::Type:
1304 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1305 return Visit(TSInfo->getTypeLoc());
1306 return false;
1307
1308 case TemplateArgument::Declaration:
1309 if (Expr *E = TAL.getSourceDeclExpression())
1310 return Visit(MakeCXCursor(E, StmtParent, TU));
1311 return false;
1312
1313 case TemplateArgument::Expression:
1314 if (Expr *E = TAL.getSourceExpression())
1315 return Visit(MakeCXCursor(E, StmtParent, TU));
1316 return false;
1317
1318 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001319 case TemplateArgument::TemplateExpansion:
1320 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001321 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001322 }
1323
1324 return false;
1325}
1326
Ted Kremeneka0536d82010-05-07 01:04:29 +00001327bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1328 return VisitDeclContext(D);
1329}
1330
Douglas Gregor01829d32010-08-31 14:41:23 +00001331bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1332 return Visit(TL.getUnqualifiedLoc());
1333}
1334
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001336 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337
1338 // Some builtin types (such as Objective-C's "id", "sel", and
1339 // "Class") have associated declarations. Create cursors for those.
1340 QualType VisitType;
1341 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001342 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001343 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001344 case BuiltinType::Char_U:
1345 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001346 case BuiltinType::Char16:
1347 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001348 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001349 case BuiltinType::UInt:
1350 case BuiltinType::ULong:
1351 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001352 case BuiltinType::UInt128:
1353 case BuiltinType::Char_S:
1354 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001355 case BuiltinType::WChar_U:
1356 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001357 case BuiltinType::Short:
1358 case BuiltinType::Int:
1359 case BuiltinType::Long:
1360 case BuiltinType::LongLong:
1361 case BuiltinType::Int128:
1362 case BuiltinType::Float:
1363 case BuiltinType::Double:
1364 case BuiltinType::LongDouble:
1365 case BuiltinType::NullPtr:
1366 case BuiltinType::Overload:
1367 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001368 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001369
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001370 case BuiltinType::ObjCId:
1371 VisitType = Context.getObjCIdType();
1372 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001373
1374 case BuiltinType::ObjCClass:
1375 VisitType = Context.getObjCClassType();
1376 break;
1377
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378 case BuiltinType::ObjCSel:
1379 VisitType = Context.getObjCSelType();
1380 break;
1381 }
1382
1383 if (!VisitType.isNull()) {
1384 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386 TU));
1387 }
1388
1389 return false;
1390}
1391
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001392bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1393 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1394}
1395
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001396bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1397 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1398}
1399
1400bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1401 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1402}
1403
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001404bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001405 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001406 // no context information with which we can match up the depth/index in the
1407 // type to the appropriate
1408 return false;
1409}
1410
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001411bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1412 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1413 return true;
1414
John McCallc12c5bb2010-05-15 11:32:37 +00001415 return false;
1416}
1417
1418bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1419 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1420 return true;
1421
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001422 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1423 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1424 TU)))
1425 return true;
1426 }
1427
1428 return false;
1429}
1430
1431bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001432 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001433}
1434
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001435bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1436 return Visit(TL.getInnerLoc());
1437}
1438
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001439bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1440 return Visit(TL.getPointeeLoc());
1441}
1442
1443bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1444 return Visit(TL.getPointeeLoc());
1445}
1446
1447bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1448 return Visit(TL.getPointeeLoc());
1449}
1450
1451bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001452 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001453}
1454
1455bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001456 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001457}
1458
Douglas Gregor01829d32010-08-31 14:41:23 +00001459bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1460 bool SkipResultType) {
1461 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001462 return true;
1463
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001464 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001465 if (Decl *D = TL.getArg(I))
1466 if (Visit(MakeCXCursor(D, TU)))
1467 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001468
1469 return false;
1470}
1471
1472bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1473 if (Visit(TL.getElementLoc()))
1474 return true;
1475
1476 if (Expr *Size = TL.getSizeExpr())
1477 return Visit(MakeCXCursor(Size, StmtParent, TU));
1478
1479 return false;
1480}
1481
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001482bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1483 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001484 // Visit the template name.
1485 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1486 TL.getTemplateNameLoc()))
1487 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001488
1489 // Visit the template arguments.
1490 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1491 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1492 return true;
1493
1494 return false;
1495}
1496
Douglas Gregor2332c112010-01-21 20:48:56 +00001497bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1498 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1499}
1500
1501bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1502 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1503 return Visit(TSInfo->getTypeLoc());
1504
1505 return false;
1506}
1507
Douglas Gregor2494dd02011-03-01 01:34:45 +00001508bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1509 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1510 return true;
1511
1512 return false;
1513}
1514
Douglas Gregor9e876872011-03-01 18:12:44 +00001515bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1516 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1517 return true;
1518
1519 return Visit(TL.getNamedTypeLoc());
1520}
1521
Douglas Gregor7536dd52010-12-20 02:24:11 +00001522bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1523 return Visit(TL.getPatternLoc());
1524}
1525
Ted Kremenek3064ef92010-08-27 21:34:58 +00001526bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001527 // Visit the nested-name-specifier, if present.
1528 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1529 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1530 return true;
1531
Ted Kremenek3064ef92010-08-27 21:34:58 +00001532 if (D->isDefinition()) {
1533 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1534 E = D->bases_end(); I != E; ++I) {
1535 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1536 return true;
1537 }
1538 }
1539
1540 return VisitTagDecl(D);
1541}
1542
Ted Kremenek09dfa372010-02-18 05:46:33 +00001543bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001544 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1545 i != e; ++i)
1546 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001547 return true;
1548
1549 return false;
1550}
1551
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001552//===----------------------------------------------------------------------===//
1553// Data-recursive visitor methods.
1554//===----------------------------------------------------------------------===//
1555
Ted Kremenek28a71942010-11-13 00:36:47 +00001556namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001557#define DEF_JOB(NAME, DATA, KIND)\
1558class NAME : public VisitorJob {\
1559public:\
1560 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1561 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001562 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001563};
1564
1565DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1566DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001567DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001568DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001569DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1570 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001571DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001572#undef DEF_JOB
1573
1574class DeclVisit : public VisitorJob {
1575public:
1576 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1577 VisitorJob(parent, VisitorJob::DeclVisitKind,
1578 d, isFirst ? (void*) 1 : (void*) 0) {}
1579 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001580 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001581 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001582 Decl *get() const { return static_cast<Decl*>(data[0]); }
1583 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001584};
Ted Kremenek035dc412010-11-13 00:36:50 +00001585class TypeLocVisit : public VisitorJob {
1586public:
1587 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1588 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1589 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1590
1591 static bool classof(const VisitorJob *VJ) {
1592 return VJ->getKind() == TypeLocVisitKind;
1593 }
1594
Ted Kremenek82f3c502010-11-15 22:23:26 +00001595 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001596 QualType T = QualType::getFromOpaquePtr(data[0]);
1597 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001598 }
1599};
1600
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001601class LabelRefVisit : public VisitorJob {
1602public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001603 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1604 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001605 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001606
1607 static bool classof(const VisitorJob *VJ) {
1608 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1609 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001610 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001611 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001612 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001613};
1614class NestedNameSpecifierVisit : public VisitorJob {
1615public:
1616 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1617 CXCursor parent)
1618 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001619 NS, R.getBegin().getPtrEncoding(),
1620 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001621 static bool classof(const VisitorJob *VJ) {
1622 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1623 }
1624 NestedNameSpecifier *get() const {
1625 return static_cast<NestedNameSpecifier*>(data[0]);
1626 }
1627 SourceRange getSourceRange() const {
1628 SourceLocation A =
1629 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1630 SourceLocation B =
1631 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1632 return SourceRange(A, B);
1633 }
1634};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001635
1636class NestedNameSpecifierLocVisit : public VisitorJob {
1637public:
1638 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1639 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1640 Qualifier.getNestedNameSpecifier(),
1641 Qualifier.getOpaqueData()) { }
1642
1643 static bool classof(const VisitorJob *VJ) {
1644 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1645 }
1646
1647 NestedNameSpecifierLoc get() const {
1648 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1649 data[1]);
1650 }
1651};
1652
Ted Kremenekf64d8032010-11-18 00:02:32 +00001653class DeclarationNameInfoVisit : public VisitorJob {
1654public:
1655 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1656 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1657 static bool classof(const VisitorJob *VJ) {
1658 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1659 }
1660 DeclarationNameInfo get() const {
1661 Stmt *S = static_cast<Stmt*>(data[0]);
1662 switch (S->getStmtClass()) {
1663 default:
1664 llvm_unreachable("Unhandled Stmt");
1665 case Stmt::CXXDependentScopeMemberExprClass:
1666 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1667 case Stmt::DependentScopeDeclRefExprClass:
1668 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1669 }
1670 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001671};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001672class MemberRefVisit : public VisitorJob {
1673public:
1674 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1675 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001676 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001677 static bool classof(const VisitorJob *VJ) {
1678 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1679 }
1680 FieldDecl *get() const {
1681 return static_cast<FieldDecl*>(data[0]);
1682 }
1683 SourceLocation getLoc() const {
1684 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1685 }
1686};
Ted Kremenek28a71942010-11-13 00:36:47 +00001687class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1688 VisitorWorkList &WL;
1689 CXCursor Parent;
1690public:
1691 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1692 : WL(wl), Parent(parent) {}
1693
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001694 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001695 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001697 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001698 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001699 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001700 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001701 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001702 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001703 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001704 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001705 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001706 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001707 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001708 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001709 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001710 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001711 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001712 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1713 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001714 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001715 void VisitIfStmt(IfStmt *If);
1716 void VisitInitListExpr(InitListExpr *IE);
1717 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001718 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001719 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001720 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1721 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001722 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001723 void VisitStmt(Stmt *S);
1724 void VisitSwitchStmt(SwitchStmt *S);
1725 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001726 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001727 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001728 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001729 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001730 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001731
Ted Kremenek28a71942010-11-13 00:36:47 +00001732private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001733 void AddDeclarationNameInfo(Stmt *S);
1734 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001735 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001736 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001737 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001738 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001739 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001740 void AddTypeLoc(TypeSourceInfo *TI);
1741 void EnqueueChildren(Stmt *S);
1742};
1743} // end anonyous namespace
1744
Ted Kremenekf64d8032010-11-18 00:02:32 +00001745void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1746 // 'S' should always be non-null, since it comes from the
1747 // statement we are visiting.
1748 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1749}
1750void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1751 SourceRange R) {
1752 if (N)
1753 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1754}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001755
1756void
1757EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1758 if (Qualifier)
1759 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1760}
1761
Ted Kremenek28a71942010-11-13 00:36:47 +00001762void EnqueueVisitor::AddStmt(Stmt *S) {
1763 if (S)
1764 WL.push_back(StmtVisit(S, Parent));
1765}
Ted Kremenek035dc412010-11-13 00:36:50 +00001766void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001767 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001768 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001769}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001770void EnqueueVisitor::
1771 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1772 if (A)
1773 WL.push_back(ExplicitTemplateArgsVisit(
1774 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1775}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001776void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1777 if (D)
1778 WL.push_back(MemberRefVisit(D, L, Parent));
1779}
Ted Kremenek28a71942010-11-13 00:36:47 +00001780void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1781 if (TI)
1782 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1783 }
1784void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001785 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001786 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001787 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001788 }
1789 if (size == WL.size())
1790 return;
1791 // Now reverse the entries we just added. This will match the DFS
1792 // ordering performed by the worklist.
1793 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1794 std::reverse(I, E);
1795}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001796void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1797 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1798}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001799void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1800 AddDecl(B->getBlockDecl());
1801}
Ted Kremenek28a71942010-11-13 00:36:47 +00001802void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1803 EnqueueChildren(E);
1804 AddTypeLoc(E->getTypeSourceInfo());
1805}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001806void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1807 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1808 E = S->body_rend(); I != E; ++I) {
1809 AddStmt(*I);
1810 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001811}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001812void EnqueueVisitor::
1813VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1814 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1815 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001816 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1817 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001818 if (!E->isImplicitAccess())
1819 AddStmt(E->getBase());
1820}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001821void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1822 // Enqueue the initializer or constructor arguments.
1823 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1824 AddStmt(E->getConstructorArg(I-1));
1825 // Enqueue the array size, if any.
1826 AddStmt(E->getArraySize());
1827 // Enqueue the allocated type.
1828 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1829 // Enqueue the placement arguments.
1830 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1831 AddStmt(E->getPlacementArg(I-1));
1832}
Ted Kremenek28a71942010-11-13 00:36:47 +00001833void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001834 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1835 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001836 AddStmt(CE->getCallee());
1837 AddStmt(CE->getArg(0));
1838}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001839void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1840 // Visit the name of the type being destroyed.
1841 AddTypeLoc(E->getDestroyedTypeInfo());
1842 // Visit the scope type that looks disturbingly like the nested-name-specifier
1843 // but isn't.
1844 AddTypeLoc(E->getScopeTypeInfo());
1845 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001846 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1847 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001848 // Visit base expression.
1849 AddStmt(E->getBase());
1850}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001851void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1852 AddTypeLoc(E->getTypeSourceInfo());
1853}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001854void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1855 EnqueueChildren(E);
1856 AddTypeLoc(E->getTypeSourceInfo());
1857}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001858void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1859 EnqueueChildren(E);
1860 if (E->isTypeOperand())
1861 AddTypeLoc(E->getTypeOperandSourceInfo());
1862}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001863
1864void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1865 *E) {
1866 EnqueueChildren(E);
1867 AddTypeLoc(E->getTypeSourceInfo());
1868}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001869void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1870 EnqueueChildren(E);
1871 if (E->isTypeOperand())
1872 AddTypeLoc(E->getTypeOperandSourceInfo());
1873}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001874void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001875 if (DR->hasExplicitTemplateArgs()) {
1876 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1877 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001878 WL.push_back(DeclRefExprParts(DR, Parent));
1879}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001880void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1881 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1882 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001883 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001884}
Ted Kremenek035dc412010-11-13 00:36:50 +00001885void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1886 unsigned size = WL.size();
1887 bool isFirst = true;
1888 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1889 D != DEnd; ++D) {
1890 AddDecl(*D, isFirst);
1891 isFirst = false;
1892 }
1893 if (size == WL.size())
1894 return;
1895 // Now reverse the entries we just added. This will match the DFS
1896 // ordering performed by the worklist.
1897 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1898 std::reverse(I, E);
1899}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001900void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1901 AddStmt(E->getInit());
1902 typedef DesignatedInitExpr::Designator Designator;
1903 for (DesignatedInitExpr::reverse_designators_iterator
1904 D = E->designators_rbegin(), DEnd = E->designators_rend();
1905 D != DEnd; ++D) {
1906 if (D->isFieldDesignator()) {
1907 if (FieldDecl *Field = D->getField())
1908 AddMemberRef(Field, D->getFieldLoc());
1909 continue;
1910 }
1911 if (D->isArrayDesignator()) {
1912 AddStmt(E->getArrayIndex(*D));
1913 continue;
1914 }
1915 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1916 AddStmt(E->getArrayRangeEnd(*D));
1917 AddStmt(E->getArrayRangeStart(*D));
1918 }
1919}
Ted Kremenek28a71942010-11-13 00:36:47 +00001920void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1921 EnqueueChildren(E);
1922 AddTypeLoc(E->getTypeInfoAsWritten());
1923}
1924void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1925 AddStmt(FS->getBody());
1926 AddStmt(FS->getInc());
1927 AddStmt(FS->getCond());
1928 AddDecl(FS->getConditionVariable());
1929 AddStmt(FS->getInit());
1930}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001931void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1932 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1933}
Ted Kremenek28a71942010-11-13 00:36:47 +00001934void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1935 AddStmt(If->getElse());
1936 AddStmt(If->getThen());
1937 AddStmt(If->getCond());
1938 AddDecl(If->getConditionVariable());
1939}
1940void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1941 // We care about the syntactic form of the initializer list, only.
1942 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1943 IE = Syntactic;
1944 EnqueueChildren(IE);
1945}
1946void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001947 WL.push_back(MemberExprParts(M, Parent));
1948
1949 // If the base of the member access expression is an implicit 'this', don't
1950 // visit it.
1951 // FIXME: If we ever want to show these implicit accesses, this will be
1952 // unfortunate. However, clang_getCursor() relies on this behavior.
1953 if (CXXThisExpr *This
1954 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1955 if (This->isImplicit())
1956 return;
1957
Ted Kremenek28a71942010-11-13 00:36:47 +00001958 AddStmt(M->getBase());
1959}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001960void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1961 AddTypeLoc(E->getEncodedTypeSourceInfo());
1962}
Ted Kremenek28a71942010-11-13 00:36:47 +00001963void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1964 EnqueueChildren(M);
1965 AddTypeLoc(M->getClassReceiverTypeInfo());
1966}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001967void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1968 // Visit the components of the offsetof expression.
1969 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1970 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1971 const OffsetOfNode &Node = E->getComponent(I-1);
1972 switch (Node.getKind()) {
1973 case OffsetOfNode::Array:
1974 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1975 break;
1976 case OffsetOfNode::Field:
1977 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1978 break;
1979 case OffsetOfNode::Identifier:
1980 case OffsetOfNode::Base:
1981 continue;
1982 }
1983 }
1984 // Visit the type into which we're computing the offset.
1985 AddTypeLoc(E->getTypeSourceInfo());
1986}
Ted Kremenek28a71942010-11-13 00:36:47 +00001987void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001988 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001989 WL.push_back(OverloadExprParts(E, Parent));
1990}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001991void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1992 EnqueueChildren(E);
1993 if (E->isArgumentType())
1994 AddTypeLoc(E->getArgumentTypeInfo());
1995}
Ted Kremenek28a71942010-11-13 00:36:47 +00001996void EnqueueVisitor::VisitStmt(Stmt *S) {
1997 EnqueueChildren(S);
1998}
1999void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2000 AddStmt(S->getBody());
2001 AddStmt(S->getCond());
2002 AddDecl(S->getConditionVariable());
2003}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002004
Ted Kremenek28a71942010-11-13 00:36:47 +00002005void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2006 AddStmt(W->getBody());
2007 AddStmt(W->getCond());
2008 AddDecl(W->getConditionVariable());
2009}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002010void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2011 AddTypeLoc(E->getQueriedTypeSourceInfo());
2012}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002013
2014void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002015 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002016 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002017}
2018
Ted Kremenek28a71942010-11-13 00:36:47 +00002019void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2020 VisitOverloadExpr(U);
2021 if (!U->isImplicitAccess())
2022 AddStmt(U->getBase());
2023}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002024void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2025 AddStmt(E->getSubExpr());
2026 AddTypeLoc(E->getWrittenTypeInfo());
2027}
Douglas Gregor94d96292011-01-19 20:34:17 +00002028void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2029 WL.push_back(SizeOfPackExprParts(E, Parent));
2030}
Ted Kremenek60458782010-11-12 21:34:16 +00002031
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002032void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002033 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002034}
2035
2036bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2037 if (RegionOfInterest.isValid()) {
2038 SourceRange Range = getRawCursorExtent(C);
2039 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2040 return false;
2041 }
2042 return true;
2043}
2044
2045bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2046 while (!WL.empty()) {
2047 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002048 VisitorJob LI = WL.back();
2049 WL.pop_back();
2050
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002051 // Set the Parent field, then back to its old value once we're done.
2052 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2053
2054 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002055 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002056 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002057 if (!D)
2058 continue;
2059
2060 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002061 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002062 return true;
2063
2064 continue;
2065 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002066 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2067 const ExplicitTemplateArgumentList *ArgList =
2068 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2069 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2070 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2071 Arg != ArgEnd; ++Arg) {
2072 if (VisitTemplateArgumentLoc(*Arg))
2073 return true;
2074 }
2075 continue;
2076 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002077 case VisitorJob::TypeLocVisitKind: {
2078 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002079 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002080 return true;
2081 continue;
2082 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002083 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002084 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002085 if (LabelStmt *stmt = LS->getStmt()) {
2086 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2087 TU))) {
2088 return true;
2089 }
2090 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002091 continue;
2092 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002093
Ted Kremenekf64d8032010-11-18 00:02:32 +00002094 case VisitorJob::NestedNameSpecifierVisitKind: {
2095 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2096 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2097 return true;
2098 continue;
2099 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002100
2101 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2102 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2103 if (VisitNestedNameSpecifierLoc(V->get()))
2104 return true;
2105 continue;
2106 }
2107
Ted Kremenekf64d8032010-11-18 00:02:32 +00002108 case VisitorJob::DeclarationNameInfoVisitKind: {
2109 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2110 ->get()))
2111 return true;
2112 continue;
2113 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002114 case VisitorJob::MemberRefVisitKind: {
2115 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2116 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2117 return true;
2118 continue;
2119 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002120 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002121 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002122 if (!S)
2123 continue;
2124
Ted Kremenekf1107452010-11-12 18:26:56 +00002125 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002126 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002127 if (!IsInRegionOfInterest(Cursor))
2128 continue;
2129 switch (Visitor(Cursor, Parent, ClientData)) {
2130 case CXChildVisit_Break: return true;
2131 case CXChildVisit_Continue: break;
2132 case CXChildVisit_Recurse:
2133 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002134 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002135 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002136 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002137 }
2138 case VisitorJob::MemberExprPartsKind: {
2139 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002140 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002141
2142 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002143 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2144 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002145 return true;
2146
2147 // Visit the declaration name.
2148 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2149 return true;
2150
2151 // Visit the explicitly-specified template arguments, if any.
2152 if (M->hasExplicitTemplateArgs()) {
2153 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2154 *ArgEnd = Arg + M->getNumTemplateArgs();
2155 Arg != ArgEnd; ++Arg) {
2156 if (VisitTemplateArgumentLoc(*Arg))
2157 return true;
2158 }
2159 }
2160 continue;
2161 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002162 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002163 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002164 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002165 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2166 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002167 return true;
2168 // Visit declaration name.
2169 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2170 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002171 continue;
2172 }
Ted Kremenek60458782010-11-12 21:34:16 +00002173 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002174 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002175 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002176 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2177 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002178 return true;
2179 // Visit the declaration name.
2180 if (VisitDeclarationNameInfo(O->getNameInfo()))
2181 return true;
2182 // Visit the overloaded declaration reference.
2183 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2184 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002185 continue;
2186 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002187 case VisitorJob::SizeOfPackExprPartsKind: {
2188 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2189 NamedDecl *Pack = E->getPack();
2190 if (isa<TemplateTypeParmDecl>(Pack)) {
2191 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2192 E->getPackLoc(), TU)))
2193 return true;
2194
2195 continue;
2196 }
2197
2198 if (isa<TemplateTemplateParmDecl>(Pack)) {
2199 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2200 E->getPackLoc(), TU)))
2201 return true;
2202
2203 continue;
2204 }
2205
2206 // Non-type template parameter packs and function parameter packs are
2207 // treated like DeclRefExpr cursors.
2208 continue;
2209 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002210 }
2211 }
2212 return false;
2213}
2214
Ted Kremenekcdba6592010-11-18 00:42:18 +00002215bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002216 VisitorWorkList *WL = 0;
2217 if (!WorkListFreeList.empty()) {
2218 WL = WorkListFreeList.back();
2219 WL->clear();
2220 WorkListFreeList.pop_back();
2221 }
2222 else {
2223 WL = new VisitorWorkList();
2224 WorkListCache.push_back(WL);
2225 }
2226 EnqueueWorkList(*WL, S);
2227 bool result = RunVisitorWorkList(*WL);
2228 WorkListFreeList.push_back(WL);
2229 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002230}
2231
2232//===----------------------------------------------------------------------===//
2233// Misc. API hooks.
2234//===----------------------------------------------------------------------===//
2235
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002236static llvm::sys::Mutex EnableMultithreadingMutex;
2237static bool EnabledMultithreading;
2238
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002239extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002240CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2241 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002242 // Disable pretty stack trace functionality, which will otherwise be a very
2243 // poor citizen of the world and set up all sorts of signal handlers.
2244 llvm::DisablePrettyStackTrace = true;
2245
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002246 // We use crash recovery to make some of our APIs more reliable, implicitly
2247 // enable it.
2248 llvm::CrashRecoveryContext::Enable();
2249
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002250 // Enable support for multithreading in LLVM.
2251 {
2252 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2253 if (!EnabledMultithreading) {
2254 llvm::llvm_start_multithreaded();
2255 EnabledMultithreading = true;
2256 }
2257 }
2258
Douglas Gregora030b7c2010-01-22 20:35:53 +00002259 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002260 if (excludeDeclarationsFromPCH)
2261 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002262 if (displayDiagnostics)
2263 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002264 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002265}
2266
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002267void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002268 if (CIdx)
2269 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002270}
2271
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002272CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002273 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002274 if (!CIdx)
2275 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002276
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002277 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002278 FileSystemOptions FileSystemOpts;
2279 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002280
Douglas Gregor28019772010-04-05 23:52:57 +00002281 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002282 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002283 CXXIdx->getOnlyLocalDecls(),
2284 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002285 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002286}
2287
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002288unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002289 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002290 CXTranslationUnit_CacheCompletionResults |
2291 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002292}
2293
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002294CXTranslationUnit
2295clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2296 const char *source_filename,
2297 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002298 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002299 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002300 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002301 return clang_parseTranslationUnit(CIdx, source_filename,
2302 command_line_args, num_command_line_args,
2303 unsaved_files, num_unsaved_files,
2304 CXTranslationUnit_DetailedPreprocessingRecord);
2305}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002306
2307struct ParseTranslationUnitInfo {
2308 CXIndex CIdx;
2309 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002310 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002311 int num_command_line_args;
2312 struct CXUnsavedFile *unsaved_files;
2313 unsigned num_unsaved_files;
2314 unsigned options;
2315 CXTranslationUnit result;
2316};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002317static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002318 ParseTranslationUnitInfo *PTUI =
2319 static_cast<ParseTranslationUnitInfo*>(UserData);
2320 CXIndex CIdx = PTUI->CIdx;
2321 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002322 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002323 int num_command_line_args = PTUI->num_command_line_args;
2324 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2325 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2326 unsigned options = PTUI->options;
2327 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002328
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002329 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002330 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002331
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002332 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2333
Douglas Gregor44c181a2010-07-23 00:33:23 +00002334 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002335 bool CompleteTranslationUnit
2336 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002337 bool CacheCodeCompetionResults
2338 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002339 bool CXXPrecompilePreamble
2340 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2341 bool CXXChainedPCH
2342 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002343
Douglas Gregor5352ac02010-01-28 00:27:43 +00002344 // Configure the diagnostics.
2345 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002346 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002347 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2348 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002349
Douglas Gregor4db64a42010-01-23 00:14:00 +00002350 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2351 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002352 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002353 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002354 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002355 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2356 Buffer));
2357 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002358
Douglas Gregorb10daed2010-10-11 16:52:23 +00002359 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002360
Ted Kremenek139ba862009-10-22 00:03:57 +00002361 // The 'source_filename' argument is optional. If the caller does not
2362 // specify it then it is assumed that the source file is specified
2363 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002364 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002365 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002366
2367 // Since the Clang C library is primarily used by batch tools dealing with
2368 // (often very broken) source code, where spell-checking can have a
2369 // significant negative impact on performance (particularly when
2370 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002371 // Only do this if we haven't found a spell-checking-related argument.
2372 bool FoundSpellCheckingArgument = false;
2373 for (int I = 0; I != num_command_line_args; ++I) {
2374 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2375 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2376 FoundSpellCheckingArgument = true;
2377 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002378 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002379 }
2380 if (!FoundSpellCheckingArgument)
2381 Args.push_back("-fno-spell-checking");
2382
2383 Args.insert(Args.end(), command_line_args,
2384 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002385
Douglas Gregor44c181a2010-07-23 00:33:23 +00002386 // Do we need the detailed preprocessing record?
2387 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002388 Args.push_back("-Xclang");
2389 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002390 }
2391
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002392 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002393 llvm::OwningPtr<ASTUnit> Unit(
2394 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2395 Diags,
2396 CXXIdx->getClangResourcesPath(),
2397 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002398 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002399 RemappedFiles.data(),
2400 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002401 PrecompilePreamble,
2402 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002403 CacheCodeCompetionResults,
2404 CXXPrecompilePreamble,
2405 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002406
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002407 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002408 // Make sure to check that 'Unit' is non-NULL.
2409 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2410 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2411 DEnd = Unit->stored_diag_end();
2412 D != DEnd; ++D) {
2413 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2414 CXString Msg = clang_formatDiagnostic(&Diag,
2415 clang_defaultDiagnosticDisplayOptions());
2416 fprintf(stderr, "%s\n", clang_getCString(Msg));
2417 clang_disposeString(Msg);
2418 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002419#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002420 // On Windows, force a flush, since there may be multiple copies of
2421 // stderr and stdout in the file system, all with different buffers
2422 // but writing to the same device.
2423 fflush(stderr);
2424#endif
2425 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002426 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002427
Ted Kremeneka60ed472010-11-16 08:15:36 +00002428 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002429}
2430CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2431 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002432 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002433 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002434 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002435 unsigned num_unsaved_files,
2436 unsigned options) {
2437 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002438 num_command_line_args, unsaved_files,
2439 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002440 llvm::CrashRecoveryContext CRC;
2441
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002442 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002443 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2444 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2445 fprintf(stderr, " 'command_line_args' : [");
2446 for (int i = 0; i != num_command_line_args; ++i) {
2447 if (i)
2448 fprintf(stderr, ", ");
2449 fprintf(stderr, "'%s'", command_line_args[i]);
2450 }
2451 fprintf(stderr, "],\n");
2452 fprintf(stderr, " 'unsaved_files' : [");
2453 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2454 if (i)
2455 fprintf(stderr, ", ");
2456 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2457 unsaved_files[i].Length);
2458 }
2459 fprintf(stderr, "],\n");
2460 fprintf(stderr, " 'options' : %d,\n", options);
2461 fprintf(stderr, "}\n");
2462
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002463 return 0;
2464 }
2465
2466 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002467}
2468
Douglas Gregor19998442010-08-13 15:35:05 +00002469unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2470 return CXSaveTranslationUnit_None;
2471}
2472
2473int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2474 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002475 if (!TU)
2476 return 1;
2477
Ted Kremeneka60ed472010-11-16 08:15:36 +00002478 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002479}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002480
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002481void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002482 if (CTUnit) {
2483 // If the translation unit has been marked as unsafe to free, just discard
2484 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002485 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002486 return;
2487
Ted Kremeneka60ed472010-11-16 08:15:36 +00002488 delete static_cast<ASTUnit *>(CTUnit->TUData);
2489 disposeCXStringPool(CTUnit->StringPool);
2490 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002491 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002492}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002493
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002494unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2495 return CXReparse_None;
2496}
2497
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002498struct ReparseTranslationUnitInfo {
2499 CXTranslationUnit TU;
2500 unsigned num_unsaved_files;
2501 struct CXUnsavedFile *unsaved_files;
2502 unsigned options;
2503 int result;
2504};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002505
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002506static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002507 ReparseTranslationUnitInfo *RTUI =
2508 static_cast<ReparseTranslationUnitInfo*>(UserData);
2509 CXTranslationUnit TU = RTUI->TU;
2510 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2511 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2512 unsigned options = RTUI->options;
2513 (void) options;
2514 RTUI->result = 1;
2515
Douglas Gregorabc563f2010-07-19 21:46:24 +00002516 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002517 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002518
Ted Kremeneka60ed472010-11-16 08:15:36 +00002519 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002520 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002521
2522 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2523 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2524 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2525 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002526 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002527 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2528 Buffer));
2529 }
2530
Douglas Gregor593b0c12010-09-23 18:47:53 +00002531 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2532 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002533}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002534
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002535int clang_reparseTranslationUnit(CXTranslationUnit TU,
2536 unsigned num_unsaved_files,
2537 struct CXUnsavedFile *unsaved_files,
2538 unsigned options) {
2539 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2540 options, 0 };
2541 llvm::CrashRecoveryContext CRC;
2542
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002543 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002544 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002545 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002546 return 1;
2547 }
2548
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002549
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002550 return RTUI.result;
2551}
2552
Douglas Gregordf95a132010-08-09 20:45:32 +00002553
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002554CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002555 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002556 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002557
Ted Kremeneka60ed472010-11-16 08:15:36 +00002558 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002559 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002560}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002561
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002562CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002563 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002564 return Result;
2565}
2566
Ted Kremenekfb480492010-01-13 21:46:36 +00002567} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002568
Ted Kremenekfb480492010-01-13 21:46:36 +00002569//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002570// CXSourceLocation and CXSourceRange Operations.
2571//===----------------------------------------------------------------------===//
2572
Douglas Gregorb9790342010-01-22 21:44:22 +00002573extern "C" {
2574CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002575 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002576 return Result;
2577}
2578
2579unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002580 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2581 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2582 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002583}
2584
2585CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2586 CXFile file,
2587 unsigned line,
2588 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002589 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002590 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002591
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002592 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002593 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002594 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002595 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002596 = CXXUnit->getSourceManager().getLocation(File, line, column);
2597 if (SLoc.isInvalid()) {
2598 if (Logging)
2599 llvm::errs() << "clang_getLocation(\"" << File->getName()
2600 << "\", " << line << ", " << column << ") = invalid\n";
2601 return clang_getNullLocation();
2602 }
2603
2604 if (Logging)
2605 llvm::errs() << "clang_getLocation(\"" << File->getName()
2606 << "\", " << line << ", " << column << ") = "
2607 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002608
2609 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2610}
2611
2612CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2613 CXFile file,
2614 unsigned offset) {
2615 if (!tu || !file)
2616 return clang_getNullLocation();
2617
Ted Kremeneka60ed472010-11-16 08:15:36 +00002618 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002619 SourceLocation Start
2620 = CXXUnit->getSourceManager().getLocation(
2621 static_cast<const FileEntry *>(file),
2622 1, 1);
2623 if (Start.isInvalid()) return clang_getNullLocation();
2624
2625 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2626
2627 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002628
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002629 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002630}
2631
Douglas Gregor5352ac02010-01-28 00:27:43 +00002632CXSourceRange clang_getNullRange() {
2633 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2634 return Result;
2635}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002636
Douglas Gregor5352ac02010-01-28 00:27:43 +00002637CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2638 if (begin.ptr_data[0] != end.ptr_data[0] ||
2639 begin.ptr_data[1] != end.ptr_data[1])
2640 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002641
2642 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002643 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002644 return Result;
2645}
2646
Douglas Gregor46766dc2010-01-26 19:19:08 +00002647void clang_getInstantiationLocation(CXSourceLocation location,
2648 CXFile *file,
2649 unsigned *line,
2650 unsigned *column,
2651 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002652 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2653
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002654 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002655 if (file)
2656 *file = 0;
2657 if (line)
2658 *line = 0;
2659 if (column)
2660 *column = 0;
2661 if (offset)
2662 *offset = 0;
2663 return;
2664 }
2665
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002666 const SourceManager &SM =
2667 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002668 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002669
2670 if (file)
2671 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2672 if (line)
2673 *line = SM.getInstantiationLineNumber(InstLoc);
2674 if (column)
2675 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002676 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002677 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002678}
2679
Douglas Gregora9b06d42010-11-09 06:24:54 +00002680void clang_getSpellingLocation(CXSourceLocation location,
2681 CXFile *file,
2682 unsigned *line,
2683 unsigned *column,
2684 unsigned *offset) {
2685 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2686
2687 if (!location.ptr_data[0] || Loc.isInvalid()) {
2688 if (file)
2689 *file = 0;
2690 if (line)
2691 *line = 0;
2692 if (column)
2693 *column = 0;
2694 if (offset)
2695 *offset = 0;
2696 return;
2697 }
2698
2699 const SourceManager &SM =
2700 *static_cast<const SourceManager*>(location.ptr_data[0]);
2701 SourceLocation SpellLoc = Loc;
2702 if (SpellLoc.isMacroID()) {
2703 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2704 if (SimpleSpellingLoc.isFileID() &&
2705 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2706 SpellLoc = SimpleSpellingLoc;
2707 else
2708 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2709 }
2710
2711 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2712 FileID FID = LocInfo.first;
2713 unsigned FileOffset = LocInfo.second;
2714
2715 if (file)
2716 *file = (void *)SM.getFileEntryForID(FID);
2717 if (line)
2718 *line = SM.getLineNumber(FID, FileOffset);
2719 if (column)
2720 *column = SM.getColumnNumber(FID, FileOffset);
2721 if (offset)
2722 *offset = FileOffset;
2723}
2724
Douglas Gregor1db19de2010-01-19 21:36:55 +00002725CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002726 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002727 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002728 return Result;
2729}
2730
2731CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002732 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002733 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002734 return Result;
2735}
2736
Douglas Gregorb9790342010-01-22 21:44:22 +00002737} // end: extern "C"
2738
Douglas Gregor1db19de2010-01-19 21:36:55 +00002739//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002740// CXFile Operations.
2741//===----------------------------------------------------------------------===//
2742
2743extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002744CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002745 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002746 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002747
Steve Naroff88145032009-10-27 14:35:18 +00002748 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002749 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002750}
2751
2752time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002753 if (!SFile)
2754 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002755
Steve Naroff88145032009-10-27 14:35:18 +00002756 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2757 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002758}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002759
Douglas Gregorb9790342010-01-22 21:44:22 +00002760CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2761 if (!tu)
2762 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002763
Ted Kremeneka60ed472010-11-16 08:15:36 +00002764 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002765
Douglas Gregorb9790342010-01-22 21:44:22 +00002766 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002767 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002768}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002769
Ted Kremenekfb480492010-01-13 21:46:36 +00002770} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002771
Ted Kremenekfb480492010-01-13 21:46:36 +00002772//===----------------------------------------------------------------------===//
2773// CXCursor Operations.
2774//===----------------------------------------------------------------------===//
2775
Ted Kremenekfb480492010-01-13 21:46:36 +00002776static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002777 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2778 return getDeclFromExpr(CE->getSubExpr());
2779
Ted Kremenekfb480492010-01-13 21:46:36 +00002780 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2781 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002782 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2783 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002784 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2785 return ME->getMemberDecl();
2786 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2787 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002788 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002789 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002790
Ted Kremenekfb480492010-01-13 21:46:36 +00002791 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2792 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002793 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2794 if (!CE->isElidable())
2795 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002796 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2797 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002798
Douglas Gregordb1314e2010-10-01 21:11:22 +00002799 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2800 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002801 if (SubstNonTypeTemplateParmPackExpr *NTTP
2802 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2803 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002804 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2805 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2806 isa<ParmVarDecl>(SizeOfPack->getPack()))
2807 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002808
Ted Kremenekfb480492010-01-13 21:46:36 +00002809 return 0;
2810}
2811
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002812static SourceLocation getLocationFromExpr(Expr *E) {
2813 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2814 return /*FIXME:*/Msg->getLeftLoc();
2815 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2816 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002817 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2818 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002819 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2820 return Member->getMemberLoc();
2821 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2822 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002823 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2824 return SizeOfPack->getPackLoc();
2825
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002826 return E->getLocStart();
2827}
2828
Ted Kremenekfb480492010-01-13 21:46:36 +00002829extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002830
2831unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002832 CXCursorVisitor visitor,
2833 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002834 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2835 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002836 return CursorVis.VisitChildren(parent);
2837}
2838
David Chisnall3387c652010-11-03 14:12:26 +00002839#ifndef __has_feature
2840#define __has_feature(x) 0
2841#endif
2842#if __has_feature(blocks)
2843typedef enum CXChildVisitResult
2844 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2845
2846static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2847 CXClientData client_data) {
2848 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2849 return block(cursor, parent);
2850}
2851#else
2852// If we are compiled with a compiler that doesn't have native blocks support,
2853// define and call the block manually, so the
2854typedef struct _CXChildVisitResult
2855{
2856 void *isa;
2857 int flags;
2858 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002859 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2860 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002861} *CXCursorVisitorBlock;
2862
2863static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2864 CXClientData client_data) {
2865 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2866 return block->invoke(block, cursor, parent);
2867}
2868#endif
2869
2870
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002871unsigned clang_visitChildrenWithBlock(CXCursor parent,
2872 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002873 return clang_visitChildren(parent, visitWithBlock, block);
2874}
2875
Douglas Gregor78205d42010-01-20 21:45:58 +00002876static CXString getDeclSpelling(Decl *D) {
2877 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002878 if (!ND) {
2879 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2880 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2881 return createCXString(Property->getIdentifier()->getName());
2882
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002883 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002884 }
2885
Douglas Gregor78205d42010-01-20 21:45:58 +00002886 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002887 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888
Douglas Gregor78205d42010-01-20 21:45:58 +00002889 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2890 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2891 // and returns different names. NamedDecl returns the class name and
2892 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002893 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002894
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002895 if (isa<UsingDirectiveDecl>(D))
2896 return createCXString("");
2897
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002898 llvm::SmallString<1024> S;
2899 llvm::raw_svector_ostream os(S);
2900 ND->printName(os);
2901
2902 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002903}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002904
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002905CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002906 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002907 return clang_getTranslationUnitSpelling(
2908 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002909
Steve Narofff334b4e2009-09-02 18:26:48 +00002910 if (clang_isReference(C.kind)) {
2911 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002912 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002913 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002914 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002915 }
2916 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002917 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002918 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002919 }
2920 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002921 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002922 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002923 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002924 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002925 case CXCursor_CXXBaseSpecifier: {
2926 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2927 return createCXString(B->getType().getAsString());
2928 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002929 case CXCursor_TypeRef: {
2930 TypeDecl *Type = getCursorTypeRef(C).first;
2931 assert(Type && "Missing type decl");
2932
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002933 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2934 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002935 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002936 case CXCursor_TemplateRef: {
2937 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002938 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002939
2940 return createCXString(Template->getNameAsString());
2941 }
Douglas Gregor69319002010-08-31 23:48:11 +00002942
2943 case CXCursor_NamespaceRef: {
2944 NamedDecl *NS = getCursorNamespaceRef(C).first;
2945 assert(NS && "Missing namespace decl");
2946
2947 return createCXString(NS->getNameAsString());
2948 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002949
Douglas Gregora67e03f2010-09-09 21:42:20 +00002950 case CXCursor_MemberRef: {
2951 FieldDecl *Field = getCursorMemberRef(C).first;
2952 assert(Field && "Missing member decl");
2953
2954 return createCXString(Field->getNameAsString());
2955 }
2956
Douglas Gregor36897b02010-09-10 00:22:18 +00002957 case CXCursor_LabelRef: {
2958 LabelStmt *Label = getCursorLabelRef(C).first;
2959 assert(Label && "Missing label");
2960
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002961 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002962 }
2963
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002964 case CXCursor_OverloadedDeclRef: {
2965 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2966 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2967 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2968 return createCXString(ND->getNameAsString());
2969 return createCXString("");
2970 }
2971 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2972 return createCXString(E->getName().getAsString());
2973 OverloadedTemplateStorage *Ovl
2974 = Storage.get<OverloadedTemplateStorage*>();
2975 if (Ovl->size() == 0)
2976 return createCXString("");
2977 return createCXString((*Ovl->begin())->getNameAsString());
2978 }
2979
Daniel Dunbaracca7252009-11-30 20:42:49 +00002980 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002981 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002982 }
2983 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002984
2985 if (clang_isExpression(C.kind)) {
2986 Decl *D = getDeclFromExpr(getCursorExpr(C));
2987 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002988 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002989 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002990 }
2991
Douglas Gregor36897b02010-09-10 00:22:18 +00002992 if (clang_isStatement(C.kind)) {
2993 Stmt *S = getCursorStmt(C);
2994 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002995 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002996
2997 return createCXString("");
2998 }
2999
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003000 if (C.kind == CXCursor_MacroInstantiation)
3001 return createCXString(getCursorMacroInstantiation(C)->getName()
3002 ->getNameStart());
3003
Douglas Gregor572feb22010-03-18 18:04:21 +00003004 if (C.kind == CXCursor_MacroDefinition)
3005 return createCXString(getCursorMacroDefinition(C)->getName()
3006 ->getNameStart());
3007
Douglas Gregorecdcb882010-10-20 22:00:55 +00003008 if (C.kind == CXCursor_InclusionDirective)
3009 return createCXString(getCursorInclusionDirective(C)->getFileName());
3010
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003011 if (clang_isDeclaration(C.kind))
3012 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003013
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003014 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003015}
3016
Douglas Gregor358559d2010-10-02 22:49:11 +00003017CXString clang_getCursorDisplayName(CXCursor C) {
3018 if (!clang_isDeclaration(C.kind))
3019 return clang_getCursorSpelling(C);
3020
3021 Decl *D = getCursorDecl(C);
3022 if (!D)
3023 return createCXString("");
3024
3025 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3026 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3027 D = FunTmpl->getTemplatedDecl();
3028
3029 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3030 llvm::SmallString<64> Str;
3031 llvm::raw_svector_ostream OS(Str);
3032 OS << Function->getNameAsString();
3033 if (Function->getPrimaryTemplate())
3034 OS << "<>";
3035 OS << "(";
3036 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3037 if (I)
3038 OS << ", ";
3039 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3040 }
3041
3042 if (Function->isVariadic()) {
3043 if (Function->getNumParams())
3044 OS << ", ";
3045 OS << "...";
3046 }
3047 OS << ")";
3048 return createCXString(OS.str());
3049 }
3050
3051 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3052 llvm::SmallString<64> Str;
3053 llvm::raw_svector_ostream OS(Str);
3054 OS << ClassTemplate->getNameAsString();
3055 OS << "<";
3056 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3057 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3058 if (I)
3059 OS << ", ";
3060
3061 NamedDecl *Param = Params->getParam(I);
3062 if (Param->getIdentifier()) {
3063 OS << Param->getIdentifier()->getName();
3064 continue;
3065 }
3066
3067 // There is no parameter name, which makes this tricky. Try to come up
3068 // with something useful that isn't too long.
3069 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3070 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3071 else if (NonTypeTemplateParmDecl *NTTP
3072 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3073 OS << NTTP->getType().getAsString(Policy);
3074 else
3075 OS << "template<...> class";
3076 }
3077
3078 OS << ">";
3079 return createCXString(OS.str());
3080 }
3081
3082 if (ClassTemplateSpecializationDecl *ClassSpec
3083 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3084 // If the type was explicitly written, use that.
3085 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3086 return createCXString(TSInfo->getType().getAsString(Policy));
3087
3088 llvm::SmallString<64> Str;
3089 llvm::raw_svector_ostream OS(Str);
3090 OS << ClassSpec->getNameAsString();
3091 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003092 ClassSpec->getTemplateArgs().data(),
3093 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003094 Policy);
3095 return createCXString(OS.str());
3096 }
3097
3098 return clang_getCursorSpelling(C);
3099}
3100
Ted Kremeneke68fff62010-02-17 00:41:32 +00003101CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003102 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003103 case CXCursor_FunctionDecl:
3104 return createCXString("FunctionDecl");
3105 case CXCursor_TypedefDecl:
3106 return createCXString("TypedefDecl");
3107 case CXCursor_EnumDecl:
3108 return createCXString("EnumDecl");
3109 case CXCursor_EnumConstantDecl:
3110 return createCXString("EnumConstantDecl");
3111 case CXCursor_StructDecl:
3112 return createCXString("StructDecl");
3113 case CXCursor_UnionDecl:
3114 return createCXString("UnionDecl");
3115 case CXCursor_ClassDecl:
3116 return createCXString("ClassDecl");
3117 case CXCursor_FieldDecl:
3118 return createCXString("FieldDecl");
3119 case CXCursor_VarDecl:
3120 return createCXString("VarDecl");
3121 case CXCursor_ParmDecl:
3122 return createCXString("ParmDecl");
3123 case CXCursor_ObjCInterfaceDecl:
3124 return createCXString("ObjCInterfaceDecl");
3125 case CXCursor_ObjCCategoryDecl:
3126 return createCXString("ObjCCategoryDecl");
3127 case CXCursor_ObjCProtocolDecl:
3128 return createCXString("ObjCProtocolDecl");
3129 case CXCursor_ObjCPropertyDecl:
3130 return createCXString("ObjCPropertyDecl");
3131 case CXCursor_ObjCIvarDecl:
3132 return createCXString("ObjCIvarDecl");
3133 case CXCursor_ObjCInstanceMethodDecl:
3134 return createCXString("ObjCInstanceMethodDecl");
3135 case CXCursor_ObjCClassMethodDecl:
3136 return createCXString("ObjCClassMethodDecl");
3137 case CXCursor_ObjCImplementationDecl:
3138 return createCXString("ObjCImplementationDecl");
3139 case CXCursor_ObjCCategoryImplDecl:
3140 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003141 case CXCursor_CXXMethod:
3142 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003143 case CXCursor_UnexposedDecl:
3144 return createCXString("UnexposedDecl");
3145 case CXCursor_ObjCSuperClassRef:
3146 return createCXString("ObjCSuperClassRef");
3147 case CXCursor_ObjCProtocolRef:
3148 return createCXString("ObjCProtocolRef");
3149 case CXCursor_ObjCClassRef:
3150 return createCXString("ObjCClassRef");
3151 case CXCursor_TypeRef:
3152 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003153 case CXCursor_TemplateRef:
3154 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003155 case CXCursor_NamespaceRef:
3156 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003157 case CXCursor_MemberRef:
3158 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003159 case CXCursor_LabelRef:
3160 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003161 case CXCursor_OverloadedDeclRef:
3162 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003163 case CXCursor_UnexposedExpr:
3164 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003165 case CXCursor_BlockExpr:
3166 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003167 case CXCursor_DeclRefExpr:
3168 return createCXString("DeclRefExpr");
3169 case CXCursor_MemberRefExpr:
3170 return createCXString("MemberRefExpr");
3171 case CXCursor_CallExpr:
3172 return createCXString("CallExpr");
3173 case CXCursor_ObjCMessageExpr:
3174 return createCXString("ObjCMessageExpr");
3175 case CXCursor_UnexposedStmt:
3176 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003177 case CXCursor_LabelStmt:
3178 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003179 case CXCursor_InvalidFile:
3180 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003181 case CXCursor_InvalidCode:
3182 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003183 case CXCursor_NoDeclFound:
3184 return createCXString("NoDeclFound");
3185 case CXCursor_NotImplemented:
3186 return createCXString("NotImplemented");
3187 case CXCursor_TranslationUnit:
3188 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003189 case CXCursor_UnexposedAttr:
3190 return createCXString("UnexposedAttr");
3191 case CXCursor_IBActionAttr:
3192 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003193 case CXCursor_IBOutletAttr:
3194 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003195 case CXCursor_IBOutletCollectionAttr:
3196 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003197 case CXCursor_PreprocessingDirective:
3198 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003199 case CXCursor_MacroDefinition:
3200 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003201 case CXCursor_MacroInstantiation:
3202 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003203 case CXCursor_InclusionDirective:
3204 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003205 case CXCursor_Namespace:
3206 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003207 case CXCursor_LinkageSpec:
3208 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003209 case CXCursor_CXXBaseSpecifier:
3210 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003211 case CXCursor_Constructor:
3212 return createCXString("CXXConstructor");
3213 case CXCursor_Destructor:
3214 return createCXString("CXXDestructor");
3215 case CXCursor_ConversionFunction:
3216 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003217 case CXCursor_TemplateTypeParameter:
3218 return createCXString("TemplateTypeParameter");
3219 case CXCursor_NonTypeTemplateParameter:
3220 return createCXString("NonTypeTemplateParameter");
3221 case CXCursor_TemplateTemplateParameter:
3222 return createCXString("TemplateTemplateParameter");
3223 case CXCursor_FunctionTemplate:
3224 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003225 case CXCursor_ClassTemplate:
3226 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003227 case CXCursor_ClassTemplatePartialSpecialization:
3228 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003229 case CXCursor_NamespaceAlias:
3230 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003231 case CXCursor_UsingDirective:
3232 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003233 case CXCursor_UsingDeclaration:
3234 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003235 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003236
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003237 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003238 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003239}
Steve Naroff89922f82009-08-31 00:59:03 +00003240
Ted Kremeneke68fff62010-02-17 00:41:32 +00003241enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3242 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003243 CXClientData client_data) {
3244 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003245
3246 // If our current best cursor is the construction of a temporary object,
3247 // don't replace that cursor with a type reference, because we want
3248 // clang_getCursor() to point at the constructor.
3249 if (clang_isExpression(BestCursor->kind) &&
3250 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3251 cursor.kind == CXCursor_TypeRef)
3252 return CXChildVisit_Recurse;
3253
Douglas Gregor85fe1562010-12-10 07:23:11 +00003254 // Don't override a preprocessing cursor with another preprocessing
3255 // cursor; we want the outermost preprocessing cursor.
3256 if (clang_isPreprocessing(cursor.kind) &&
3257 clang_isPreprocessing(BestCursor->kind))
3258 return CXChildVisit_Recurse;
3259
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003260 *BestCursor = cursor;
3261 return CXChildVisit_Recurse;
3262}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003263
Douglas Gregorb9790342010-01-22 21:44:22 +00003264CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3265 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003266 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003267
Ted Kremeneka60ed472010-11-16 08:15:36 +00003268 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003269 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3270
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003271 // Translate the given source location to make it point at the beginning of
3272 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003273 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003274
3275 // Guard against an invalid SourceLocation, or we may assert in one
3276 // of the following calls.
3277 if (SLoc.isInvalid())
3278 return clang_getNullCursor();
3279
Douglas Gregor40749ee2010-11-03 00:35:38 +00003280 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003281 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3282 CXXUnit->getASTContext().getLangOptions());
3283
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003284 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3285 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003286 // FIXME: Would be great to have a "hint" cursor, then walk from that
3287 // hint cursor upward until we find a cursor whose source range encloses
3288 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003289 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3290 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003291 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003292 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003293 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003294
3295 if (Logging) {
3296 CXFile SearchFile;
3297 unsigned SearchLine, SearchColumn;
3298 CXFile ResultFile;
3299 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003300 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3301 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003302 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3303
3304 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3305 0);
3306 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3307 &ResultColumn, 0);
3308 SearchFileName = clang_getFileName(SearchFile);
3309 ResultFileName = clang_getFileName(ResultFile);
3310 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003311 USR = clang_getCursorUSR(Result);
3312 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003313 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3314 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003315 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3316 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003317 clang_disposeString(SearchFileName);
3318 clang_disposeString(ResultFileName);
3319 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003320 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003321
3322 CXCursor Definition = clang_getCursorDefinition(Result);
3323 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3324 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3325 CXString DefinitionKindSpelling
3326 = clang_getCursorKindSpelling(Definition.kind);
3327 CXFile DefinitionFile;
3328 unsigned DefinitionLine, DefinitionColumn;
3329 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3330 &DefinitionLine, &DefinitionColumn, 0);
3331 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3332 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3333 clang_getCString(DefinitionKindSpelling),
3334 clang_getCString(DefinitionFileName),
3335 DefinitionLine, DefinitionColumn);
3336 clang_disposeString(DefinitionFileName);
3337 clang_disposeString(DefinitionKindSpelling);
3338 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003339 }
3340
Ted Kremeneke68fff62010-02-17 00:41:32 +00003341 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003342}
3343
Ted Kremenek73885552009-11-17 19:28:59 +00003344CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003345 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003346}
3347
3348unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003349 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003350}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003351
Douglas Gregor9ce55842010-11-20 00:09:34 +00003352unsigned clang_hashCursor(CXCursor C) {
3353 unsigned Index = 0;
3354 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3355 Index = 1;
3356
3357 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3358 std::make_pair(C.kind, C.data[Index]));
3359}
3360
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003361unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003362 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3363}
3364
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003365unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003366 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3367}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003368
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003369unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003370 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3371}
3372
Douglas Gregor97b98722010-01-19 23:20:36 +00003373unsigned clang_isExpression(enum CXCursorKind K) {
3374 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3375}
3376
3377unsigned clang_isStatement(enum CXCursorKind K) {
3378 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3379}
3380
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003381unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3382 return K == CXCursor_TranslationUnit;
3383}
3384
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003385unsigned clang_isPreprocessing(enum CXCursorKind K) {
3386 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3387}
3388
Ted Kremenekad6eff62010-03-08 21:17:29 +00003389unsigned clang_isUnexposed(enum CXCursorKind K) {
3390 switch (K) {
3391 case CXCursor_UnexposedDecl:
3392 case CXCursor_UnexposedExpr:
3393 case CXCursor_UnexposedStmt:
3394 case CXCursor_UnexposedAttr:
3395 return true;
3396 default:
3397 return false;
3398 }
3399}
3400
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003401CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003402 return C.kind;
3403}
3404
Douglas Gregor98258af2010-01-18 22:46:11 +00003405CXSourceLocation clang_getCursorLocation(CXCursor C) {
3406 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003407 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003408 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003409 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3410 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003411 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003412 }
3413
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003414 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003415 std::pair<ObjCProtocolDecl *, SourceLocation> P
3416 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003417 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003418 }
3419
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003420 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003421 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3422 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003423 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003424 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003425
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003426 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003427 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003428 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003429 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003430
3431 case CXCursor_TemplateRef: {
3432 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3433 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3434 }
3435
Douglas Gregor69319002010-08-31 23:48:11 +00003436 case CXCursor_NamespaceRef: {
3437 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3438 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3439 }
3440
Douglas Gregora67e03f2010-09-09 21:42:20 +00003441 case CXCursor_MemberRef: {
3442 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3443 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3444 }
3445
Ted Kremenek3064ef92010-08-27 21:34:58 +00003446 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003447 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3448 if (!BaseSpec)
3449 return clang_getNullLocation();
3450
3451 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3452 return cxloc::translateSourceLocation(getCursorContext(C),
3453 TSInfo->getTypeLoc().getBeginLoc());
3454
3455 return cxloc::translateSourceLocation(getCursorContext(C),
3456 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003457 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003458
Douglas Gregor36897b02010-09-10 00:22:18 +00003459 case CXCursor_LabelRef: {
3460 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3461 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3462 }
3463
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003464 case CXCursor_OverloadedDeclRef:
3465 return cxloc::translateSourceLocation(getCursorContext(C),
3466 getCursorOverloadedDeclRef(C).second);
3467
Douglas Gregorf46034a2010-01-18 23:41:10 +00003468 default:
3469 // FIXME: Need a way to enumerate all non-reference cases.
3470 llvm_unreachable("Missed a reference kind");
3471 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003472 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003473
3474 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003475 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003476 getLocationFromExpr(getCursorExpr(C)));
3477
Douglas Gregor36897b02010-09-10 00:22:18 +00003478 if (clang_isStatement(C.kind))
3479 return cxloc::translateSourceLocation(getCursorContext(C),
3480 getCursorStmt(C)->getLocStart());
3481
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003482 if (C.kind == CXCursor_PreprocessingDirective) {
3483 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3484 return cxloc::translateSourceLocation(getCursorContext(C), L);
3485 }
Douglas Gregor48072312010-03-18 15:23:44 +00003486
3487 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003488 SourceLocation L
3489 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003490 return cxloc::translateSourceLocation(getCursorContext(C), L);
3491 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003492
3493 if (C.kind == CXCursor_MacroDefinition) {
3494 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3495 return cxloc::translateSourceLocation(getCursorContext(C), L);
3496 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003497
3498 if (C.kind == CXCursor_InclusionDirective) {
3499 SourceLocation L
3500 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3501 return cxloc::translateSourceLocation(getCursorContext(C), L);
3502 }
3503
Ted Kremenek9a700d22010-05-12 06:16:13 +00003504 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003505 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003506
Douglas Gregorf46034a2010-01-18 23:41:10 +00003507 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003508 SourceLocation Loc = D->getLocation();
3509 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3510 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003511 // FIXME: Multiple variables declared in a single declaration
3512 // currently lack the information needed to correctly determine their
3513 // ranges when accounting for the type-specifier. We use context
3514 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3515 // and if so, whether it is the first decl.
3516 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3517 if (!cxcursor::isFirstInDeclGroup(C))
3518 Loc = VD->getLocation();
3519 }
3520
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003521 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003522}
Douglas Gregora7bde202010-01-19 00:34:46 +00003523
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003524} // end extern "C"
3525
3526static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003527 if (clang_isReference(C.kind)) {
3528 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003529 case CXCursor_ObjCSuperClassRef:
3530 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003531
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003532 case CXCursor_ObjCProtocolRef:
3533 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003534
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003535 case CXCursor_ObjCClassRef:
3536 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003537
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003538 case CXCursor_TypeRef:
3539 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003540
3541 case CXCursor_TemplateRef:
3542 return getCursorTemplateRef(C).second;
3543
Douglas Gregor69319002010-08-31 23:48:11 +00003544 case CXCursor_NamespaceRef:
3545 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003546
3547 case CXCursor_MemberRef:
3548 return getCursorMemberRef(C).second;
3549
Ted Kremenek3064ef92010-08-27 21:34:58 +00003550 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003551 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003552
Douglas Gregor36897b02010-09-10 00:22:18 +00003553 case CXCursor_LabelRef:
3554 return getCursorLabelRef(C).second;
3555
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003556 case CXCursor_OverloadedDeclRef:
3557 return getCursorOverloadedDeclRef(C).second;
3558
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003559 default:
3560 // FIXME: Need a way to enumerate all non-reference cases.
3561 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003562 }
3563 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003564
3565 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003566 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003567
3568 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003569 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003570
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003571 if (C.kind == CXCursor_PreprocessingDirective)
3572 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003573
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003574 if (C.kind == CXCursor_MacroInstantiation)
3575 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003576
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003577 if (C.kind == CXCursor_MacroDefinition)
3578 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003579
3580 if (C.kind == CXCursor_InclusionDirective)
3581 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3582
Ted Kremenek007a7c92010-11-01 23:26:51 +00003583 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3584 Decl *D = cxcursor::getCursorDecl(C);
3585 SourceRange R = D->getSourceRange();
3586 // FIXME: Multiple variables declared in a single declaration
3587 // currently lack the information needed to correctly determine their
3588 // ranges when accounting for the type-specifier. We use context
3589 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3590 // and if so, whether it is the first decl.
3591 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3592 if (!cxcursor::isFirstInDeclGroup(C))
3593 R.setBegin(VD->getLocation());
3594 }
3595 return R;
3596 }
Douglas Gregor66537982010-11-17 17:14:07 +00003597 return SourceRange();
3598}
3599
3600/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3601/// the decl-specifier-seq for declarations.
3602static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3603 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3604 Decl *D = cxcursor::getCursorDecl(C);
3605 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003606
Douglas Gregor2494dd02011-03-01 01:34:45 +00003607 // Adjust the start of the location for declarations preceded by
3608 // declaration specifiers.
3609 SourceLocation StartLoc;
3610 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3611 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3612 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3613 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3614 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3615 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3616 }
3617
3618 if (StartLoc.isValid() && R.getBegin().isValid() &&
3619 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3620 R.setBegin(StartLoc);
3621
3622 // FIXME: Multiple variables declared in a single declaration
3623 // currently lack the information needed to correctly determine their
3624 // ranges when accounting for the type-specifier. We use context
3625 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3626 // and if so, whether it is the first decl.
3627 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3628 if (!cxcursor::isFirstInDeclGroup(C))
3629 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003630 }
3631
3632 return R;
3633 }
3634
3635 return getRawCursorExtent(C);
3636}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003637
3638extern "C" {
3639
3640CXSourceRange clang_getCursorExtent(CXCursor C) {
3641 SourceRange R = getRawCursorExtent(C);
3642 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003643 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003644
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003645 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003646}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003647
3648CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003649 if (clang_isInvalid(C.kind))
3650 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003651
Ted Kremeneka60ed472010-11-16 08:15:36 +00003652 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003653 if (clang_isDeclaration(C.kind)) {
3654 Decl *D = getCursorDecl(C);
3655 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003656 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003657 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003658 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003659 if (ObjCForwardProtocolDecl *Protocols
3660 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003661 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003662 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3663 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3664 return MakeCXCursor(Property, tu);
3665
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003666 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003667 }
3668
Douglas Gregor97b98722010-01-19 23:20:36 +00003669 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003670 Expr *E = getCursorExpr(C);
3671 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003672 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003673 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003674
3675 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003676 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003677
Douglas Gregor97b98722010-01-19 23:20:36 +00003678 return clang_getNullCursor();
3679 }
3680
Douglas Gregor36897b02010-09-10 00:22:18 +00003681 if (clang_isStatement(C.kind)) {
3682 Stmt *S = getCursorStmt(C);
3683 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003684 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003685
3686 return clang_getNullCursor();
3687 }
3688
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003689 if (C.kind == CXCursor_MacroInstantiation) {
3690 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003691 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003692 }
3693
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003694 if (!clang_isReference(C.kind))
3695 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003696
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003697 switch (C.kind) {
3698 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003699 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003700
3701 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003702 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003703
3704 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003705 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003706
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003707 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003708 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003709
3710 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003711 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003712
Douglas Gregor69319002010-08-31 23:48:11 +00003713 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003714 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003715
Douglas Gregora67e03f2010-09-09 21:42:20 +00003716 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003717 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003718
Ted Kremenek3064ef92010-08-27 21:34:58 +00003719 case CXCursor_CXXBaseSpecifier: {
3720 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3721 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003722 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003723 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003724
Douglas Gregor36897b02010-09-10 00:22:18 +00003725 case CXCursor_LabelRef:
3726 // FIXME: We end up faking the "parent" declaration here because we
3727 // don't want to make CXCursor larger.
3728 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003729 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3730 .getTranslationUnitDecl(),
3731 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003732
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003733 case CXCursor_OverloadedDeclRef:
3734 return C;
3735
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003736 default:
3737 // We would prefer to enumerate all non-reference cursor kinds here.
3738 llvm_unreachable("Unhandled reference cursor kind");
3739 break;
3740 }
3741 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003742
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003743 return clang_getNullCursor();
3744}
3745
Douglas Gregorb6998662010-01-19 19:34:47 +00003746CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003747 if (clang_isInvalid(C.kind))
3748 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003749
Ted Kremeneka60ed472010-11-16 08:15:36 +00003750 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003751
Douglas Gregorb6998662010-01-19 19:34:47 +00003752 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003753 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003754 C = clang_getCursorReferenced(C);
3755 WasReference = true;
3756 }
3757
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003758 if (C.kind == CXCursor_MacroInstantiation)
3759 return clang_getCursorReferenced(C);
3760
Douglas Gregorb6998662010-01-19 19:34:47 +00003761 if (!clang_isDeclaration(C.kind))
3762 return clang_getNullCursor();
3763
3764 Decl *D = getCursorDecl(C);
3765 if (!D)
3766 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003767
Douglas Gregorb6998662010-01-19 19:34:47 +00003768 switch (D->getKind()) {
3769 // Declaration kinds that don't really separate the notions of
3770 // declaration and definition.
3771 case Decl::Namespace:
3772 case Decl::Typedef:
3773 case Decl::TemplateTypeParm:
3774 case Decl::EnumConstant:
3775 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003776 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003777 case Decl::ObjCIvar:
3778 case Decl::ObjCAtDefsField:
3779 case Decl::ImplicitParam:
3780 case Decl::ParmVar:
3781 case Decl::NonTypeTemplateParm:
3782 case Decl::TemplateTemplateParm:
3783 case Decl::ObjCCategoryImpl:
3784 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003785 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003786 case Decl::LinkageSpec:
3787 case Decl::ObjCPropertyImpl:
3788 case Decl::FileScopeAsm:
3789 case Decl::StaticAssert:
3790 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003791 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003792 return C;
3793
3794 // Declaration kinds that don't make any sense here, but are
3795 // nonetheless harmless.
3796 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003797 break;
3798
3799 // Declaration kinds for which the definition is not resolvable.
3800 case Decl::UnresolvedUsingTypename:
3801 case Decl::UnresolvedUsingValue:
3802 break;
3803
3804 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003805 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003806 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003807
3808 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003809 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003810
3811 case Decl::Enum:
3812 case Decl::Record:
3813 case Decl::CXXRecord:
3814 case Decl::ClassTemplateSpecialization:
3815 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003816 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003817 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003818 return clang_getNullCursor();
3819
3820 case Decl::Function:
3821 case Decl::CXXMethod:
3822 case Decl::CXXConstructor:
3823 case Decl::CXXDestructor:
3824 case Decl::CXXConversion: {
3825 const FunctionDecl *Def = 0;
3826 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003827 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003828 return clang_getNullCursor();
3829 }
3830
3831 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003832 // Ask the variable if it has a definition.
3833 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003834 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003835 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003836 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003837
Douglas Gregorb6998662010-01-19 19:34:47 +00003838 case Decl::FunctionTemplate: {
3839 const FunctionDecl *Def = 0;
3840 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003841 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003842 return clang_getNullCursor();
3843 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003844
Douglas Gregorb6998662010-01-19 19:34:47 +00003845 case Decl::ClassTemplate: {
3846 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003847 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003848 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003849 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003850 return clang_getNullCursor();
3851 }
3852
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003853 case Decl::Using:
3854 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003855 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003856
3857 case Decl::UsingShadow:
3858 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003860 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003861
3862 case Decl::ObjCMethod: {
3863 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3864 if (Method->isThisDeclarationADefinition())
3865 return C;
3866
3867 // Dig out the method definition in the associated
3868 // @implementation, if we have it.
3869 // FIXME: The ASTs should make finding the definition easier.
3870 if (ObjCInterfaceDecl *Class
3871 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3872 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3873 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3874 Method->isInstanceMethod()))
3875 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003876 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003877
3878 return clang_getNullCursor();
3879 }
3880
3881 case Decl::ObjCCategory:
3882 if (ObjCCategoryImplDecl *Impl
3883 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003884 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003885 return clang_getNullCursor();
3886
3887 case Decl::ObjCProtocol:
3888 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3889 return C;
3890 return clang_getNullCursor();
3891
3892 case Decl::ObjCInterface:
3893 // There are two notions of a "definition" for an Objective-C
3894 // class: the interface and its implementation. When we resolved a
3895 // reference to an Objective-C class, produce the @interface as
3896 // the definition; when we were provided with the interface,
3897 // produce the @implementation as the definition.
3898 if (WasReference) {
3899 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3900 return C;
3901 } else if (ObjCImplementationDecl *Impl
3902 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003903 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003904 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003905
Douglas Gregorb6998662010-01-19 19:34:47 +00003906 case Decl::ObjCProperty:
3907 // FIXME: We don't really know where to find the
3908 // ObjCPropertyImplDecls that implement this property.
3909 return clang_getNullCursor();
3910
3911 case Decl::ObjCCompatibleAlias:
3912 if (ObjCInterfaceDecl *Class
3913 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3914 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003915 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003916
Douglas Gregorb6998662010-01-19 19:34:47 +00003917 return clang_getNullCursor();
3918
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003919 case Decl::ObjCForwardProtocol:
3920 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003921 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003922
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003923 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003924 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003925 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003926
3927 case Decl::Friend:
3928 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003929 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003930 return clang_getNullCursor();
3931
3932 case Decl::FriendTemplate:
3933 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003934 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003935 return clang_getNullCursor();
3936 }
3937
3938 return clang_getNullCursor();
3939}
3940
3941unsigned clang_isCursorDefinition(CXCursor C) {
3942 if (!clang_isDeclaration(C.kind))
3943 return 0;
3944
3945 return clang_getCursorDefinition(C) == C;
3946}
3947
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003948CXCursor clang_getCanonicalCursor(CXCursor C) {
3949 if (!clang_isDeclaration(C.kind))
3950 return C;
3951
3952 if (Decl *D = getCursorDecl(C))
3953 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3954
3955 return C;
3956}
3957
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003958unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003959 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003960 return 0;
3961
3962 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3963 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3964 return E->getNumDecls();
3965
3966 if (OverloadedTemplateStorage *S
3967 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3968 return S->size();
3969
3970 Decl *D = Storage.get<Decl*>();
3971 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003972 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003973 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3974 return Classes->size();
3975 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3976 return Protocols->protocol_size();
3977
3978 return 0;
3979}
3980
3981CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003982 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003983 return clang_getNullCursor();
3984
3985 if (index >= clang_getNumOverloadedDecls(cursor))
3986 return clang_getNullCursor();
3987
Ted Kremeneka60ed472010-11-16 08:15:36 +00003988 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003989 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3990 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003991 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003992
3993 if (OverloadedTemplateStorage *S
3994 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003995 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003996
3997 Decl *D = Storage.get<Decl*>();
3998 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3999 // FIXME: This is, unfortunately, linear time.
4000 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4001 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004002 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004003 }
4004
4005 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004006 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004007
4008 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004009 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004010
4011 return clang_getNullCursor();
4012}
4013
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004014void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004015 const char **startBuf,
4016 const char **endBuf,
4017 unsigned *startLine,
4018 unsigned *startColumn,
4019 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004020 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004021 assert(getCursorDecl(C) && "CXCursor has null decl");
4022 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004023 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4024 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004025
Steve Naroff4ade6d62009-09-23 17:52:52 +00004026 SourceManager &SM = FD->getASTContext().getSourceManager();
4027 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4028 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4029 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4030 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4031 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4032 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4033}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004034
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004035void clang_enableStackTraces(void) {
4036 llvm::sys::PrintStackTraceOnErrorSignal();
4037}
4038
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004039void clang_executeOnThread(void (*fn)(void*), void *user_data,
4040 unsigned stack_size) {
4041 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4042}
4043
Ted Kremenekfb480492010-01-13 21:46:36 +00004044} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004045
Ted Kremenekfb480492010-01-13 21:46:36 +00004046//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004047// Token-based Operations.
4048//===----------------------------------------------------------------------===//
4049
4050/* CXToken layout:
4051 * int_data[0]: a CXTokenKind
4052 * int_data[1]: starting token location
4053 * int_data[2]: token length
4054 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004055 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004056 * otherwise unused.
4057 */
4058extern "C" {
4059
4060CXTokenKind clang_getTokenKind(CXToken CXTok) {
4061 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4062}
4063
4064CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4065 switch (clang_getTokenKind(CXTok)) {
4066 case CXToken_Identifier:
4067 case CXToken_Keyword:
4068 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004069 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4070 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004071
4072 case CXToken_Literal: {
4073 // We have stashed the starting pointer in the ptr_data field. Use it.
4074 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004075 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004076 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004077
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004078 case CXToken_Punctuation:
4079 case CXToken_Comment:
4080 break;
4081 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004082
4083 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004084 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004085 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004086 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004087 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004088
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004089 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4090 std::pair<FileID, unsigned> LocInfo
4091 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004092 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004093 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004094 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4095 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004096 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004097
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004098 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004099}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004100
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004101CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004102 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004103 if (!CXXUnit)
4104 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004105
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004106 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4107 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4108}
4109
4110CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004111 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004112 if (!CXXUnit)
4113 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004114
4115 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004116 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4117}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004118
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004119void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4120 CXToken **Tokens, unsigned *NumTokens) {
4121 if (Tokens)
4122 *Tokens = 0;
4123 if (NumTokens)
4124 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004125
Ted Kremeneka60ed472010-11-16 08:15:36 +00004126 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004127 if (!CXXUnit || !Tokens || !NumTokens)
4128 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004129
Douglas Gregorbdf60622010-03-05 21:16:25 +00004130 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4131
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004132 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004133 if (R.isInvalid())
4134 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004135
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004136 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4137 std::pair<FileID, unsigned> BeginLocInfo
4138 = SourceMgr.getDecomposedLoc(R.getBegin());
4139 std::pair<FileID, unsigned> EndLocInfo
4140 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004141
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004142 // Cannot tokenize across files.
4143 if (BeginLocInfo.first != EndLocInfo.first)
4144 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004145
4146 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004147 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004148 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004149 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004150 if (Invalid)
4151 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004152
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004153 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4154 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004155 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004156 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004157
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004158 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004159 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004160 llvm::SmallVector<CXToken, 32> CXTokens;
4161 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004162 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004163 do {
4164 // Lex the next token
4165 Lex.LexFromRawLexer(Tok);
4166 if (Tok.is(tok::eof))
4167 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004168
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004169 // Initialize the CXToken.
4170 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004171
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004172 // - Common fields
4173 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4174 CXTok.int_data[2] = Tok.getLength();
4175 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004176
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004177 // - Kind-specific fields
4178 if (Tok.isLiteral()) {
4179 CXTok.int_data[0] = CXToken_Literal;
4180 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004181 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004182 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004183 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004184 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004185
David Chisnall096428b2010-10-13 21:44:48 +00004186 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004187 CXTok.int_data[0] = CXToken_Keyword;
4188 }
4189 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004190 CXTok.int_data[0] = Tok.is(tok::identifier)
4191 ? CXToken_Identifier
4192 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004193 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004194 CXTok.ptr_data = II;
4195 } else if (Tok.is(tok::comment)) {
4196 CXTok.int_data[0] = CXToken_Comment;
4197 CXTok.ptr_data = 0;
4198 } else {
4199 CXTok.int_data[0] = CXToken_Punctuation;
4200 CXTok.ptr_data = 0;
4201 }
4202 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004203 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004204 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004205
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004206 if (CXTokens.empty())
4207 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004208
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004209 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4210 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4211 *NumTokens = CXTokens.size();
4212}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004213
Ted Kremenek6db61092010-05-05 00:55:15 +00004214void clang_disposeTokens(CXTranslationUnit TU,
4215 CXToken *Tokens, unsigned NumTokens) {
4216 free(Tokens);
4217}
4218
4219} // end: extern "C"
4220
4221//===----------------------------------------------------------------------===//
4222// Token annotation APIs.
4223//===----------------------------------------------------------------------===//
4224
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004225typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004226static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4227 CXCursor parent,
4228 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004229namespace {
4230class AnnotateTokensWorker {
4231 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004232 CXToken *Tokens;
4233 CXCursor *Cursors;
4234 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004235 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004236 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004237 CursorVisitor AnnotateVis;
4238 SourceManager &SrcMgr;
4239
4240 bool MoreTokens() const { return TokIdx < NumTokens; }
4241 unsigned NextToken() const { return TokIdx; }
4242 void AdvanceToken() { ++TokIdx; }
4243 SourceLocation GetTokenLoc(unsigned tokI) {
4244 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4245 }
4246
Ted Kremenek6db61092010-05-05 00:55:15 +00004247public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004248 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004249 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004250 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004251 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004252 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004253 AnnotateVis(tu,
4254 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004255 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004256 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004257
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004258 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004259 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004260 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004261 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004262 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004263 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004264};
4265}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004266
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004267void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4268 // Walk the AST within the region of interest, annotating tokens
4269 // along the way.
4270 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004271
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004272 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4273 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004274 if (Pos != Annotated.end() &&
4275 (clang_isInvalid(Cursors[I].kind) ||
4276 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004277 Cursors[I] = Pos->second;
4278 }
4279
4280 // Finish up annotating any tokens left.
4281 if (!MoreTokens())
4282 return;
4283
4284 const CXCursor &C = clang_getNullCursor();
4285 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4286 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4287 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004288 }
4289}
4290
Ted Kremenek6db61092010-05-05 00:55:15 +00004291enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004292AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004293 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004294 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004295 if (cursorRange.isInvalid())
4296 return CXChildVisit_Recurse;
4297
Douglas Gregor4419b672010-10-21 06:10:04 +00004298 if (clang_isPreprocessing(cursor.kind)) {
4299 // For macro instantiations, just note where the beginning of the macro
4300 // instantiation occurs.
4301 if (cursor.kind == CXCursor_MacroInstantiation) {
4302 Annotated[Loc.int_data] = cursor;
4303 return CXChildVisit_Recurse;
4304 }
4305
Douglas Gregor4419b672010-10-21 06:10:04 +00004306 // Items in the preprocessing record are kept separate from items in
4307 // declarations, so we keep a separate token index.
4308 unsigned SavedTokIdx = TokIdx;
4309 TokIdx = PreprocessingTokIdx;
4310
4311 // Skip tokens up until we catch up to the beginning of the preprocessing
4312 // entry.
4313 while (MoreTokens()) {
4314 const unsigned I = NextToken();
4315 SourceLocation TokLoc = GetTokenLoc(I);
4316 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4317 case RangeBefore:
4318 AdvanceToken();
4319 continue;
4320 case RangeAfter:
4321 case RangeOverlap:
4322 break;
4323 }
4324 break;
4325 }
4326
4327 // Look at all of the tokens within this range.
4328 while (MoreTokens()) {
4329 const unsigned I = NextToken();
4330 SourceLocation TokLoc = GetTokenLoc(I);
4331 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4332 case RangeBefore:
4333 assert(0 && "Infeasible");
4334 case RangeAfter:
4335 break;
4336 case RangeOverlap:
4337 Cursors[I] = cursor;
4338 AdvanceToken();
4339 continue;
4340 }
4341 break;
4342 }
4343
4344 // Save the preprocessing token index; restore the non-preprocessing
4345 // token index.
4346 PreprocessingTokIdx = TokIdx;
4347 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004348 return CXChildVisit_Recurse;
4349 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004350
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004351 if (cursorRange.isInvalid())
4352 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004353
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004354 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4355
Ted Kremeneka333c662010-05-12 05:29:33 +00004356 // Adjust the annotated range based specific declarations.
4357 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4358 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004359 Decl *D = cxcursor::getCursorDecl(cursor);
4360 // Don't visit synthesized ObjC methods, since they have no syntatic
4361 // representation in the source.
4362 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4363 if (MD->isSynthesized())
4364 return CXChildVisit_Continue;
4365 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004366
4367 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004368 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004369 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4370 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4371 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4372 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4373 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004374 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004375
4376 if (StartLoc.isValid() && L.isValid() &&
4377 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4378 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004379 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004380
Ted Kremenek3f404602010-08-14 01:14:06 +00004381 // If the location of the cursor occurs within a macro instantiation, record
4382 // the spelling location of the cursor in our annotation map. We can then
4383 // paper over the token labelings during a post-processing step to try and
4384 // get cursor mappings for tokens that are the *arguments* of a macro
4385 // instantiation.
4386 if (L.isMacroID()) {
4387 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4388 // Only invalidate the old annotation if it isn't part of a preprocessing
4389 // directive. Here we assume that the default construction of CXCursor
4390 // results in CXCursor.kind being an initialized value (i.e., 0). If
4391 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004392
Ted Kremenek3f404602010-08-14 01:14:06 +00004393 CXCursor &oldC = Annotated[rawEncoding];
4394 if (!clang_isPreprocessing(oldC.kind))
4395 oldC = cursor;
4396 }
4397
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004398 const enum CXCursorKind K = clang_getCursorKind(parent);
4399 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004400 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4401 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004402
4403 while (MoreTokens()) {
4404 const unsigned I = NextToken();
4405 SourceLocation TokLoc = GetTokenLoc(I);
4406 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4407 case RangeBefore:
4408 Cursors[I] = updateC;
4409 AdvanceToken();
4410 continue;
4411 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004412 case RangeOverlap:
4413 break;
4414 }
4415 break;
4416 }
4417
4418 // Visit children to get their cursor information.
4419 const unsigned BeforeChildren = NextToken();
4420 VisitChildren(cursor);
4421 const unsigned AfterChildren = NextToken();
4422
4423 // Adjust 'Last' to the last token within the extent of the cursor.
4424 while (MoreTokens()) {
4425 const unsigned I = NextToken();
4426 SourceLocation TokLoc = GetTokenLoc(I);
4427 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4428 case RangeBefore:
4429 assert(0 && "Infeasible");
4430 case RangeAfter:
4431 break;
4432 case RangeOverlap:
4433 Cursors[I] = updateC;
4434 AdvanceToken();
4435 continue;
4436 }
4437 break;
4438 }
4439 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004440
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004441 // Scan the tokens that are at the beginning of the cursor, but are not
4442 // capture by the child cursors.
4443
4444 // For AST elements within macros, rely on a post-annotate pass to
4445 // to correctly annotate the tokens with cursors. Otherwise we can
4446 // get confusing results of having tokens that map to cursors that really
4447 // are expanded by an instantiation.
4448 if (L.isMacroID())
4449 cursor = clang_getNullCursor();
4450
4451 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4452 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4453 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004454
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004455 Cursors[I] = cursor;
4456 }
4457 // Scan the tokens that are at the end of the cursor, but are not captured
4458 // but the child cursors.
4459 for (unsigned I = AfterChildren; I != Last; ++I)
4460 Cursors[I] = cursor;
4461
4462 TokIdx = Last;
4463 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004464}
4465
Ted Kremenek6db61092010-05-05 00:55:15 +00004466static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4467 CXCursor parent,
4468 CXClientData client_data) {
4469 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4470}
4471
Ted Kremenekab979612010-11-11 08:05:23 +00004472// This gets run a separate thread to avoid stack blowout.
4473static void runAnnotateTokensWorker(void *UserData) {
4474 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4475}
4476
Ted Kremenek6db61092010-05-05 00:55:15 +00004477extern "C" {
4478
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004479void clang_annotateTokens(CXTranslationUnit TU,
4480 CXToken *Tokens, unsigned NumTokens,
4481 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004482
4483 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004484 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004485
Douglas Gregor4419b672010-10-21 06:10:04 +00004486 // Any token we don't specifically annotate will have a NULL cursor.
4487 CXCursor C = clang_getNullCursor();
4488 for (unsigned I = 0; I != NumTokens; ++I)
4489 Cursors[I] = C;
4490
Ted Kremeneka60ed472010-11-16 08:15:36 +00004491 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004492 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004493 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004494
Douglas Gregorbdf60622010-03-05 21:16:25 +00004495 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004496
Douglas Gregor0396f462010-03-19 05:22:59 +00004497 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004498 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004499 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4500 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004501 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4502 clang_getTokenLocation(TU,
4503 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004504
Douglas Gregor0396f462010-03-19 05:22:59 +00004505 // A mapping from the source locations found when re-lexing or traversing the
4506 // region of interest to the corresponding cursors.
4507 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004508
4509 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004510 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004511 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4512 std::pair<FileID, unsigned> BeginLocInfo
4513 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4514 std::pair<FileID, unsigned> EndLocInfo
4515 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004516
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004517 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004518 bool Invalid = false;
4519 if (BeginLocInfo.first == EndLocInfo.first &&
4520 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4521 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004522 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4523 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004524 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004525 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004526 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004527
4528 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004529 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004530 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004531 Token Tok;
4532 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004533
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004534 reprocess:
4535 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4536 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004537 // don't see it while preprocessing these tokens later, but keep track
4538 // of all of the token locations inside this preprocessing directive so
4539 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004540 //
4541 // FIXME: Some simple tests here could identify macro definitions and
4542 // #undefs, to provide specific cursor kinds for those.
4543 std::vector<SourceLocation> Locations;
4544 do {
4545 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004546 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004547 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004548
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004549 using namespace cxcursor;
4550 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004551 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4552 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004553 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004554 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4555 Annotated[Locations[I].getRawEncoding()] = Cursor;
4556 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004557
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004558 if (Tok.isAtStartOfLine())
4559 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004560
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004561 continue;
4562 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004563
Douglas Gregor48072312010-03-18 15:23:44 +00004564 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004565 break;
4566 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004567 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004568
Douglas Gregor0396f462010-03-19 05:22:59 +00004569 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004570 // a specific cursor.
4571 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004572 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004573
4574 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004575 // FIXME: We use a ridiculous stack size here because the data-recursion
4576 // algorithm uses a large stack frame than the non-data recursive version,
4577 // and AnnotationTokensWorker currently transforms the data-recursion
4578 // algorithm back into a traditional recursion by explicitly calling
4579 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004580 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004581 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4582 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004583 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4584 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004585}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004586} // end: extern "C"
4587
4588//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004589// Operations for querying linkage of a cursor.
4590//===----------------------------------------------------------------------===//
4591
4592extern "C" {
4593CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004594 if (!clang_isDeclaration(cursor.kind))
4595 return CXLinkage_Invalid;
4596
Ted Kremenek16b42592010-03-03 06:36:57 +00004597 Decl *D = cxcursor::getCursorDecl(cursor);
4598 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4599 switch (ND->getLinkage()) {
4600 case NoLinkage: return CXLinkage_NoLinkage;
4601 case InternalLinkage: return CXLinkage_Internal;
4602 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4603 case ExternalLinkage: return CXLinkage_External;
4604 };
4605
4606 return CXLinkage_Invalid;
4607}
4608} // end: extern "C"
4609
4610//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004611// Operations for querying language of a cursor.
4612//===----------------------------------------------------------------------===//
4613
4614static CXLanguageKind getDeclLanguage(const Decl *D) {
4615 switch (D->getKind()) {
4616 default:
4617 break;
4618 case Decl::ImplicitParam:
4619 case Decl::ObjCAtDefsField:
4620 case Decl::ObjCCategory:
4621 case Decl::ObjCCategoryImpl:
4622 case Decl::ObjCClass:
4623 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004624 case Decl::ObjCForwardProtocol:
4625 case Decl::ObjCImplementation:
4626 case Decl::ObjCInterface:
4627 case Decl::ObjCIvar:
4628 case Decl::ObjCMethod:
4629 case Decl::ObjCProperty:
4630 case Decl::ObjCPropertyImpl:
4631 case Decl::ObjCProtocol:
4632 return CXLanguage_ObjC;
4633 case Decl::CXXConstructor:
4634 case Decl::CXXConversion:
4635 case Decl::CXXDestructor:
4636 case Decl::CXXMethod:
4637 case Decl::CXXRecord:
4638 case Decl::ClassTemplate:
4639 case Decl::ClassTemplatePartialSpecialization:
4640 case Decl::ClassTemplateSpecialization:
4641 case Decl::Friend:
4642 case Decl::FriendTemplate:
4643 case Decl::FunctionTemplate:
4644 case Decl::LinkageSpec:
4645 case Decl::Namespace:
4646 case Decl::NamespaceAlias:
4647 case Decl::NonTypeTemplateParm:
4648 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004649 case Decl::TemplateTemplateParm:
4650 case Decl::TemplateTypeParm:
4651 case Decl::UnresolvedUsingTypename:
4652 case Decl::UnresolvedUsingValue:
4653 case Decl::Using:
4654 case Decl::UsingDirective:
4655 case Decl::UsingShadow:
4656 return CXLanguage_CPlusPlus;
4657 }
4658
4659 return CXLanguage_C;
4660}
4661
4662extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004663
4664enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4665 if (clang_isDeclaration(cursor.kind))
4666 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4667 if (D->hasAttr<UnavailableAttr>() ||
4668 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4669 return CXAvailability_Available;
4670
4671 if (D->hasAttr<DeprecatedAttr>())
4672 return CXAvailability_Deprecated;
4673 }
4674
4675 return CXAvailability_Available;
4676}
4677
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004678CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4679 if (clang_isDeclaration(cursor.kind))
4680 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4681
4682 return CXLanguage_Invalid;
4683}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004684
4685 /// \brief If the given cursor is the "templated" declaration
4686 /// descibing a class or function template, return the class or
4687 /// function template.
4688static Decl *maybeGetTemplateCursor(Decl *D) {
4689 if (!D)
4690 return 0;
4691
4692 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4693 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4694 return FunTmpl;
4695
4696 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4697 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4698 return ClassTmpl;
4699
4700 return D;
4701}
4702
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004703CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4704 if (clang_isDeclaration(cursor.kind)) {
4705 if (Decl *D = getCursorDecl(cursor)) {
4706 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004707 if (!DC)
4708 return clang_getNullCursor();
4709
4710 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4711 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004712 }
4713 }
4714
4715 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4716 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004717 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004718 }
4719
4720 return clang_getNullCursor();
4721}
4722
4723CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4724 if (clang_isDeclaration(cursor.kind)) {
4725 if (Decl *D = getCursorDecl(cursor)) {
4726 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004727 if (!DC)
4728 return clang_getNullCursor();
4729
4730 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4731 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004732 }
4733 }
4734
4735 // FIXME: Note that we can't easily compute the lexical context of a
4736 // statement or expression, so we return nothing.
4737 return clang_getNullCursor();
4738}
4739
Douglas Gregor9f592342010-10-01 20:25:15 +00004740static void CollectOverriddenMethods(DeclContext *Ctx,
4741 ObjCMethodDecl *Method,
4742 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4743 if (!Ctx)
4744 return;
4745
4746 // If we have a class or category implementation, jump straight to the
4747 // interface.
4748 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4749 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4750
4751 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4752 if (!Container)
4753 return;
4754
4755 // Check whether we have a matching method at this level.
4756 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4757 Method->isInstanceMethod()))
4758 if (Method != Overridden) {
4759 // We found an override at this level; there is no need to look
4760 // into other protocols or categories.
4761 Methods.push_back(Overridden);
4762 return;
4763 }
4764
4765 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4766 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4767 PEnd = Protocol->protocol_end();
4768 P != PEnd; ++P)
4769 CollectOverriddenMethods(*P, Method, Methods);
4770 }
4771
4772 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4773 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4774 PEnd = Category->protocol_end();
4775 P != PEnd; ++P)
4776 CollectOverriddenMethods(*P, Method, Methods);
4777 }
4778
4779 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4780 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4781 PEnd = Interface->protocol_end();
4782 P != PEnd; ++P)
4783 CollectOverriddenMethods(*P, Method, Methods);
4784
4785 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4786 Category; Category = Category->getNextClassCategory())
4787 CollectOverriddenMethods(Category, Method, Methods);
4788
4789 // We only look into the superclass if we haven't found anything yet.
4790 if (Methods.empty())
4791 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4792 return CollectOverriddenMethods(Super, Method, Methods);
4793 }
4794}
4795
4796void clang_getOverriddenCursors(CXCursor cursor,
4797 CXCursor **overridden,
4798 unsigned *num_overridden) {
4799 if (overridden)
4800 *overridden = 0;
4801 if (num_overridden)
4802 *num_overridden = 0;
4803 if (!overridden || !num_overridden)
4804 return;
4805
4806 if (!clang_isDeclaration(cursor.kind))
4807 return;
4808
4809 Decl *D = getCursorDecl(cursor);
4810 if (!D)
4811 return;
4812
4813 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004814 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004815 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4816 *num_overridden = CXXMethod->size_overridden_methods();
4817 if (!*num_overridden)
4818 return;
4819
4820 *overridden = new CXCursor [*num_overridden];
4821 unsigned I = 0;
4822 for (CXXMethodDecl::method_iterator
4823 M = CXXMethod->begin_overridden_methods(),
4824 MEnd = CXXMethod->end_overridden_methods();
4825 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004826 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004827 return;
4828 }
4829
4830 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4831 if (!Method)
4832 return;
4833
4834 // Handle Objective-C methods.
4835 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4836 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4837
4838 if (Methods.empty())
4839 return;
4840
4841 *num_overridden = Methods.size();
4842 *overridden = new CXCursor [Methods.size()];
4843 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004844 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004845}
4846
4847void clang_disposeOverriddenCursors(CXCursor *overridden) {
4848 delete [] overridden;
4849}
4850
Douglas Gregorecdcb882010-10-20 22:00:55 +00004851CXFile clang_getIncludedFile(CXCursor cursor) {
4852 if (cursor.kind != CXCursor_InclusionDirective)
4853 return 0;
4854
4855 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4856 return (void *)ID->getFile();
4857}
4858
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004859} // end: extern "C"
4860
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004861
4862//===----------------------------------------------------------------------===//
4863// C++ AST instrospection.
4864//===----------------------------------------------------------------------===//
4865
4866extern "C" {
4867unsigned clang_CXXMethod_isStatic(CXCursor C) {
4868 if (!clang_isDeclaration(C.kind))
4869 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004870
4871 CXXMethodDecl *Method = 0;
4872 Decl *D = cxcursor::getCursorDecl(C);
4873 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4874 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4875 else
4876 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4877 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004878}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004879
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004880} // end: extern "C"
4881
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004882//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004883// Attribute introspection.
4884//===----------------------------------------------------------------------===//
4885
4886extern "C" {
4887CXType clang_getIBOutletCollectionType(CXCursor C) {
4888 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004889 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004890
4891 IBOutletCollectionAttr *A =
4892 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4893
Ted Kremeneka60ed472010-11-16 08:15:36 +00004894 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004895}
4896} // end: extern "C"
4897
4898//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004899// Misc. utility functions.
4900//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004901
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004902/// Default to using an 8 MB stack size on "safety" threads.
4903static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004904
4905namespace clang {
4906
4907bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004908 void (*Fn)(void*), void *UserData,
4909 unsigned Size) {
4910 if (!Size)
4911 Size = GetSafetyThreadStackSize();
4912 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004913 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4914 return CRC.RunSafely(Fn, UserData);
4915}
4916
4917unsigned GetSafetyThreadStackSize() {
4918 return SafetyStackThreadSize;
4919}
4920
4921void SetSafetyThreadStackSize(unsigned Value) {
4922 SafetyStackThreadSize = Value;
4923}
4924
4925}
4926
Ted Kremenek04bb7162010-01-22 22:44:15 +00004927extern "C" {
4928
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004929CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004930 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004931}
4932
4933} // end: extern "C"