blob: 74f90790c748fa590a6aaf178f55ab5bbc580977 [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 Gregor94fdffa2011-03-01 20:11:18 +0000346 bool VisitDependentTemplateSpecializationTypeLoc(
347 DependentTemplateSpecializationTypeLoc TL);
Douglas Gregor9e876872011-03-01 18:12:44 +0000348 bool VisitElaboratedTypeLoc(ElaboratedTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000349
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000350 // Data-recursive visitor functions.
351 bool IsInRegionOfInterest(CXCursor C);
352 bool RunVisitorWorkList(VisitorWorkList &WL);
353 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000354 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000355};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000356
Ted Kremenekab188932010-01-05 19:32:54 +0000357} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000358
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000359static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000360static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
361
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000362
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000363RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000364 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365}
366
Douglas Gregorb1373d02010-01-20 20:59:29 +0000367/// \brief Visit the given cursor and, if requested by the visitor,
368/// its children.
369///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000370/// \param Cursor the cursor to visit.
371///
372/// \param CheckRegionOfInterest if true, then the caller already checked that
373/// this cursor is within the region of interest.
374///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375/// \returns true if the visitation should be aborted, false if it
376/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000377bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378 if (clang_isInvalid(Cursor.kind))
379 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000380
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381 if (clang_isDeclaration(Cursor.kind)) {
382 Decl *D = getCursorDecl(Cursor);
383 assert(D && "Invalid declaration cursor");
384 if (D->getPCHLevel() > MaxPCHLevel)
385 return false;
386
387 if (D->isImplicit())
388 return false;
389 }
390
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391 // If we have a range of interest, and this cursor doesn't intersect with it,
392 // we're done.
393 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000394 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000395 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000396 return false;
397 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000398
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399 switch (Visitor(Cursor, Parent, ClientData)) {
400 case CXChildVisit_Break:
401 return true;
402
403 case CXChildVisit_Continue:
404 return false;
405
406 case CXChildVisit_Recurse:
407 return VisitChildren(Cursor);
408 }
409
Douglas Gregorfd643772010-01-25 16:45:46 +0000410 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000411}
412
Douglas Gregor788f5a12010-03-20 00:41:21 +0000413std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
414CursorVisitor::getPreprocessedEntities() {
415 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000416 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000417
418 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000419 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
420
421 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
422 // If we would only look at local declarations but we have a region of
423 // interest, check whether that region of interest is in the main file.
424 // If not, we should traverse all declarations.
425 // FIXME: My kingdom for a proper binary search approach to finding
426 // cursors!
427 std::pair<FileID, unsigned> Location
428 = AU->getSourceManager().getDecomposedInstantiationLoc(
429 RegionOfInterest.getBegin());
430 if (Location.first != AU->getSourceManager().getMainFileID())
431 OnlyLocalDecls = false;
432 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000433
Douglas Gregor89d99802010-11-30 06:16:57 +0000434 PreprocessingRecord::iterator StartEntity, EndEntity;
435 if (OnlyLocalDecls) {
436 StartEntity = AU->pp_entity_begin();
437 EndEntity = AU->pp_entity_end();
438 } else {
439 StartEntity = PPRec.begin();
440 EndEntity = PPRec.end();
441 }
442
Douglas Gregor788f5a12010-03-20 00:41:21 +0000443 // There is no region of interest; we have to walk everything.
444 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000445 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000446
447 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000448 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000449 std::pair<FileID, unsigned> Begin
450 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
451 std::pair<FileID, unsigned> End
452 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
453
454 // The region of interest spans files; we have to walk everything.
455 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000456 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000457
458 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000459 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000460 if (ByFileMap.empty()) {
461 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000462 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000463 std::pair<FileID, unsigned> P
464 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000465
Douglas Gregor788f5a12010-03-20 00:41:21 +0000466 ByFileMap[P.first].push_back(*E);
467 }
468 }
469
470 return std::make_pair(ByFileMap[Begin.first].begin(),
471 ByFileMap[Begin.first].end());
472}
473
Douglas Gregorb1373d02010-01-20 20:59:29 +0000474/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000475///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476/// \returns true if the visitation should be aborted, false if it
477/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000479 if (clang_isReference(Cursor.kind) &&
480 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000481 // By definition, references have no children.
482 return false;
483 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000484
485 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000487 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000488
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489 if (clang_isDeclaration(Cursor.kind)) {
490 Decl *D = getCursorDecl(Cursor);
491 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000492 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000494
Douglas Gregora59e3902010-01-21 23:27:09 +0000495 if (clang_isStatement(Cursor.kind))
496 return Visit(getCursorStmt(Cursor));
497 if (clang_isExpression(Cursor.kind))
498 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000499
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000501 CXTranslationUnit tu = getCursorTU(Cursor);
502 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000503 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
504 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000505 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
506 TLEnd = CXXUnit->top_level_end();
507 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000508 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000509 return true;
510 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000511 } else if (VisitDeclContext(
512 CXXUnit->getASTContext().getTranslationUnitDecl()))
513 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000514
Douglas Gregor0396f462010-03-19 05:22:59 +0000515 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000516 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 // FIXME: Once we have the ability to deserialize a preprocessing record,
518 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000519 PreprocessingRecord::iterator E, EEnd;
520 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000522 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000523 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000524
Douglas Gregor0396f462010-03-19 05:22:59 +0000525 continue;
526 }
527
528 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000529 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000530 return true;
531
532 continue;
533 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000534
535 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000536 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000537 return true;
538
539 continue;
540 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000541 }
542 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000543 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000544 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000545
Douglas Gregorc314aa42011-03-02 19:17:03 +0000546 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
547 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
548 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
549 return Visit(BaseTSInfo->getTypeLoc());
550 }
551 }
552 }
553
Douglas Gregorb1373d02010-01-20 20:59:29 +0000554 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000555 return false;
556}
557
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000558bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000559 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
560 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000561
Ted Kremenek664cffd2010-07-22 11:30:19 +0000562 if (Stmt *Body = B->getBody())
563 return Visit(MakeCXCursor(Body, StmtParent, TU));
564
565 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000566}
567
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000568llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
569 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000570 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000571 if (Range.isInvalid())
572 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000573
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000574 switch (CompareRegionOfInterest(Range)) {
575 case RangeBefore:
576 // This declaration comes before the region of interest; skip it.
577 return llvm::Optional<bool>();
578
579 case RangeAfter:
580 // This declaration comes after the region of interest; we're done.
581 return false;
582
583 case RangeOverlap:
584 // This declaration overlaps the region of interest; visit it.
585 break;
586 }
587 }
588 return true;
589}
590
591bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
592 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
593
594 // FIXME: Eventually remove. This part of a hack to support proper
595 // iteration over all Decls contained lexically within an ObjC container.
596 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
597 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
598
599 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000600 Decl *D = *I;
601 if (D->getLexicalDeclContext() != DC)
602 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000603 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000604 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
605 if (!V.hasValue())
606 continue;
607 if (!V.getValue())
608 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000609 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000610 return true;
611 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000612 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000613}
614
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000615bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
616 llvm_unreachable("Translation units are visited directly by Visit()");
617 return false;
618}
619
620bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
621 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
622 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000623
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000624 return false;
625}
626
627bool CursorVisitor::VisitTagDecl(TagDecl *D) {
628 return VisitDeclContext(D);
629}
630
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000631bool CursorVisitor::VisitClassTemplateSpecializationDecl(
632 ClassTemplateSpecializationDecl *D) {
633 bool ShouldVisitBody = false;
634 switch (D->getSpecializationKind()) {
635 case TSK_Undeclared:
636 case TSK_ImplicitInstantiation:
637 // Nothing to visit
638 return false;
639
640 case TSK_ExplicitInstantiationDeclaration:
641 case TSK_ExplicitInstantiationDefinition:
642 break;
643
644 case TSK_ExplicitSpecialization:
645 ShouldVisitBody = true;
646 break;
647 }
648
649 // Visit the template arguments used in the specialization.
650 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
651 TypeLoc TL = SpecType->getTypeLoc();
652 if (TemplateSpecializationTypeLoc *TSTLoc
653 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
654 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
655 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
656 return true;
657 }
658 }
659
660 if (ShouldVisitBody && VisitCXXRecordDecl(D))
661 return true;
662
663 return false;
664}
665
Douglas Gregor74dbe642010-08-31 19:31:58 +0000666bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
667 ClassTemplatePartialSpecializationDecl *D) {
668 // FIXME: Visit the "outer" template parameter lists on the TagDecl
669 // before visiting these template parameters.
670 if (VisitTemplateParameters(D->getTemplateParameters()))
671 return true;
672
673 // Visit the partial specialization arguments.
674 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
675 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
676 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
677 return true;
678
679 return VisitCXXRecordDecl(D);
680}
681
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000682bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000683 // Visit the default argument.
684 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
685 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
686 if (Visit(DefArg->getTypeLoc()))
687 return true;
688
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000689 return false;
690}
691
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000692bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
693 if (Expr *Init = D->getInitExpr())
694 return Visit(MakeCXCursor(Init, StmtParent, TU));
695 return false;
696}
697
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000698bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
699 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
700 if (Visit(TSInfo->getTypeLoc()))
701 return true;
702
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000703 // Visit the nested-name-specifier, if present.
704 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
705 if (VisitNestedNameSpecifierLoc(QualifierLoc))
706 return true;
707
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000708 return false;
709}
710
Douglas Gregora67e03f2010-09-09 21:42:20 +0000711/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000712static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
713 CXXCtorInitializer const * const *X
714 = static_cast<CXXCtorInitializer const * const *>(Xp);
715 CXXCtorInitializer const * const *Y
716 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000717
718 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
719 return -1;
720 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
721 return 1;
722 else
723 return 0;
724}
725
Douglas Gregorb1373d02010-01-20 20:59:29 +0000726bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000727 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
728 // Visit the function declaration's syntactic components in the order
729 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000730 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000731 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
732
733 // If we have a function declared directly (without the use of a typedef),
734 // visit just the return type. Otherwise, just visit the function's type
735 // now.
736 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
737 (!FTL && Visit(TL)))
738 return true;
739
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000740 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000741 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
742 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000743 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000744
745 // Visit the declaration name.
746 if (VisitDeclarationNameInfo(ND->getNameInfo()))
747 return true;
748
749 // FIXME: Visit explicitly-specified template arguments!
750
751 // Visit the function parameters, if we have a function type.
752 if (FTL && VisitFunctionTypeLoc(*FTL, true))
753 return true;
754
755 // FIXME: Attributes?
756 }
757
Douglas Gregora67e03f2010-09-09 21:42:20 +0000758 if (ND->isThisDeclarationADefinition()) {
759 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
760 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000761 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000762 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
763 IEnd = Constructor->init_end();
764 I != IEnd; ++I) {
765 if (!(*I)->isWritten())
766 continue;
767
768 WrittenInits.push_back(*I);
769 }
770
771 // Sort the initializers in source order
772 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000773 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000774
775 // Visit the initializers in source order
776 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000777 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000778 if (Init->isAnyMemberInitializer()) {
779 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000780 Init->getMemberLocation(), TU)))
781 return true;
782 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
783 if (Visit(BaseInfo->getTypeLoc()))
784 return true;
785 }
786
787 // Visit the initializer value.
788 if (Expr *Initializer = Init->getInit())
789 if (Visit(MakeCXCursor(Initializer, ND, TU)))
790 return true;
791 }
792 }
793
794 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
795 return true;
796 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000797
Douglas Gregorb1373d02010-01-20 20:59:29 +0000798 return false;
799}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000800
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000801bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
802 if (VisitDeclaratorDecl(D))
803 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 if (Expr *BitWidth = D->getBitWidth())
806 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000807
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000808 return false;
809}
810
811bool CursorVisitor::VisitVarDecl(VarDecl *D) {
812 if (VisitDeclaratorDecl(D))
813 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815 if (Expr *Init = D->getInit())
816 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000817
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000818 return false;
819}
820
Douglas Gregor84b51d72010-09-01 20:16:53 +0000821bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
822 if (VisitDeclaratorDecl(D))
823 return true;
824
825 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
826 if (Expr *DefArg = D->getDefaultArgument())
827 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
828
829 return false;
830}
831
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000832bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
833 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
834 // before visiting these template parameters.
835 if (VisitTemplateParameters(D->getTemplateParameters()))
836 return true;
837
838 return VisitFunctionDecl(D->getTemplatedDecl());
839}
840
Douglas Gregor39d6f072010-08-31 19:02:00 +0000841bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
842 // FIXME: Visit the "outer" template parameter lists on the TagDecl
843 // before visiting these template parameters.
844 if (VisitTemplateParameters(D->getTemplateParameters()))
845 return true;
846
847 return VisitCXXRecordDecl(D->getTemplatedDecl());
848}
849
Douglas Gregor84b51d72010-09-01 20:16:53 +0000850bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
851 if (VisitTemplateParameters(D->getTemplateParameters()))
852 return true;
853
854 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
855 VisitTemplateArgumentLoc(D->getDefaultArgument()))
856 return true;
857
858 return false;
859}
860
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000861bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000862 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
863 if (Visit(TSInfo->getTypeLoc()))
864 return true;
865
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000867 PEnd = ND->param_end();
868 P != PEnd; ++P) {
869 if (Visit(MakeCXCursor(*P, TU)))
870 return true;
871 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000872
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000873 if (ND->isThisDeclarationADefinition() &&
874 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
875 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000876
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000877 return false;
878}
879
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000880namespace {
881 struct ContainerDeclsSort {
882 SourceManager &SM;
883 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
884 bool operator()(Decl *A, Decl *B) {
885 SourceLocation L_A = A->getLocStart();
886 SourceLocation L_B = B->getLocStart();
887 assert(L_A.isValid() && L_B.isValid());
888 return SM.isBeforeInTranslationUnit(L_A, L_B);
889 }
890 };
891}
892
Douglas Gregora59e3902010-01-21 23:27:09 +0000893bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000894 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
895 // an @implementation can lexically contain Decls that are not properly
896 // nested in the AST. When we identify such cases, we need to retrofit
897 // this nesting here.
898 if (!DI_current)
899 return VisitDeclContext(D);
900
901 // Scan the Decls that immediately come after the container
902 // in the current DeclContext. If any fall within the
903 // container's lexical region, stash them into a vector
904 // for later processing.
905 llvm::SmallVector<Decl *, 24> DeclsInContainer;
906 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000907 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000908 if (EndLoc.isValid()) {
909 DeclContext::decl_iterator next = *DI_current;
910 while (++next != DE_current) {
911 Decl *D_next = *next;
912 if (!D_next)
913 break;
914 SourceLocation L = D_next->getLocStart();
915 if (!L.isValid())
916 break;
917 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
918 *DI_current = next;
919 DeclsInContainer.push_back(D_next);
920 continue;
921 }
922 break;
923 }
924 }
925
926 // The common case.
927 if (DeclsInContainer.empty())
928 return VisitDeclContext(D);
929
930 // Get all the Decls in the DeclContext, and sort them with the
931 // additional ones we've collected. Then visit them.
932 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
933 I!=E; ++I) {
934 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000935 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
936 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000937 continue;
938 DeclsInContainer.push_back(subDecl);
939 }
940
941 // Now sort the Decls so that they appear in lexical order.
942 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
943 ContainerDeclsSort(SM));
944
945 // Now visit the decls.
946 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
947 E = DeclsInContainer.end(); I != E; ++I) {
948 CXCursor Cursor = MakeCXCursor(*I, TU);
949 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
950 if (!V.hasValue())
951 continue;
952 if (!V.getValue())
953 return false;
954 if (Visit(Cursor, true))
955 return true;
956 }
957 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000958}
959
Douglas Gregorb1373d02010-01-20 20:59:29 +0000960bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000961 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
962 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000963 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000964
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000965 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
966 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
967 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000968 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000969 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000970
Douglas Gregora59e3902010-01-21 23:27:09 +0000971 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000972}
973
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000974bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
975 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
976 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
977 E = PID->protocol_end(); I != E; ++I, ++PL)
978 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
979 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000980
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000981 return VisitObjCContainerDecl(PID);
982}
983
Ted Kremenek23173d72010-05-18 21:09:07 +0000984bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000985 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000986 return true;
987
Ted Kremenek23173d72010-05-18 21:09:07 +0000988 // FIXME: This implements a workaround with @property declarations also being
989 // installed in the DeclContext for the @interface. Eventually this code
990 // should be removed.
991 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
992 if (!CDecl || !CDecl->IsClassExtension())
993 return false;
994
995 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
996 if (!ID)
997 return false;
998
999 IdentifierInfo *PropertyId = PD->getIdentifier();
1000 ObjCPropertyDecl *prevDecl =
1001 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1002
1003 if (!prevDecl)
1004 return false;
1005
1006 // Visit synthesized methods since they will be skipped when visiting
1007 // the @interface.
1008 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001009 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001010 if (Visit(MakeCXCursor(MD, TU)))
1011 return true;
1012
1013 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001014 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001015 if (Visit(MakeCXCursor(MD, TU)))
1016 return true;
1017
1018 return false;
1019}
1020
Douglas Gregorb1373d02010-01-20 20:59:29 +00001021bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001022 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001023 if (D->getSuperClass() &&
1024 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001026 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001027 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001029 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1030 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1031 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001032 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregora59e3902010-01-21 23:27:09 +00001035 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001036}
1037
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001038bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1039 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001040}
1041
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001043 // 'ID' could be null when dealing with invalid code.
1044 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1045 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1046 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001048 return VisitObjCImplDecl(D);
1049}
1050
1051bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1052#if 0
1053 // Issue callbacks for super class.
1054 // FIXME: No source location information!
1055 if (D->getSuperClass() &&
1056 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001057 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001058 TU)))
1059 return true;
1060#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062 return VisitObjCImplDecl(D);
1063}
1064
1065bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1066 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1067 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1068 E = D->protocol_end();
1069 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001070 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001071 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001072
1073 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001074}
1075
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001076bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1077 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1078 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1079 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001080
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001081 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001082}
1083
Douglas Gregora4ffd852010-11-17 01:03:52 +00001084bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1085 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1086 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1087
1088 return false;
1089}
1090
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001091bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1092 return VisitDeclContext(D);
1093}
1094
Douglas Gregor69319002010-08-31 23:48:11 +00001095bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001097 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1098 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001099 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001100
1101 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1102 D->getTargetNameLoc(), TU));
1103}
1104
Douglas Gregor7e242562010-09-01 19:52:22 +00001105bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001107 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1108 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001109 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001110 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001111
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001112 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1113 return true;
1114
Douglas Gregor7e242562010-09-01 19:52:22 +00001115 return VisitDeclarationNameInfo(D->getNameInfo());
1116}
1117
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001118bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001120 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1121 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001122 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001123
1124 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1125 D->getIdentLocation(), TU));
1126}
1127
Douglas Gregor7e242562010-09-01 19:52:22 +00001128bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *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;
Douglas Gregordc355712011-02-25 00:36:19 +00001133 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001134
Douglas Gregor7e242562010-09-01 19:52:22 +00001135 return VisitDeclarationNameInfo(D->getNameInfo());
1136}
1137
1138bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1139 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001140 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001141 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1142 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001143 return true;
1144
Douglas Gregor7e242562010-09-01 19:52:22 +00001145 return false;
1146}
1147
Douglas Gregor01829d32010-08-31 14:41:23 +00001148bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1149 switch (Name.getName().getNameKind()) {
1150 case clang::DeclarationName::Identifier:
1151 case clang::DeclarationName::CXXLiteralOperatorName:
1152 case clang::DeclarationName::CXXOperatorName:
1153 case clang::DeclarationName::CXXUsingDirective:
1154 return false;
1155
1156 case clang::DeclarationName::CXXConstructorName:
1157 case clang::DeclarationName::CXXDestructorName:
1158 case clang::DeclarationName::CXXConversionFunctionName:
1159 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1160 return Visit(TSInfo->getTypeLoc());
1161 return false;
1162
1163 case clang::DeclarationName::ObjCZeroArgSelector:
1164 case clang::DeclarationName::ObjCOneArgSelector:
1165 case clang::DeclarationName::ObjCMultiArgSelector:
1166 // FIXME: Per-identifier location info?
1167 return false;
1168 }
1169
1170 return false;
1171}
1172
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001173bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1174 SourceRange Range) {
1175 // FIXME: This whole routine is a hack to work around the lack of proper
1176 // source information in nested-name-specifiers (PR5791). Since we do have
1177 // a beginning source location, we can visit the first component of the
1178 // nested-name-specifier, if it's a single-token component.
1179 if (!NNS)
1180 return false;
1181
1182 // Get the first component in the nested-name-specifier.
1183 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1184 NNS = Prefix;
1185
1186 switch (NNS->getKind()) {
1187 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001188 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1189 TU));
1190
Douglas Gregor14aba762011-02-24 02:36:08 +00001191 case NestedNameSpecifier::NamespaceAlias:
1192 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1193 Range.getBegin(), TU));
1194
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001195 case NestedNameSpecifier::TypeSpec: {
1196 // If the type has a form where we know that the beginning of the source
1197 // range matches up with a reference cursor. Visit the appropriate reference
1198 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001199 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001200 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1201 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1202 if (const TagType *Tag = dyn_cast<TagType>(T))
1203 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1204 if (const TemplateSpecializationType *TST
1205 = dyn_cast<TemplateSpecializationType>(T))
1206 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1207 break;
1208 }
1209
1210 case NestedNameSpecifier::TypeSpecWithTemplate:
1211 case NestedNameSpecifier::Global:
1212 case NestedNameSpecifier::Identifier:
1213 break;
1214 }
1215
1216 return false;
1217}
1218
Douglas Gregordc355712011-02-25 00:36:19 +00001219bool
1220CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1221 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1222 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1223 Qualifiers.push_back(Qualifier);
1224
1225 while (!Qualifiers.empty()) {
1226 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1227 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1228 switch (NNS->getKind()) {
1229 case NestedNameSpecifier::Namespace:
1230 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001231 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001232 TU)))
1233 return true;
1234
1235 break;
1236
1237 case NestedNameSpecifier::NamespaceAlias:
1238 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001239 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001240 TU)))
1241 return true;
1242
1243 break;
1244
1245 case NestedNameSpecifier::TypeSpec:
1246 case NestedNameSpecifier::TypeSpecWithTemplate:
1247 if (Visit(Q.getTypeLoc()))
1248 return true;
1249
1250 break;
1251
1252 case NestedNameSpecifier::Global:
1253 case NestedNameSpecifier::Identifier:
1254 break;
1255 }
1256 }
1257
1258 return false;
1259}
1260
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001261bool CursorVisitor::VisitTemplateParameters(
1262 const TemplateParameterList *Params) {
1263 if (!Params)
1264 return false;
1265
1266 for (TemplateParameterList::const_iterator P = Params->begin(),
1267 PEnd = Params->end();
1268 P != PEnd; ++P) {
1269 if (Visit(MakeCXCursor(*P, TU)))
1270 return true;
1271 }
1272
1273 return false;
1274}
1275
Douglas Gregor0b36e612010-08-31 20:37:03 +00001276bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1277 switch (Name.getKind()) {
1278 case TemplateName::Template:
1279 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1280
1281 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001282 // Visit the overloaded template set.
1283 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1284 return true;
1285
Douglas Gregor0b36e612010-08-31 20:37:03 +00001286 return false;
1287
1288 case TemplateName::DependentTemplate:
1289 // FIXME: Visit nested-name-specifier.
1290 return false;
1291
1292 case TemplateName::QualifiedTemplate:
1293 // FIXME: Visit nested-name-specifier.
1294 return Visit(MakeCursorTemplateRef(
1295 Name.getAsQualifiedTemplateName()->getDecl(),
1296 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001297
1298 case TemplateName::SubstTemplateTemplateParmPack:
1299 return Visit(MakeCursorTemplateRef(
1300 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1301 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001302 }
1303
1304 return false;
1305}
1306
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001307bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1308 switch (TAL.getArgument().getKind()) {
1309 case TemplateArgument::Null:
1310 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001311 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001312 return false;
1313
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001314 case TemplateArgument::Type:
1315 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1316 return Visit(TSInfo->getTypeLoc());
1317 return false;
1318
1319 case TemplateArgument::Declaration:
1320 if (Expr *E = TAL.getSourceDeclExpression())
1321 return Visit(MakeCXCursor(E, StmtParent, TU));
1322 return false;
1323
1324 case TemplateArgument::Expression:
1325 if (Expr *E = TAL.getSourceExpression())
1326 return Visit(MakeCXCursor(E, StmtParent, TU));
1327 return false;
1328
1329 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001330 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001331 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1332 return true;
1333
Douglas Gregora7fc9012011-01-05 18:58:31 +00001334 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001335 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001336 }
1337
1338 return false;
1339}
1340
Ted Kremeneka0536d82010-05-07 01:04:29 +00001341bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1342 return VisitDeclContext(D);
1343}
1344
Douglas Gregor01829d32010-08-31 14:41:23 +00001345bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1346 return Visit(TL.getUnqualifiedLoc());
1347}
1348
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001349bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001350 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001351
1352 // Some builtin types (such as Objective-C's "id", "sel", and
1353 // "Class") have associated declarations. Create cursors for those.
1354 QualType VisitType;
1355 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001356 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001357 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001358 case BuiltinType::Char_U:
1359 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001360 case BuiltinType::Char16:
1361 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001362 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001363 case BuiltinType::UInt:
1364 case BuiltinType::ULong:
1365 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001366 case BuiltinType::UInt128:
1367 case BuiltinType::Char_S:
1368 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001369 case BuiltinType::WChar_U:
1370 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001371 case BuiltinType::Short:
1372 case BuiltinType::Int:
1373 case BuiltinType::Long:
1374 case BuiltinType::LongLong:
1375 case BuiltinType::Int128:
1376 case BuiltinType::Float:
1377 case BuiltinType::Double:
1378 case BuiltinType::LongDouble:
1379 case BuiltinType::NullPtr:
1380 case BuiltinType::Overload:
1381 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001382 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001383
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001384 case BuiltinType::ObjCId:
1385 VisitType = Context.getObjCIdType();
1386 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001387
1388 case BuiltinType::ObjCClass:
1389 VisitType = Context.getObjCClassType();
1390 break;
1391
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392 case BuiltinType::ObjCSel:
1393 VisitType = Context.getObjCSelType();
1394 break;
1395 }
1396
1397 if (!VisitType.isNull()) {
1398 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001399 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001400 TU));
1401 }
1402
1403 return false;
1404}
1405
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001406bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1407 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1408}
1409
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001410bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1411 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1412}
1413
1414bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1415 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1416}
1417
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001418bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001419 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001420 // no context information with which we can match up the depth/index in the
1421 // type to the appropriate
1422 return false;
1423}
1424
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001425bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1426 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1427 return true;
1428
John McCallc12c5bb2010-05-15 11:32:37 +00001429 return false;
1430}
1431
1432bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1433 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1434 return true;
1435
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001436 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1437 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1438 TU)))
1439 return true;
1440 }
1441
1442 return false;
1443}
1444
1445bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001446 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001447}
1448
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001449bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1450 return Visit(TL.getInnerLoc());
1451}
1452
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001453bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1454 return Visit(TL.getPointeeLoc());
1455}
1456
1457bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1458 return Visit(TL.getPointeeLoc());
1459}
1460
1461bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1462 return Visit(TL.getPointeeLoc());
1463}
1464
1465bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001466 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001467}
1468
1469bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001470 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001471}
1472
Douglas Gregor01829d32010-08-31 14:41:23 +00001473bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1474 bool SkipResultType) {
1475 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001476 return true;
1477
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001478 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001479 if (Decl *D = TL.getArg(I))
1480 if (Visit(MakeCXCursor(D, TU)))
1481 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001482
1483 return false;
1484}
1485
1486bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1487 if (Visit(TL.getElementLoc()))
1488 return true;
1489
1490 if (Expr *Size = TL.getSizeExpr())
1491 return Visit(MakeCXCursor(Size, StmtParent, TU));
1492
1493 return false;
1494}
1495
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001496bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1497 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001498 // Visit the template name.
1499 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1500 TL.getTemplateNameLoc()))
1501 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001502
1503 // Visit the template arguments.
1504 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1505 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1506 return true;
1507
1508 return false;
1509}
1510
Douglas Gregor2332c112010-01-21 20:48:56 +00001511bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1512 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1513}
1514
1515bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1516 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1517 return Visit(TSInfo->getTypeLoc());
1518
1519 return false;
1520}
1521
Douglas Gregor2494dd02011-03-01 01:34:45 +00001522bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1523 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1524 return true;
1525
1526 return false;
1527}
1528
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001529bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1530 DependentTemplateSpecializationTypeLoc TL) {
1531 // Visit the nested-name-specifier, if there is one.
1532 if (TL.getQualifierLoc() &&
1533 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1534 return true;
1535
1536 // Visit the template arguments.
1537 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1538 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1539 return true;
1540
1541 return false;
1542}
1543
Douglas Gregor9e876872011-03-01 18:12:44 +00001544bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1545 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1546 return true;
1547
1548 return Visit(TL.getNamedTypeLoc());
1549}
1550
Douglas Gregor7536dd52010-12-20 02:24:11 +00001551bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1552 return Visit(TL.getPatternLoc());
1553}
1554
Ted Kremenek3064ef92010-08-27 21:34:58 +00001555bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001556 // Visit the nested-name-specifier, if present.
1557 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1558 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1559 return true;
1560
Ted Kremenek3064ef92010-08-27 21:34:58 +00001561 if (D->isDefinition()) {
1562 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1563 E = D->bases_end(); I != E; ++I) {
1564 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1565 return true;
1566 }
1567 }
1568
1569 return VisitTagDecl(D);
1570}
1571
Ted Kremenek09dfa372010-02-18 05:46:33 +00001572bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001573 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1574 i != e; ++i)
1575 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001576 return true;
1577
1578 return false;
1579}
1580
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001581//===----------------------------------------------------------------------===//
1582// Data-recursive visitor methods.
1583//===----------------------------------------------------------------------===//
1584
Ted Kremenek28a71942010-11-13 00:36:47 +00001585namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001586#define DEF_JOB(NAME, DATA, KIND)\
1587class NAME : public VisitorJob {\
1588public:\
1589 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1590 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001591 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001592};
1593
1594DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1595DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001596DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001597DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001598DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1599 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001600DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001601#undef DEF_JOB
1602
1603class DeclVisit : public VisitorJob {
1604public:
1605 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1606 VisitorJob(parent, VisitorJob::DeclVisitKind,
1607 d, isFirst ? (void*) 1 : (void*) 0) {}
1608 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001609 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001610 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001611 Decl *get() const { return static_cast<Decl*>(data[0]); }
1612 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001613};
Ted Kremenek035dc412010-11-13 00:36:50 +00001614class TypeLocVisit : public VisitorJob {
1615public:
1616 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1617 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1618 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1619
1620 static bool classof(const VisitorJob *VJ) {
1621 return VJ->getKind() == TypeLocVisitKind;
1622 }
1623
Ted Kremenek82f3c502010-11-15 22:23:26 +00001624 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001625 QualType T = QualType::getFromOpaquePtr(data[0]);
1626 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001627 }
1628};
1629
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001630class LabelRefVisit : public VisitorJob {
1631public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001632 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1633 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001634 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001635
1636 static bool classof(const VisitorJob *VJ) {
1637 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1638 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001639 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001640 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001641 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001642};
1643class NestedNameSpecifierVisit : public VisitorJob {
1644public:
1645 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1646 CXCursor parent)
1647 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001648 NS, R.getBegin().getPtrEncoding(),
1649 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001650 static bool classof(const VisitorJob *VJ) {
1651 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1652 }
1653 NestedNameSpecifier *get() const {
1654 return static_cast<NestedNameSpecifier*>(data[0]);
1655 }
1656 SourceRange getSourceRange() const {
1657 SourceLocation A =
1658 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1659 SourceLocation B =
1660 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1661 return SourceRange(A, B);
1662 }
1663};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001664
1665class NestedNameSpecifierLocVisit : public VisitorJob {
1666public:
1667 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1668 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1669 Qualifier.getNestedNameSpecifier(),
1670 Qualifier.getOpaqueData()) { }
1671
1672 static bool classof(const VisitorJob *VJ) {
1673 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1674 }
1675
1676 NestedNameSpecifierLoc get() const {
1677 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1678 data[1]);
1679 }
1680};
1681
Ted Kremenekf64d8032010-11-18 00:02:32 +00001682class DeclarationNameInfoVisit : public VisitorJob {
1683public:
1684 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1685 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1686 static bool classof(const VisitorJob *VJ) {
1687 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1688 }
1689 DeclarationNameInfo get() const {
1690 Stmt *S = static_cast<Stmt*>(data[0]);
1691 switch (S->getStmtClass()) {
1692 default:
1693 llvm_unreachable("Unhandled Stmt");
1694 case Stmt::CXXDependentScopeMemberExprClass:
1695 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1696 case Stmt::DependentScopeDeclRefExprClass:
1697 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1698 }
1699 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001700};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001701class MemberRefVisit : public VisitorJob {
1702public:
1703 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1704 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001705 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001706 static bool classof(const VisitorJob *VJ) {
1707 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1708 }
1709 FieldDecl *get() const {
1710 return static_cast<FieldDecl*>(data[0]);
1711 }
1712 SourceLocation getLoc() const {
1713 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1714 }
1715};
Ted Kremenek28a71942010-11-13 00:36:47 +00001716class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1717 VisitorWorkList &WL;
1718 CXCursor Parent;
1719public:
1720 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1721 : WL(wl), Parent(parent) {}
1722
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001723 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001724 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001725 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001726 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001727 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001728 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001729 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001730 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001731 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001732 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001733 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001734 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001735 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001736 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001737 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001738 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001739 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001740 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001741 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1742 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001743 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001744 void VisitIfStmt(IfStmt *If);
1745 void VisitInitListExpr(InitListExpr *IE);
1746 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001747 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001748 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001749 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1750 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001751 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001752 void VisitStmt(Stmt *S);
1753 void VisitSwitchStmt(SwitchStmt *S);
1754 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001755 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001756 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001757 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001758 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001759 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001760
Ted Kremenek28a71942010-11-13 00:36:47 +00001761private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001762 void AddDeclarationNameInfo(Stmt *S);
1763 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001764 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001765 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001766 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001767 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001768 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001769 void AddTypeLoc(TypeSourceInfo *TI);
1770 void EnqueueChildren(Stmt *S);
1771};
1772} // end anonyous namespace
1773
Ted Kremenekf64d8032010-11-18 00:02:32 +00001774void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1775 // 'S' should always be non-null, since it comes from the
1776 // statement we are visiting.
1777 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1778}
1779void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1780 SourceRange R) {
1781 if (N)
1782 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1783}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001784
1785void
1786EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1787 if (Qualifier)
1788 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1789}
1790
Ted Kremenek28a71942010-11-13 00:36:47 +00001791void EnqueueVisitor::AddStmt(Stmt *S) {
1792 if (S)
1793 WL.push_back(StmtVisit(S, Parent));
1794}
Ted Kremenek035dc412010-11-13 00:36:50 +00001795void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001796 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001797 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001798}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001799void EnqueueVisitor::
1800 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1801 if (A)
1802 WL.push_back(ExplicitTemplateArgsVisit(
1803 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1804}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001805void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1806 if (D)
1807 WL.push_back(MemberRefVisit(D, L, Parent));
1808}
Ted Kremenek28a71942010-11-13 00:36:47 +00001809void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1810 if (TI)
1811 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1812 }
1813void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001814 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001815 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001816 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001817 }
1818 if (size == WL.size())
1819 return;
1820 // Now reverse the entries we just added. This will match the DFS
1821 // ordering performed by the worklist.
1822 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1823 std::reverse(I, E);
1824}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001825void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1826 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1827}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001828void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1829 AddDecl(B->getBlockDecl());
1830}
Ted Kremenek28a71942010-11-13 00:36:47 +00001831void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1832 EnqueueChildren(E);
1833 AddTypeLoc(E->getTypeSourceInfo());
1834}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001835void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1836 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1837 E = S->body_rend(); I != E; ++I) {
1838 AddStmt(*I);
1839 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001840}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001841void EnqueueVisitor::
1842VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1843 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1844 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001845 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1846 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001847 if (!E->isImplicitAccess())
1848 AddStmt(E->getBase());
1849}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001850void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1851 // Enqueue the initializer or constructor arguments.
1852 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1853 AddStmt(E->getConstructorArg(I-1));
1854 // Enqueue the array size, if any.
1855 AddStmt(E->getArraySize());
1856 // Enqueue the allocated type.
1857 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1858 // Enqueue the placement arguments.
1859 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1860 AddStmt(E->getPlacementArg(I-1));
1861}
Ted Kremenek28a71942010-11-13 00:36:47 +00001862void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001863 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1864 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001865 AddStmt(CE->getCallee());
1866 AddStmt(CE->getArg(0));
1867}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001868void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1869 // Visit the name of the type being destroyed.
1870 AddTypeLoc(E->getDestroyedTypeInfo());
1871 // Visit the scope type that looks disturbingly like the nested-name-specifier
1872 // but isn't.
1873 AddTypeLoc(E->getScopeTypeInfo());
1874 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001875 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1876 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001877 // Visit base expression.
1878 AddStmt(E->getBase());
1879}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001880void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1881 AddTypeLoc(E->getTypeSourceInfo());
1882}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001883void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1884 EnqueueChildren(E);
1885 AddTypeLoc(E->getTypeSourceInfo());
1886}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001887void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1888 EnqueueChildren(E);
1889 if (E->isTypeOperand())
1890 AddTypeLoc(E->getTypeOperandSourceInfo());
1891}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001892
1893void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1894 *E) {
1895 EnqueueChildren(E);
1896 AddTypeLoc(E->getTypeSourceInfo());
1897}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001898void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1899 EnqueueChildren(E);
1900 if (E->isTypeOperand())
1901 AddTypeLoc(E->getTypeOperandSourceInfo());
1902}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001903void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001904 if (DR->hasExplicitTemplateArgs()) {
1905 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1906 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001907 WL.push_back(DeclRefExprParts(DR, Parent));
1908}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001909void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1910 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1911 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001912 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001913}
Ted Kremenek035dc412010-11-13 00:36:50 +00001914void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1915 unsigned size = WL.size();
1916 bool isFirst = true;
1917 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1918 D != DEnd; ++D) {
1919 AddDecl(*D, isFirst);
1920 isFirst = false;
1921 }
1922 if (size == WL.size())
1923 return;
1924 // Now reverse the entries we just added. This will match the DFS
1925 // ordering performed by the worklist.
1926 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1927 std::reverse(I, E);
1928}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001929void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1930 AddStmt(E->getInit());
1931 typedef DesignatedInitExpr::Designator Designator;
1932 for (DesignatedInitExpr::reverse_designators_iterator
1933 D = E->designators_rbegin(), DEnd = E->designators_rend();
1934 D != DEnd; ++D) {
1935 if (D->isFieldDesignator()) {
1936 if (FieldDecl *Field = D->getField())
1937 AddMemberRef(Field, D->getFieldLoc());
1938 continue;
1939 }
1940 if (D->isArrayDesignator()) {
1941 AddStmt(E->getArrayIndex(*D));
1942 continue;
1943 }
1944 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1945 AddStmt(E->getArrayRangeEnd(*D));
1946 AddStmt(E->getArrayRangeStart(*D));
1947 }
1948}
Ted Kremenek28a71942010-11-13 00:36:47 +00001949void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1950 EnqueueChildren(E);
1951 AddTypeLoc(E->getTypeInfoAsWritten());
1952}
1953void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1954 AddStmt(FS->getBody());
1955 AddStmt(FS->getInc());
1956 AddStmt(FS->getCond());
1957 AddDecl(FS->getConditionVariable());
1958 AddStmt(FS->getInit());
1959}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001960void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1961 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1962}
Ted Kremenek28a71942010-11-13 00:36:47 +00001963void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1964 AddStmt(If->getElse());
1965 AddStmt(If->getThen());
1966 AddStmt(If->getCond());
1967 AddDecl(If->getConditionVariable());
1968}
1969void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1970 // We care about the syntactic form of the initializer list, only.
1971 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1972 IE = Syntactic;
1973 EnqueueChildren(IE);
1974}
1975void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001976 WL.push_back(MemberExprParts(M, Parent));
1977
1978 // If the base of the member access expression is an implicit 'this', don't
1979 // visit it.
1980 // FIXME: If we ever want to show these implicit accesses, this will be
1981 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001982 if (!M->isImplicitAccess())
1983 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001984}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001985void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1986 AddTypeLoc(E->getEncodedTypeSourceInfo());
1987}
Ted Kremenek28a71942010-11-13 00:36:47 +00001988void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1989 EnqueueChildren(M);
1990 AddTypeLoc(M->getClassReceiverTypeInfo());
1991}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001992void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1993 // Visit the components of the offsetof expression.
1994 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1995 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1996 const OffsetOfNode &Node = E->getComponent(I-1);
1997 switch (Node.getKind()) {
1998 case OffsetOfNode::Array:
1999 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2000 break;
2001 case OffsetOfNode::Field:
2002 AddMemberRef(Node.getField(), Node.getRange().getEnd());
2003 break;
2004 case OffsetOfNode::Identifier:
2005 case OffsetOfNode::Base:
2006 continue;
2007 }
2008 }
2009 // Visit the type into which we're computing the offset.
2010 AddTypeLoc(E->getTypeSourceInfo());
2011}
Ted Kremenek28a71942010-11-13 00:36:47 +00002012void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002013 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002014 WL.push_back(OverloadExprParts(E, Parent));
2015}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002016void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
2017 EnqueueChildren(E);
2018 if (E->isArgumentType())
2019 AddTypeLoc(E->getArgumentTypeInfo());
2020}
Ted Kremenek28a71942010-11-13 00:36:47 +00002021void EnqueueVisitor::VisitStmt(Stmt *S) {
2022 EnqueueChildren(S);
2023}
2024void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2025 AddStmt(S->getBody());
2026 AddStmt(S->getCond());
2027 AddDecl(S->getConditionVariable());
2028}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002029
Ted Kremenek28a71942010-11-13 00:36:47 +00002030void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2031 AddStmt(W->getBody());
2032 AddStmt(W->getCond());
2033 AddDecl(W->getConditionVariable());
2034}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002035void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2036 AddTypeLoc(E->getQueriedTypeSourceInfo());
2037}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002038
2039void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002040 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002041 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002042}
2043
Ted Kremenek28a71942010-11-13 00:36:47 +00002044void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2045 VisitOverloadExpr(U);
2046 if (!U->isImplicitAccess())
2047 AddStmt(U->getBase());
2048}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002049void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2050 AddStmt(E->getSubExpr());
2051 AddTypeLoc(E->getWrittenTypeInfo());
2052}
Douglas Gregor94d96292011-01-19 20:34:17 +00002053void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2054 WL.push_back(SizeOfPackExprParts(E, Parent));
2055}
Ted Kremenek60458782010-11-12 21:34:16 +00002056
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002057void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002058 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002059}
2060
2061bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2062 if (RegionOfInterest.isValid()) {
2063 SourceRange Range = getRawCursorExtent(C);
2064 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2065 return false;
2066 }
2067 return true;
2068}
2069
2070bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2071 while (!WL.empty()) {
2072 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002073 VisitorJob LI = WL.back();
2074 WL.pop_back();
2075
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002076 // Set the Parent field, then back to its old value once we're done.
2077 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2078
2079 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002080 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002081 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002082 if (!D)
2083 continue;
2084
2085 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002086 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002087 return true;
2088
2089 continue;
2090 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002091 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2092 const ExplicitTemplateArgumentList *ArgList =
2093 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2094 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2095 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2096 Arg != ArgEnd; ++Arg) {
2097 if (VisitTemplateArgumentLoc(*Arg))
2098 return true;
2099 }
2100 continue;
2101 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002102 case VisitorJob::TypeLocVisitKind: {
2103 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002104 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002105 return true;
2106 continue;
2107 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002108 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002109 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002110 if (LabelStmt *stmt = LS->getStmt()) {
2111 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2112 TU))) {
2113 return true;
2114 }
2115 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002116 continue;
2117 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002118
Ted Kremenekf64d8032010-11-18 00:02:32 +00002119 case VisitorJob::NestedNameSpecifierVisitKind: {
2120 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2121 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2122 return true;
2123 continue;
2124 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002125
2126 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2127 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2128 if (VisitNestedNameSpecifierLoc(V->get()))
2129 return true;
2130 continue;
2131 }
2132
Ted Kremenekf64d8032010-11-18 00:02:32 +00002133 case VisitorJob::DeclarationNameInfoVisitKind: {
2134 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2135 ->get()))
2136 return true;
2137 continue;
2138 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002139 case VisitorJob::MemberRefVisitKind: {
2140 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2141 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2142 return true;
2143 continue;
2144 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002145 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002146 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002147 if (!S)
2148 continue;
2149
Ted Kremenekf1107452010-11-12 18:26:56 +00002150 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002151 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002152 if (!IsInRegionOfInterest(Cursor))
2153 continue;
2154 switch (Visitor(Cursor, Parent, ClientData)) {
2155 case CXChildVisit_Break: return true;
2156 case CXChildVisit_Continue: break;
2157 case CXChildVisit_Recurse:
2158 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002159 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002160 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002161 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002162 }
2163 case VisitorJob::MemberExprPartsKind: {
2164 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002165 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002166
2167 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002168 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2169 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002170 return true;
2171
2172 // Visit the declaration name.
2173 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2174 return true;
2175
2176 // Visit the explicitly-specified template arguments, if any.
2177 if (M->hasExplicitTemplateArgs()) {
2178 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2179 *ArgEnd = Arg + M->getNumTemplateArgs();
2180 Arg != ArgEnd; ++Arg) {
2181 if (VisitTemplateArgumentLoc(*Arg))
2182 return true;
2183 }
2184 }
2185 continue;
2186 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002187 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002188 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002189 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002190 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2191 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002192 return true;
2193 // Visit declaration name.
2194 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2195 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002196 continue;
2197 }
Ted Kremenek60458782010-11-12 21:34:16 +00002198 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002199 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002200 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002201 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2202 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002203 return true;
2204 // Visit the declaration name.
2205 if (VisitDeclarationNameInfo(O->getNameInfo()))
2206 return true;
2207 // Visit the overloaded declaration reference.
2208 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2209 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002210 continue;
2211 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002212 case VisitorJob::SizeOfPackExprPartsKind: {
2213 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2214 NamedDecl *Pack = E->getPack();
2215 if (isa<TemplateTypeParmDecl>(Pack)) {
2216 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2217 E->getPackLoc(), TU)))
2218 return true;
2219
2220 continue;
2221 }
2222
2223 if (isa<TemplateTemplateParmDecl>(Pack)) {
2224 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2225 E->getPackLoc(), TU)))
2226 return true;
2227
2228 continue;
2229 }
2230
2231 // Non-type template parameter packs and function parameter packs are
2232 // treated like DeclRefExpr cursors.
2233 continue;
2234 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002235 }
2236 }
2237 return false;
2238}
2239
Ted Kremenekcdba6592010-11-18 00:42:18 +00002240bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002241 VisitorWorkList *WL = 0;
2242 if (!WorkListFreeList.empty()) {
2243 WL = WorkListFreeList.back();
2244 WL->clear();
2245 WorkListFreeList.pop_back();
2246 }
2247 else {
2248 WL = new VisitorWorkList();
2249 WorkListCache.push_back(WL);
2250 }
2251 EnqueueWorkList(*WL, S);
2252 bool result = RunVisitorWorkList(*WL);
2253 WorkListFreeList.push_back(WL);
2254 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002255}
2256
2257//===----------------------------------------------------------------------===//
2258// Misc. API hooks.
2259//===----------------------------------------------------------------------===//
2260
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002261static llvm::sys::Mutex EnableMultithreadingMutex;
2262static bool EnabledMultithreading;
2263
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002264extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002265CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2266 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002267 // Disable pretty stack trace functionality, which will otherwise be a very
2268 // poor citizen of the world and set up all sorts of signal handlers.
2269 llvm::DisablePrettyStackTrace = true;
2270
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002271 // We use crash recovery to make some of our APIs more reliable, implicitly
2272 // enable it.
2273 llvm::CrashRecoveryContext::Enable();
2274
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002275 // Enable support for multithreading in LLVM.
2276 {
2277 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2278 if (!EnabledMultithreading) {
2279 llvm::llvm_start_multithreaded();
2280 EnabledMultithreading = true;
2281 }
2282 }
2283
Douglas Gregora030b7c2010-01-22 20:35:53 +00002284 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002285 if (excludeDeclarationsFromPCH)
2286 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002287 if (displayDiagnostics)
2288 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002289 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002290}
2291
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002292void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002293 if (CIdx)
2294 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002295}
2296
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002297CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002298 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002299 if (!CIdx)
2300 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002301
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002302 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002303 FileSystemOptions FileSystemOpts;
2304 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002305
Douglas Gregor28019772010-04-05 23:52:57 +00002306 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002307 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002308 CXXIdx->getOnlyLocalDecls(),
2309 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002310 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002311}
2312
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002313unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002314 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002315 CXTranslationUnit_CacheCompletionResults |
2316 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002317}
2318
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002319CXTranslationUnit
2320clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2321 const char *source_filename,
2322 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002323 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002324 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002325 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002326 return clang_parseTranslationUnit(CIdx, source_filename,
2327 command_line_args, num_command_line_args,
2328 unsaved_files, num_unsaved_files,
2329 CXTranslationUnit_DetailedPreprocessingRecord);
2330}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002331
2332struct ParseTranslationUnitInfo {
2333 CXIndex CIdx;
2334 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002335 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002336 int num_command_line_args;
2337 struct CXUnsavedFile *unsaved_files;
2338 unsigned num_unsaved_files;
2339 unsigned options;
2340 CXTranslationUnit result;
2341};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002342static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002343 ParseTranslationUnitInfo *PTUI =
2344 static_cast<ParseTranslationUnitInfo*>(UserData);
2345 CXIndex CIdx = PTUI->CIdx;
2346 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002347 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002348 int num_command_line_args = PTUI->num_command_line_args;
2349 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2350 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2351 unsigned options = PTUI->options;
2352 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002353
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002354 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002355 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002356
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002357 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2358
Douglas Gregor44c181a2010-07-23 00:33:23 +00002359 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002360 bool CompleteTranslationUnit
2361 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002362 bool CacheCodeCompetionResults
2363 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002364 bool CXXPrecompilePreamble
2365 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2366 bool CXXChainedPCH
2367 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002368
Douglas Gregor5352ac02010-01-28 00:27:43 +00002369 // Configure the diagnostics.
2370 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002371 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002372 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2373 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002374
Douglas Gregor4db64a42010-01-23 00:14:00 +00002375 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2376 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002377 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002378 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002379 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002380 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2381 Buffer));
2382 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002383
Douglas Gregorb10daed2010-10-11 16:52:23 +00002384 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002385
Ted Kremenek139ba862009-10-22 00:03:57 +00002386 // The 'source_filename' argument is optional. If the caller does not
2387 // specify it then it is assumed that the source file is specified
2388 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002389 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002390 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002391
2392 // Since the Clang C library is primarily used by batch tools dealing with
2393 // (often very broken) source code, where spell-checking can have a
2394 // significant negative impact on performance (particularly when
2395 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002396 // Only do this if we haven't found a spell-checking-related argument.
2397 bool FoundSpellCheckingArgument = false;
2398 for (int I = 0; I != num_command_line_args; ++I) {
2399 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2400 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2401 FoundSpellCheckingArgument = true;
2402 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002403 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002404 }
2405 if (!FoundSpellCheckingArgument)
2406 Args.push_back("-fno-spell-checking");
2407
2408 Args.insert(Args.end(), command_line_args,
2409 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002410
Douglas Gregor44c181a2010-07-23 00:33:23 +00002411 // Do we need the detailed preprocessing record?
2412 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002413 Args.push_back("-Xclang");
2414 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002415 }
2416
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002417 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002418 llvm::OwningPtr<ASTUnit> Unit(
2419 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2420 Diags,
2421 CXXIdx->getClangResourcesPath(),
2422 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002423 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002424 RemappedFiles.data(),
2425 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002426 PrecompilePreamble,
2427 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002428 CacheCodeCompetionResults,
2429 CXXPrecompilePreamble,
2430 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002431
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002432 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002433 // Make sure to check that 'Unit' is non-NULL.
2434 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2435 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2436 DEnd = Unit->stored_diag_end();
2437 D != DEnd; ++D) {
2438 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2439 CXString Msg = clang_formatDiagnostic(&Diag,
2440 clang_defaultDiagnosticDisplayOptions());
2441 fprintf(stderr, "%s\n", clang_getCString(Msg));
2442 clang_disposeString(Msg);
2443 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002444#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002445 // On Windows, force a flush, since there may be multiple copies of
2446 // stderr and stdout in the file system, all with different buffers
2447 // but writing to the same device.
2448 fflush(stderr);
2449#endif
2450 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002451 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002452
Ted Kremeneka60ed472010-11-16 08:15:36 +00002453 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002454}
2455CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2456 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002457 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002458 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002459 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002460 unsigned num_unsaved_files,
2461 unsigned options) {
2462 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002463 num_command_line_args, unsaved_files,
2464 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002465 llvm::CrashRecoveryContext CRC;
2466
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002467 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002468 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2469 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2470 fprintf(stderr, " 'command_line_args' : [");
2471 for (int i = 0; i != num_command_line_args; ++i) {
2472 if (i)
2473 fprintf(stderr, ", ");
2474 fprintf(stderr, "'%s'", command_line_args[i]);
2475 }
2476 fprintf(stderr, "],\n");
2477 fprintf(stderr, " 'unsaved_files' : [");
2478 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2479 if (i)
2480 fprintf(stderr, ", ");
2481 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2482 unsaved_files[i].Length);
2483 }
2484 fprintf(stderr, "],\n");
2485 fprintf(stderr, " 'options' : %d,\n", options);
2486 fprintf(stderr, "}\n");
2487
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002488 return 0;
2489 }
2490
2491 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002492}
2493
Douglas Gregor19998442010-08-13 15:35:05 +00002494unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2495 return CXSaveTranslationUnit_None;
2496}
2497
2498int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2499 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002500 if (!TU)
2501 return 1;
2502
Ted Kremeneka60ed472010-11-16 08:15:36 +00002503 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002504}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002505
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002506void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002507 if (CTUnit) {
2508 // If the translation unit has been marked as unsafe to free, just discard
2509 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002510 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002511 return;
2512
Ted Kremeneka60ed472010-11-16 08:15:36 +00002513 delete static_cast<ASTUnit *>(CTUnit->TUData);
2514 disposeCXStringPool(CTUnit->StringPool);
2515 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002516 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002517}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002518
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002519unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2520 return CXReparse_None;
2521}
2522
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002523struct ReparseTranslationUnitInfo {
2524 CXTranslationUnit TU;
2525 unsigned num_unsaved_files;
2526 struct CXUnsavedFile *unsaved_files;
2527 unsigned options;
2528 int result;
2529};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002530
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002531static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002532 ReparseTranslationUnitInfo *RTUI =
2533 static_cast<ReparseTranslationUnitInfo*>(UserData);
2534 CXTranslationUnit TU = RTUI->TU;
2535 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2536 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2537 unsigned options = RTUI->options;
2538 (void) options;
2539 RTUI->result = 1;
2540
Douglas Gregorabc563f2010-07-19 21:46:24 +00002541 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002542 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002543
Ted Kremeneka60ed472010-11-16 08:15:36 +00002544 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002545 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002546
2547 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2548 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2549 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2550 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002551 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002552 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2553 Buffer));
2554 }
2555
Douglas Gregor593b0c12010-09-23 18:47:53 +00002556 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2557 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002558}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002559
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002560int clang_reparseTranslationUnit(CXTranslationUnit TU,
2561 unsigned num_unsaved_files,
2562 struct CXUnsavedFile *unsaved_files,
2563 unsigned options) {
2564 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2565 options, 0 };
2566 llvm::CrashRecoveryContext CRC;
2567
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002568 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002569 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002570 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002571 return 1;
2572 }
2573
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002574
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002575 return RTUI.result;
2576}
2577
Douglas Gregordf95a132010-08-09 20:45:32 +00002578
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002579CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002580 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002581 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582
Ted Kremeneka60ed472010-11-16 08:15:36 +00002583 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002584 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002585}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002586
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002587CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002588 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002589 return Result;
2590}
2591
Ted Kremenekfb480492010-01-13 21:46:36 +00002592} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002593
Ted Kremenekfb480492010-01-13 21:46:36 +00002594//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002595// CXSourceLocation and CXSourceRange Operations.
2596//===----------------------------------------------------------------------===//
2597
Douglas Gregorb9790342010-01-22 21:44:22 +00002598extern "C" {
2599CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002600 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002601 return Result;
2602}
2603
2604unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002605 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2606 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2607 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002608}
2609
2610CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2611 CXFile file,
2612 unsigned line,
2613 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002614 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002615 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002616
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002617 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002618 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002619 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002620 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002621 = CXXUnit->getSourceManager().getLocation(File, line, column);
2622 if (SLoc.isInvalid()) {
2623 if (Logging)
2624 llvm::errs() << "clang_getLocation(\"" << File->getName()
2625 << "\", " << line << ", " << column << ") = invalid\n";
2626 return clang_getNullLocation();
2627 }
2628
2629 if (Logging)
2630 llvm::errs() << "clang_getLocation(\"" << File->getName()
2631 << "\", " << line << ", " << column << ") = "
2632 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002633
2634 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2635}
2636
2637CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2638 CXFile file,
2639 unsigned offset) {
2640 if (!tu || !file)
2641 return clang_getNullLocation();
2642
Ted Kremeneka60ed472010-11-16 08:15:36 +00002643 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002644 SourceLocation Start
2645 = CXXUnit->getSourceManager().getLocation(
2646 static_cast<const FileEntry *>(file),
2647 1, 1);
2648 if (Start.isInvalid()) return clang_getNullLocation();
2649
2650 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2651
2652 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002653
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002654 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002655}
2656
Douglas Gregor5352ac02010-01-28 00:27:43 +00002657CXSourceRange clang_getNullRange() {
2658 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2659 return Result;
2660}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002661
Douglas Gregor5352ac02010-01-28 00:27:43 +00002662CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2663 if (begin.ptr_data[0] != end.ptr_data[0] ||
2664 begin.ptr_data[1] != end.ptr_data[1])
2665 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002666
2667 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002668 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002669 return Result;
2670}
2671
Douglas Gregor46766dc2010-01-26 19:19:08 +00002672void clang_getInstantiationLocation(CXSourceLocation location,
2673 CXFile *file,
2674 unsigned *line,
2675 unsigned *column,
2676 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002677 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2678
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002679 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002680 if (file)
2681 *file = 0;
2682 if (line)
2683 *line = 0;
2684 if (column)
2685 *column = 0;
2686 if (offset)
2687 *offset = 0;
2688 return;
2689 }
2690
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002691 const SourceManager &SM =
2692 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002693 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002694
2695 if (file)
2696 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2697 if (line)
2698 *line = SM.getInstantiationLineNumber(InstLoc);
2699 if (column)
2700 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002701 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002702 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002703}
2704
Douglas Gregora9b06d42010-11-09 06:24:54 +00002705void clang_getSpellingLocation(CXSourceLocation location,
2706 CXFile *file,
2707 unsigned *line,
2708 unsigned *column,
2709 unsigned *offset) {
2710 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2711
2712 if (!location.ptr_data[0] || Loc.isInvalid()) {
2713 if (file)
2714 *file = 0;
2715 if (line)
2716 *line = 0;
2717 if (column)
2718 *column = 0;
2719 if (offset)
2720 *offset = 0;
2721 return;
2722 }
2723
2724 const SourceManager &SM =
2725 *static_cast<const SourceManager*>(location.ptr_data[0]);
2726 SourceLocation SpellLoc = Loc;
2727 if (SpellLoc.isMacroID()) {
2728 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2729 if (SimpleSpellingLoc.isFileID() &&
2730 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2731 SpellLoc = SimpleSpellingLoc;
2732 else
2733 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2734 }
2735
2736 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2737 FileID FID = LocInfo.first;
2738 unsigned FileOffset = LocInfo.second;
2739
2740 if (file)
2741 *file = (void *)SM.getFileEntryForID(FID);
2742 if (line)
2743 *line = SM.getLineNumber(FID, FileOffset);
2744 if (column)
2745 *column = SM.getColumnNumber(FID, FileOffset);
2746 if (offset)
2747 *offset = FileOffset;
2748}
2749
Douglas Gregor1db19de2010-01-19 21:36:55 +00002750CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002751 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002752 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002753 return Result;
2754}
2755
2756CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002757 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002758 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002759 return Result;
2760}
2761
Douglas Gregorb9790342010-01-22 21:44:22 +00002762} // end: extern "C"
2763
Douglas Gregor1db19de2010-01-19 21:36:55 +00002764//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002765// CXFile Operations.
2766//===----------------------------------------------------------------------===//
2767
2768extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002769CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002770 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002771 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002772
Steve Naroff88145032009-10-27 14:35:18 +00002773 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002774 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002775}
2776
2777time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002778 if (!SFile)
2779 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002780
Steve Naroff88145032009-10-27 14:35:18 +00002781 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2782 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002783}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002784
Douglas Gregorb9790342010-01-22 21:44:22 +00002785CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2786 if (!tu)
2787 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002788
Ted Kremeneka60ed472010-11-16 08:15:36 +00002789 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002790
Douglas Gregorb9790342010-01-22 21:44:22 +00002791 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002792 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002793}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002794
Ted Kremenekfb480492010-01-13 21:46:36 +00002795} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002796
Ted Kremenekfb480492010-01-13 21:46:36 +00002797//===----------------------------------------------------------------------===//
2798// CXCursor Operations.
2799//===----------------------------------------------------------------------===//
2800
Ted Kremenekfb480492010-01-13 21:46:36 +00002801static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002802 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2803 return getDeclFromExpr(CE->getSubExpr());
2804
Ted Kremenekfb480492010-01-13 21:46:36 +00002805 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2806 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002807 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2808 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002809 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2810 return ME->getMemberDecl();
2811 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2812 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002813 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002814 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002815
Ted Kremenekfb480492010-01-13 21:46:36 +00002816 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2817 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002818 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2819 if (!CE->isElidable())
2820 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002821 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2822 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002823
Douglas Gregordb1314e2010-10-01 21:11:22 +00002824 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2825 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002826 if (SubstNonTypeTemplateParmPackExpr *NTTP
2827 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2828 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002829 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2830 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2831 isa<ParmVarDecl>(SizeOfPack->getPack()))
2832 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002833
Ted Kremenekfb480492010-01-13 21:46:36 +00002834 return 0;
2835}
2836
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002837static SourceLocation getLocationFromExpr(Expr *E) {
2838 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2839 return /*FIXME:*/Msg->getLeftLoc();
2840 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2841 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002842 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2843 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002844 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2845 return Member->getMemberLoc();
2846 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2847 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002848 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2849 return SizeOfPack->getPackLoc();
2850
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002851 return E->getLocStart();
2852}
2853
Ted Kremenekfb480492010-01-13 21:46:36 +00002854extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002855
2856unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002857 CXCursorVisitor visitor,
2858 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002859 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2860 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002861 return CursorVis.VisitChildren(parent);
2862}
2863
David Chisnall3387c652010-11-03 14:12:26 +00002864#ifndef __has_feature
2865#define __has_feature(x) 0
2866#endif
2867#if __has_feature(blocks)
2868typedef enum CXChildVisitResult
2869 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2870
2871static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2872 CXClientData client_data) {
2873 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2874 return block(cursor, parent);
2875}
2876#else
2877// If we are compiled with a compiler that doesn't have native blocks support,
2878// define and call the block manually, so the
2879typedef struct _CXChildVisitResult
2880{
2881 void *isa;
2882 int flags;
2883 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002884 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2885 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002886} *CXCursorVisitorBlock;
2887
2888static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2889 CXClientData client_data) {
2890 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2891 return block->invoke(block, cursor, parent);
2892}
2893#endif
2894
2895
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002896unsigned clang_visitChildrenWithBlock(CXCursor parent,
2897 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002898 return clang_visitChildren(parent, visitWithBlock, block);
2899}
2900
Douglas Gregor78205d42010-01-20 21:45:58 +00002901static CXString getDeclSpelling(Decl *D) {
2902 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002903 if (!ND) {
2904 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2905 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2906 return createCXString(Property->getIdentifier()->getName());
2907
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002908 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002909 }
2910
Douglas Gregor78205d42010-01-20 21:45:58 +00002911 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002912 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002913
Douglas Gregor78205d42010-01-20 21:45:58 +00002914 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2915 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2916 // and returns different names. NamedDecl returns the class name and
2917 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002918 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002919
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002920 if (isa<UsingDirectiveDecl>(D))
2921 return createCXString("");
2922
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002923 llvm::SmallString<1024> S;
2924 llvm::raw_svector_ostream os(S);
2925 ND->printName(os);
2926
2927 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002928}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002929
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002930CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002931 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002932 return clang_getTranslationUnitSpelling(
2933 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002934
Steve Narofff334b4e2009-09-02 18:26:48 +00002935 if (clang_isReference(C.kind)) {
2936 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002937 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002938 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002939 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002940 }
2941 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002942 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002943 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002944 }
2945 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002946 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002947 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002948 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002949 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002950 case CXCursor_CXXBaseSpecifier: {
2951 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2952 return createCXString(B->getType().getAsString());
2953 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002954 case CXCursor_TypeRef: {
2955 TypeDecl *Type = getCursorTypeRef(C).first;
2956 assert(Type && "Missing type decl");
2957
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002958 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2959 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002960 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002961 case CXCursor_TemplateRef: {
2962 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002963 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002964
2965 return createCXString(Template->getNameAsString());
2966 }
Douglas Gregor69319002010-08-31 23:48:11 +00002967
2968 case CXCursor_NamespaceRef: {
2969 NamedDecl *NS = getCursorNamespaceRef(C).first;
2970 assert(NS && "Missing namespace decl");
2971
2972 return createCXString(NS->getNameAsString());
2973 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002974
Douglas Gregora67e03f2010-09-09 21:42:20 +00002975 case CXCursor_MemberRef: {
2976 FieldDecl *Field = getCursorMemberRef(C).first;
2977 assert(Field && "Missing member decl");
2978
2979 return createCXString(Field->getNameAsString());
2980 }
2981
Douglas Gregor36897b02010-09-10 00:22:18 +00002982 case CXCursor_LabelRef: {
2983 LabelStmt *Label = getCursorLabelRef(C).first;
2984 assert(Label && "Missing label");
2985
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002986 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002987 }
2988
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002989 case CXCursor_OverloadedDeclRef: {
2990 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2991 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2992 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2993 return createCXString(ND->getNameAsString());
2994 return createCXString("");
2995 }
2996 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2997 return createCXString(E->getName().getAsString());
2998 OverloadedTemplateStorage *Ovl
2999 = Storage.get<OverloadedTemplateStorage*>();
3000 if (Ovl->size() == 0)
3001 return createCXString("");
3002 return createCXString((*Ovl->begin())->getNameAsString());
3003 }
3004
Daniel Dunbaracca7252009-11-30 20:42:49 +00003005 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003006 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003007 }
3008 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003009
3010 if (clang_isExpression(C.kind)) {
3011 Decl *D = getDeclFromExpr(getCursorExpr(C));
3012 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003013 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003014 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003015 }
3016
Douglas Gregor36897b02010-09-10 00:22:18 +00003017 if (clang_isStatement(C.kind)) {
3018 Stmt *S = getCursorStmt(C);
3019 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003020 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003021
3022 return createCXString("");
3023 }
3024
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003025 if (C.kind == CXCursor_MacroInstantiation)
3026 return createCXString(getCursorMacroInstantiation(C)->getName()
3027 ->getNameStart());
3028
Douglas Gregor572feb22010-03-18 18:04:21 +00003029 if (C.kind == CXCursor_MacroDefinition)
3030 return createCXString(getCursorMacroDefinition(C)->getName()
3031 ->getNameStart());
3032
Douglas Gregorecdcb882010-10-20 22:00:55 +00003033 if (C.kind == CXCursor_InclusionDirective)
3034 return createCXString(getCursorInclusionDirective(C)->getFileName());
3035
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003036 if (clang_isDeclaration(C.kind))
3037 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003038
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003039 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003040}
3041
Douglas Gregor358559d2010-10-02 22:49:11 +00003042CXString clang_getCursorDisplayName(CXCursor C) {
3043 if (!clang_isDeclaration(C.kind))
3044 return clang_getCursorSpelling(C);
3045
3046 Decl *D = getCursorDecl(C);
3047 if (!D)
3048 return createCXString("");
3049
3050 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3051 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3052 D = FunTmpl->getTemplatedDecl();
3053
3054 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3055 llvm::SmallString<64> Str;
3056 llvm::raw_svector_ostream OS(Str);
3057 OS << Function->getNameAsString();
3058 if (Function->getPrimaryTemplate())
3059 OS << "<>";
3060 OS << "(";
3061 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3062 if (I)
3063 OS << ", ";
3064 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3065 }
3066
3067 if (Function->isVariadic()) {
3068 if (Function->getNumParams())
3069 OS << ", ";
3070 OS << "...";
3071 }
3072 OS << ")";
3073 return createCXString(OS.str());
3074 }
3075
3076 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3077 llvm::SmallString<64> Str;
3078 llvm::raw_svector_ostream OS(Str);
3079 OS << ClassTemplate->getNameAsString();
3080 OS << "<";
3081 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3082 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3083 if (I)
3084 OS << ", ";
3085
3086 NamedDecl *Param = Params->getParam(I);
3087 if (Param->getIdentifier()) {
3088 OS << Param->getIdentifier()->getName();
3089 continue;
3090 }
3091
3092 // There is no parameter name, which makes this tricky. Try to come up
3093 // with something useful that isn't too long.
3094 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3095 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3096 else if (NonTypeTemplateParmDecl *NTTP
3097 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3098 OS << NTTP->getType().getAsString(Policy);
3099 else
3100 OS << "template<...> class";
3101 }
3102
3103 OS << ">";
3104 return createCXString(OS.str());
3105 }
3106
3107 if (ClassTemplateSpecializationDecl *ClassSpec
3108 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3109 // If the type was explicitly written, use that.
3110 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3111 return createCXString(TSInfo->getType().getAsString(Policy));
3112
3113 llvm::SmallString<64> Str;
3114 llvm::raw_svector_ostream OS(Str);
3115 OS << ClassSpec->getNameAsString();
3116 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003117 ClassSpec->getTemplateArgs().data(),
3118 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003119 Policy);
3120 return createCXString(OS.str());
3121 }
3122
3123 return clang_getCursorSpelling(C);
3124}
3125
Ted Kremeneke68fff62010-02-17 00:41:32 +00003126CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003127 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003128 case CXCursor_FunctionDecl:
3129 return createCXString("FunctionDecl");
3130 case CXCursor_TypedefDecl:
3131 return createCXString("TypedefDecl");
3132 case CXCursor_EnumDecl:
3133 return createCXString("EnumDecl");
3134 case CXCursor_EnumConstantDecl:
3135 return createCXString("EnumConstantDecl");
3136 case CXCursor_StructDecl:
3137 return createCXString("StructDecl");
3138 case CXCursor_UnionDecl:
3139 return createCXString("UnionDecl");
3140 case CXCursor_ClassDecl:
3141 return createCXString("ClassDecl");
3142 case CXCursor_FieldDecl:
3143 return createCXString("FieldDecl");
3144 case CXCursor_VarDecl:
3145 return createCXString("VarDecl");
3146 case CXCursor_ParmDecl:
3147 return createCXString("ParmDecl");
3148 case CXCursor_ObjCInterfaceDecl:
3149 return createCXString("ObjCInterfaceDecl");
3150 case CXCursor_ObjCCategoryDecl:
3151 return createCXString("ObjCCategoryDecl");
3152 case CXCursor_ObjCProtocolDecl:
3153 return createCXString("ObjCProtocolDecl");
3154 case CXCursor_ObjCPropertyDecl:
3155 return createCXString("ObjCPropertyDecl");
3156 case CXCursor_ObjCIvarDecl:
3157 return createCXString("ObjCIvarDecl");
3158 case CXCursor_ObjCInstanceMethodDecl:
3159 return createCXString("ObjCInstanceMethodDecl");
3160 case CXCursor_ObjCClassMethodDecl:
3161 return createCXString("ObjCClassMethodDecl");
3162 case CXCursor_ObjCImplementationDecl:
3163 return createCXString("ObjCImplementationDecl");
3164 case CXCursor_ObjCCategoryImplDecl:
3165 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003166 case CXCursor_CXXMethod:
3167 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003168 case CXCursor_UnexposedDecl:
3169 return createCXString("UnexposedDecl");
3170 case CXCursor_ObjCSuperClassRef:
3171 return createCXString("ObjCSuperClassRef");
3172 case CXCursor_ObjCProtocolRef:
3173 return createCXString("ObjCProtocolRef");
3174 case CXCursor_ObjCClassRef:
3175 return createCXString("ObjCClassRef");
3176 case CXCursor_TypeRef:
3177 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003178 case CXCursor_TemplateRef:
3179 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003180 case CXCursor_NamespaceRef:
3181 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003182 case CXCursor_MemberRef:
3183 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003184 case CXCursor_LabelRef:
3185 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003186 case CXCursor_OverloadedDeclRef:
3187 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003188 case CXCursor_UnexposedExpr:
3189 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003190 case CXCursor_BlockExpr:
3191 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003192 case CXCursor_DeclRefExpr:
3193 return createCXString("DeclRefExpr");
3194 case CXCursor_MemberRefExpr:
3195 return createCXString("MemberRefExpr");
3196 case CXCursor_CallExpr:
3197 return createCXString("CallExpr");
3198 case CXCursor_ObjCMessageExpr:
3199 return createCXString("ObjCMessageExpr");
3200 case CXCursor_UnexposedStmt:
3201 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003202 case CXCursor_LabelStmt:
3203 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003204 case CXCursor_InvalidFile:
3205 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003206 case CXCursor_InvalidCode:
3207 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003208 case CXCursor_NoDeclFound:
3209 return createCXString("NoDeclFound");
3210 case CXCursor_NotImplemented:
3211 return createCXString("NotImplemented");
3212 case CXCursor_TranslationUnit:
3213 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003214 case CXCursor_UnexposedAttr:
3215 return createCXString("UnexposedAttr");
3216 case CXCursor_IBActionAttr:
3217 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003218 case CXCursor_IBOutletAttr:
3219 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003220 case CXCursor_IBOutletCollectionAttr:
3221 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003222 case CXCursor_PreprocessingDirective:
3223 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003224 case CXCursor_MacroDefinition:
3225 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003226 case CXCursor_MacroInstantiation:
3227 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003228 case CXCursor_InclusionDirective:
3229 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003230 case CXCursor_Namespace:
3231 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003232 case CXCursor_LinkageSpec:
3233 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003234 case CXCursor_CXXBaseSpecifier:
3235 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003236 case CXCursor_Constructor:
3237 return createCXString("CXXConstructor");
3238 case CXCursor_Destructor:
3239 return createCXString("CXXDestructor");
3240 case CXCursor_ConversionFunction:
3241 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003242 case CXCursor_TemplateTypeParameter:
3243 return createCXString("TemplateTypeParameter");
3244 case CXCursor_NonTypeTemplateParameter:
3245 return createCXString("NonTypeTemplateParameter");
3246 case CXCursor_TemplateTemplateParameter:
3247 return createCXString("TemplateTemplateParameter");
3248 case CXCursor_FunctionTemplate:
3249 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003250 case CXCursor_ClassTemplate:
3251 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003252 case CXCursor_ClassTemplatePartialSpecialization:
3253 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003254 case CXCursor_NamespaceAlias:
3255 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003256 case CXCursor_UsingDirective:
3257 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003258 case CXCursor_UsingDeclaration:
3259 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003260 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003261
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003262 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003263 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003264}
Steve Naroff89922f82009-08-31 00:59:03 +00003265
Ted Kremeneke68fff62010-02-17 00:41:32 +00003266enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3267 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003268 CXClientData client_data) {
3269 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003270
3271 // If our current best cursor is the construction of a temporary object,
3272 // don't replace that cursor with a type reference, because we want
3273 // clang_getCursor() to point at the constructor.
3274 if (clang_isExpression(BestCursor->kind) &&
3275 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3276 cursor.kind == CXCursor_TypeRef)
3277 return CXChildVisit_Recurse;
3278
Douglas Gregor85fe1562010-12-10 07:23:11 +00003279 // Don't override a preprocessing cursor with another preprocessing
3280 // cursor; we want the outermost preprocessing cursor.
3281 if (clang_isPreprocessing(cursor.kind) &&
3282 clang_isPreprocessing(BestCursor->kind))
3283 return CXChildVisit_Recurse;
3284
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003285 *BestCursor = cursor;
3286 return CXChildVisit_Recurse;
3287}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003288
Douglas Gregorb9790342010-01-22 21:44:22 +00003289CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3290 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003291 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003292
Ted Kremeneka60ed472010-11-16 08:15:36 +00003293 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003294 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3295
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003296 // Translate the given source location to make it point at the beginning of
3297 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003298 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003299
3300 // Guard against an invalid SourceLocation, or we may assert in one
3301 // of the following calls.
3302 if (SLoc.isInvalid())
3303 return clang_getNullCursor();
3304
Douglas Gregor40749ee2010-11-03 00:35:38 +00003305 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003306 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3307 CXXUnit->getASTContext().getLangOptions());
3308
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003309 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3310 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003311 // FIXME: Would be great to have a "hint" cursor, then walk from that
3312 // hint cursor upward until we find a cursor whose source range encloses
3313 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003314 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3315 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003316 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003317 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003318 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003319
3320 if (Logging) {
3321 CXFile SearchFile;
3322 unsigned SearchLine, SearchColumn;
3323 CXFile ResultFile;
3324 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003325 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3326 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003327 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3328
3329 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3330 0);
3331 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3332 &ResultColumn, 0);
3333 SearchFileName = clang_getFileName(SearchFile);
3334 ResultFileName = clang_getFileName(ResultFile);
3335 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003336 USR = clang_getCursorUSR(Result);
3337 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003338 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3339 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003340 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3341 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003342 clang_disposeString(SearchFileName);
3343 clang_disposeString(ResultFileName);
3344 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003345 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003346
3347 CXCursor Definition = clang_getCursorDefinition(Result);
3348 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3349 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3350 CXString DefinitionKindSpelling
3351 = clang_getCursorKindSpelling(Definition.kind);
3352 CXFile DefinitionFile;
3353 unsigned DefinitionLine, DefinitionColumn;
3354 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3355 &DefinitionLine, &DefinitionColumn, 0);
3356 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3357 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3358 clang_getCString(DefinitionKindSpelling),
3359 clang_getCString(DefinitionFileName),
3360 DefinitionLine, DefinitionColumn);
3361 clang_disposeString(DefinitionFileName);
3362 clang_disposeString(DefinitionKindSpelling);
3363 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003364 }
3365
Ted Kremeneke68fff62010-02-17 00:41:32 +00003366 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003367}
3368
Ted Kremenek73885552009-11-17 19:28:59 +00003369CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003370 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003371}
3372
3373unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003374 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003375}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003376
Douglas Gregor9ce55842010-11-20 00:09:34 +00003377unsigned clang_hashCursor(CXCursor C) {
3378 unsigned Index = 0;
3379 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3380 Index = 1;
3381
3382 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3383 std::make_pair(C.kind, C.data[Index]));
3384}
3385
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003386unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003387 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3388}
3389
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003390unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003391 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3392}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003393
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003394unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003395 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3396}
3397
Douglas Gregor97b98722010-01-19 23:20:36 +00003398unsigned clang_isExpression(enum CXCursorKind K) {
3399 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3400}
3401
3402unsigned clang_isStatement(enum CXCursorKind K) {
3403 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3404}
3405
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003406unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3407 return K == CXCursor_TranslationUnit;
3408}
3409
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003410unsigned clang_isPreprocessing(enum CXCursorKind K) {
3411 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3412}
3413
Ted Kremenekad6eff62010-03-08 21:17:29 +00003414unsigned clang_isUnexposed(enum CXCursorKind K) {
3415 switch (K) {
3416 case CXCursor_UnexposedDecl:
3417 case CXCursor_UnexposedExpr:
3418 case CXCursor_UnexposedStmt:
3419 case CXCursor_UnexposedAttr:
3420 return true;
3421 default:
3422 return false;
3423 }
3424}
3425
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003426CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003427 return C.kind;
3428}
3429
Douglas Gregor98258af2010-01-18 22:46:11 +00003430CXSourceLocation clang_getCursorLocation(CXCursor C) {
3431 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003432 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003433 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003434 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3435 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003436 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003437 }
3438
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003439 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003440 std::pair<ObjCProtocolDecl *, SourceLocation> P
3441 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003442 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003443 }
3444
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003445 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003446 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3447 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003448 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003449 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003450
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003451 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003452 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003453 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003454 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003455
3456 case CXCursor_TemplateRef: {
3457 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3458 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3459 }
3460
Douglas Gregor69319002010-08-31 23:48:11 +00003461 case CXCursor_NamespaceRef: {
3462 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3463 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3464 }
3465
Douglas Gregora67e03f2010-09-09 21:42:20 +00003466 case CXCursor_MemberRef: {
3467 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3468 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3469 }
3470
Ted Kremenek3064ef92010-08-27 21:34:58 +00003471 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003472 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3473 if (!BaseSpec)
3474 return clang_getNullLocation();
3475
3476 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3477 return cxloc::translateSourceLocation(getCursorContext(C),
3478 TSInfo->getTypeLoc().getBeginLoc());
3479
3480 return cxloc::translateSourceLocation(getCursorContext(C),
3481 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003482 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003483
Douglas Gregor36897b02010-09-10 00:22:18 +00003484 case CXCursor_LabelRef: {
3485 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3486 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3487 }
3488
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003489 case CXCursor_OverloadedDeclRef:
3490 return cxloc::translateSourceLocation(getCursorContext(C),
3491 getCursorOverloadedDeclRef(C).second);
3492
Douglas Gregorf46034a2010-01-18 23:41:10 +00003493 default:
3494 // FIXME: Need a way to enumerate all non-reference cases.
3495 llvm_unreachable("Missed a reference kind");
3496 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003497 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003498
3499 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003500 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003501 getLocationFromExpr(getCursorExpr(C)));
3502
Douglas Gregor36897b02010-09-10 00:22:18 +00003503 if (clang_isStatement(C.kind))
3504 return cxloc::translateSourceLocation(getCursorContext(C),
3505 getCursorStmt(C)->getLocStart());
3506
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003507 if (C.kind == CXCursor_PreprocessingDirective) {
3508 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3509 return cxloc::translateSourceLocation(getCursorContext(C), L);
3510 }
Douglas Gregor48072312010-03-18 15:23:44 +00003511
3512 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003513 SourceLocation L
3514 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003515 return cxloc::translateSourceLocation(getCursorContext(C), L);
3516 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003517
3518 if (C.kind == CXCursor_MacroDefinition) {
3519 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3520 return cxloc::translateSourceLocation(getCursorContext(C), L);
3521 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003522
3523 if (C.kind == CXCursor_InclusionDirective) {
3524 SourceLocation L
3525 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3526 return cxloc::translateSourceLocation(getCursorContext(C), L);
3527 }
3528
Ted Kremenek9a700d22010-05-12 06:16:13 +00003529 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003530 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003531
Douglas Gregorf46034a2010-01-18 23:41:10 +00003532 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003533 SourceLocation Loc = D->getLocation();
3534 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3535 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003536 // FIXME: Multiple variables declared in a single declaration
3537 // currently lack the information needed to correctly determine their
3538 // ranges when accounting for the type-specifier. We use context
3539 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3540 // and if so, whether it is the first decl.
3541 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3542 if (!cxcursor::isFirstInDeclGroup(C))
3543 Loc = VD->getLocation();
3544 }
3545
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003546 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003547}
Douglas Gregora7bde202010-01-19 00:34:46 +00003548
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003549} // end extern "C"
3550
3551static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003552 if (clang_isReference(C.kind)) {
3553 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003554 case CXCursor_ObjCSuperClassRef:
3555 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003556
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003557 case CXCursor_ObjCProtocolRef:
3558 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003559
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003560 case CXCursor_ObjCClassRef:
3561 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003562
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003563 case CXCursor_TypeRef:
3564 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003565
3566 case CXCursor_TemplateRef:
3567 return getCursorTemplateRef(C).second;
3568
Douglas Gregor69319002010-08-31 23:48:11 +00003569 case CXCursor_NamespaceRef:
3570 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003571
3572 case CXCursor_MemberRef:
3573 return getCursorMemberRef(C).second;
3574
Ted Kremenek3064ef92010-08-27 21:34:58 +00003575 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003576 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003577
Douglas Gregor36897b02010-09-10 00:22:18 +00003578 case CXCursor_LabelRef:
3579 return getCursorLabelRef(C).second;
3580
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003581 case CXCursor_OverloadedDeclRef:
3582 return getCursorOverloadedDeclRef(C).second;
3583
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003584 default:
3585 // FIXME: Need a way to enumerate all non-reference cases.
3586 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003587 }
3588 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003589
3590 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003591 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003592
3593 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003594 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003595
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003596 if (C.kind == CXCursor_PreprocessingDirective)
3597 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003598
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003599 if (C.kind == CXCursor_MacroInstantiation)
3600 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003601
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003602 if (C.kind == CXCursor_MacroDefinition)
3603 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003604
3605 if (C.kind == CXCursor_InclusionDirective)
3606 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3607
Ted Kremenek007a7c92010-11-01 23:26:51 +00003608 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3609 Decl *D = cxcursor::getCursorDecl(C);
3610 SourceRange R = D->getSourceRange();
3611 // FIXME: Multiple variables declared in a single declaration
3612 // currently lack the information needed to correctly determine their
3613 // ranges when accounting for the type-specifier. We use context
3614 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3615 // and if so, whether it is the first decl.
3616 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3617 if (!cxcursor::isFirstInDeclGroup(C))
3618 R.setBegin(VD->getLocation());
3619 }
3620 return R;
3621 }
Douglas Gregor66537982010-11-17 17:14:07 +00003622 return SourceRange();
3623}
3624
3625/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3626/// the decl-specifier-seq for declarations.
3627static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3628 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3629 Decl *D = cxcursor::getCursorDecl(C);
3630 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003631
Douglas Gregor2494dd02011-03-01 01:34:45 +00003632 // Adjust the start of the location for declarations preceded by
3633 // declaration specifiers.
3634 SourceLocation StartLoc;
3635 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3636 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3637 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3638 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3639 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3640 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3641 }
3642
3643 if (StartLoc.isValid() && R.getBegin().isValid() &&
3644 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3645 R.setBegin(StartLoc);
3646
3647 // FIXME: Multiple variables declared in a single declaration
3648 // currently lack the information needed to correctly determine their
3649 // ranges when accounting for the type-specifier. We use context
3650 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3651 // and if so, whether it is the first decl.
3652 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3653 if (!cxcursor::isFirstInDeclGroup(C))
3654 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003655 }
3656
3657 return R;
3658 }
3659
3660 return getRawCursorExtent(C);
3661}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003662
3663extern "C" {
3664
3665CXSourceRange clang_getCursorExtent(CXCursor C) {
3666 SourceRange R = getRawCursorExtent(C);
3667 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003668 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003669
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003670 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003671}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003672
3673CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003674 if (clang_isInvalid(C.kind))
3675 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003676
Ted Kremeneka60ed472010-11-16 08:15:36 +00003677 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003678 if (clang_isDeclaration(C.kind)) {
3679 Decl *D = getCursorDecl(C);
3680 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003681 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003682 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003683 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003684 if (ObjCForwardProtocolDecl *Protocols
3685 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003686 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003687 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3688 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3689 return MakeCXCursor(Property, tu);
3690
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003691 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003692 }
3693
Douglas Gregor97b98722010-01-19 23:20:36 +00003694 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003695 Expr *E = getCursorExpr(C);
3696 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003697 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003698 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003699
3700 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003701 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003702
Douglas Gregor97b98722010-01-19 23:20:36 +00003703 return clang_getNullCursor();
3704 }
3705
Douglas Gregor36897b02010-09-10 00:22:18 +00003706 if (clang_isStatement(C.kind)) {
3707 Stmt *S = getCursorStmt(C);
3708 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003709 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003710
3711 return clang_getNullCursor();
3712 }
3713
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003714 if (C.kind == CXCursor_MacroInstantiation) {
3715 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003716 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003717 }
3718
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003719 if (!clang_isReference(C.kind))
3720 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003721
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003722 switch (C.kind) {
3723 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003724 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003725
3726 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003727 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003728
3729 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003730 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003731
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003732 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003733 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003734
3735 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003736 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003737
Douglas Gregor69319002010-08-31 23:48:11 +00003738 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003739 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003740
Douglas Gregora67e03f2010-09-09 21:42:20 +00003741 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003742 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003743
Ted Kremenek3064ef92010-08-27 21:34:58 +00003744 case CXCursor_CXXBaseSpecifier: {
3745 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3746 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003747 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003748 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003749
Douglas Gregor36897b02010-09-10 00:22:18 +00003750 case CXCursor_LabelRef:
3751 // FIXME: We end up faking the "parent" declaration here because we
3752 // don't want to make CXCursor larger.
3753 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003754 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3755 .getTranslationUnitDecl(),
3756 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003757
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003758 case CXCursor_OverloadedDeclRef:
3759 return C;
3760
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003761 default:
3762 // We would prefer to enumerate all non-reference cursor kinds here.
3763 llvm_unreachable("Unhandled reference cursor kind");
3764 break;
3765 }
3766 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003767
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003768 return clang_getNullCursor();
3769}
3770
Douglas Gregorb6998662010-01-19 19:34:47 +00003771CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003772 if (clang_isInvalid(C.kind))
3773 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003774
Ted Kremeneka60ed472010-11-16 08:15:36 +00003775 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003776
Douglas Gregorb6998662010-01-19 19:34:47 +00003777 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003778 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003779 C = clang_getCursorReferenced(C);
3780 WasReference = true;
3781 }
3782
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003783 if (C.kind == CXCursor_MacroInstantiation)
3784 return clang_getCursorReferenced(C);
3785
Douglas Gregorb6998662010-01-19 19:34:47 +00003786 if (!clang_isDeclaration(C.kind))
3787 return clang_getNullCursor();
3788
3789 Decl *D = getCursorDecl(C);
3790 if (!D)
3791 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003792
Douglas Gregorb6998662010-01-19 19:34:47 +00003793 switch (D->getKind()) {
3794 // Declaration kinds that don't really separate the notions of
3795 // declaration and definition.
3796 case Decl::Namespace:
3797 case Decl::Typedef:
3798 case Decl::TemplateTypeParm:
3799 case Decl::EnumConstant:
3800 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003801 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003802 case Decl::ObjCIvar:
3803 case Decl::ObjCAtDefsField:
3804 case Decl::ImplicitParam:
3805 case Decl::ParmVar:
3806 case Decl::NonTypeTemplateParm:
3807 case Decl::TemplateTemplateParm:
3808 case Decl::ObjCCategoryImpl:
3809 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003810 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003811 case Decl::LinkageSpec:
3812 case Decl::ObjCPropertyImpl:
3813 case Decl::FileScopeAsm:
3814 case Decl::StaticAssert:
3815 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003816 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003817 return C;
3818
3819 // Declaration kinds that don't make any sense here, but are
3820 // nonetheless harmless.
3821 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003822 break;
3823
3824 // Declaration kinds for which the definition is not resolvable.
3825 case Decl::UnresolvedUsingTypename:
3826 case Decl::UnresolvedUsingValue:
3827 break;
3828
3829 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003830 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003831 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003832
3833 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003834 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003835
3836 case Decl::Enum:
3837 case Decl::Record:
3838 case Decl::CXXRecord:
3839 case Decl::ClassTemplateSpecialization:
3840 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003841 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003842 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003843 return clang_getNullCursor();
3844
3845 case Decl::Function:
3846 case Decl::CXXMethod:
3847 case Decl::CXXConstructor:
3848 case Decl::CXXDestructor:
3849 case Decl::CXXConversion: {
3850 const FunctionDecl *Def = 0;
3851 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003852 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003853 return clang_getNullCursor();
3854 }
3855
3856 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003857 // Ask the variable if it has a definition.
3858 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003859 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003860 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003861 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003862
Douglas Gregorb6998662010-01-19 19:34:47 +00003863 case Decl::FunctionTemplate: {
3864 const FunctionDecl *Def = 0;
3865 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003866 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003867 return clang_getNullCursor();
3868 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869
Douglas Gregorb6998662010-01-19 19:34:47 +00003870 case Decl::ClassTemplate: {
3871 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003872 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003873 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003874 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003875 return clang_getNullCursor();
3876 }
3877
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003878 case Decl::Using:
3879 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003880 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003881
3882 case Decl::UsingShadow:
3883 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003884 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003885 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003886
3887 case Decl::ObjCMethod: {
3888 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3889 if (Method->isThisDeclarationADefinition())
3890 return C;
3891
3892 // Dig out the method definition in the associated
3893 // @implementation, if we have it.
3894 // FIXME: The ASTs should make finding the definition easier.
3895 if (ObjCInterfaceDecl *Class
3896 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3897 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3898 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3899 Method->isInstanceMethod()))
3900 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003901 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003902
3903 return clang_getNullCursor();
3904 }
3905
3906 case Decl::ObjCCategory:
3907 if (ObjCCategoryImplDecl *Impl
3908 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003909 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003910 return clang_getNullCursor();
3911
3912 case Decl::ObjCProtocol:
3913 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3914 return C;
3915 return clang_getNullCursor();
3916
3917 case Decl::ObjCInterface:
3918 // There are two notions of a "definition" for an Objective-C
3919 // class: the interface and its implementation. When we resolved a
3920 // reference to an Objective-C class, produce the @interface as
3921 // the definition; when we were provided with the interface,
3922 // produce the @implementation as the definition.
3923 if (WasReference) {
3924 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3925 return C;
3926 } else if (ObjCImplementationDecl *Impl
3927 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003928 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003929 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003930
Douglas Gregorb6998662010-01-19 19:34:47 +00003931 case Decl::ObjCProperty:
3932 // FIXME: We don't really know where to find the
3933 // ObjCPropertyImplDecls that implement this property.
3934 return clang_getNullCursor();
3935
3936 case Decl::ObjCCompatibleAlias:
3937 if (ObjCInterfaceDecl *Class
3938 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3939 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003940 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003941
Douglas Gregorb6998662010-01-19 19:34:47 +00003942 return clang_getNullCursor();
3943
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003944 case Decl::ObjCForwardProtocol:
3945 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003946 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003947
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003948 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003949 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003950 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003951
3952 case Decl::Friend:
3953 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003954 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003955 return clang_getNullCursor();
3956
3957 case Decl::FriendTemplate:
3958 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003959 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003960 return clang_getNullCursor();
3961 }
3962
3963 return clang_getNullCursor();
3964}
3965
3966unsigned clang_isCursorDefinition(CXCursor C) {
3967 if (!clang_isDeclaration(C.kind))
3968 return 0;
3969
3970 return clang_getCursorDefinition(C) == C;
3971}
3972
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003973CXCursor clang_getCanonicalCursor(CXCursor C) {
3974 if (!clang_isDeclaration(C.kind))
3975 return C;
3976
3977 if (Decl *D = getCursorDecl(C))
3978 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3979
3980 return C;
3981}
3982
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003983unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003984 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003985 return 0;
3986
3987 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3988 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3989 return E->getNumDecls();
3990
3991 if (OverloadedTemplateStorage *S
3992 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3993 return S->size();
3994
3995 Decl *D = Storage.get<Decl*>();
3996 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003997 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003998 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3999 return Classes->size();
4000 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4001 return Protocols->protocol_size();
4002
4003 return 0;
4004}
4005
4006CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004007 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004008 return clang_getNullCursor();
4009
4010 if (index >= clang_getNumOverloadedDecls(cursor))
4011 return clang_getNullCursor();
4012
Ted Kremeneka60ed472010-11-16 08:15:36 +00004013 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004014 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4015 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004016 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004017
4018 if (OverloadedTemplateStorage *S
4019 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004020 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004021
4022 Decl *D = Storage.get<Decl*>();
4023 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4024 // FIXME: This is, unfortunately, linear time.
4025 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4026 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004027 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004028 }
4029
4030 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004031 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004032
4033 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004034 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004035
4036 return clang_getNullCursor();
4037}
4038
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004039void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004040 const char **startBuf,
4041 const char **endBuf,
4042 unsigned *startLine,
4043 unsigned *startColumn,
4044 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004045 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004046 assert(getCursorDecl(C) && "CXCursor has null decl");
4047 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004048 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4049 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004050
Steve Naroff4ade6d62009-09-23 17:52:52 +00004051 SourceManager &SM = FD->getASTContext().getSourceManager();
4052 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4053 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4054 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4055 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4056 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4057 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4058}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004059
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004060void clang_enableStackTraces(void) {
4061 llvm::sys::PrintStackTraceOnErrorSignal();
4062}
4063
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004064void clang_executeOnThread(void (*fn)(void*), void *user_data,
4065 unsigned stack_size) {
4066 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4067}
4068
Ted Kremenekfb480492010-01-13 21:46:36 +00004069} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004070
Ted Kremenekfb480492010-01-13 21:46:36 +00004071//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004072// Token-based Operations.
4073//===----------------------------------------------------------------------===//
4074
4075/* CXToken layout:
4076 * int_data[0]: a CXTokenKind
4077 * int_data[1]: starting token location
4078 * int_data[2]: token length
4079 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004080 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004081 * otherwise unused.
4082 */
4083extern "C" {
4084
4085CXTokenKind clang_getTokenKind(CXToken CXTok) {
4086 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4087}
4088
4089CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4090 switch (clang_getTokenKind(CXTok)) {
4091 case CXToken_Identifier:
4092 case CXToken_Keyword:
4093 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004094 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4095 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004096
4097 case CXToken_Literal: {
4098 // We have stashed the starting pointer in the ptr_data field. Use it.
4099 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004100 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004101 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004102
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004103 case CXToken_Punctuation:
4104 case CXToken_Comment:
4105 break;
4106 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004107
4108 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004109 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004110 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004111 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004112 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004113
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004114 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4115 std::pair<FileID, unsigned> LocInfo
4116 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004117 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004118 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004119 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4120 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004121 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004122
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004123 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004124}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004125
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004126CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004127 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004128 if (!CXXUnit)
4129 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004130
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004131 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4132 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4133}
4134
4135CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004136 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004137 if (!CXXUnit)
4138 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004139
4140 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004141 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4142}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004143
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004144void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4145 CXToken **Tokens, unsigned *NumTokens) {
4146 if (Tokens)
4147 *Tokens = 0;
4148 if (NumTokens)
4149 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004150
Ted Kremeneka60ed472010-11-16 08:15:36 +00004151 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004152 if (!CXXUnit || !Tokens || !NumTokens)
4153 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004154
Douglas Gregorbdf60622010-03-05 21:16:25 +00004155 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4156
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004157 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004158 if (R.isInvalid())
4159 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004160
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004161 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4162 std::pair<FileID, unsigned> BeginLocInfo
4163 = SourceMgr.getDecomposedLoc(R.getBegin());
4164 std::pair<FileID, unsigned> EndLocInfo
4165 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004166
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004167 // Cannot tokenize across files.
4168 if (BeginLocInfo.first != EndLocInfo.first)
4169 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004170
4171 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004172 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004173 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004174 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004175 if (Invalid)
4176 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004177
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004178 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4179 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004180 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004181 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004182
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004183 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004184 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004185 llvm::SmallVector<CXToken, 32> CXTokens;
4186 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004187 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004188 do {
4189 // Lex the next token
4190 Lex.LexFromRawLexer(Tok);
4191 if (Tok.is(tok::eof))
4192 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004193
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004194 // Initialize the CXToken.
4195 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004196
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004197 // - Common fields
4198 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4199 CXTok.int_data[2] = Tok.getLength();
4200 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004201
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004202 // - Kind-specific fields
4203 if (Tok.isLiteral()) {
4204 CXTok.int_data[0] = CXToken_Literal;
4205 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004206 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004207 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004208 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004209 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004210
David Chisnall096428b2010-10-13 21:44:48 +00004211 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004212 CXTok.int_data[0] = CXToken_Keyword;
4213 }
4214 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004215 CXTok.int_data[0] = Tok.is(tok::identifier)
4216 ? CXToken_Identifier
4217 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004218 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004219 CXTok.ptr_data = II;
4220 } else if (Tok.is(tok::comment)) {
4221 CXTok.int_data[0] = CXToken_Comment;
4222 CXTok.ptr_data = 0;
4223 } else {
4224 CXTok.int_data[0] = CXToken_Punctuation;
4225 CXTok.ptr_data = 0;
4226 }
4227 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004228 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004229 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004230
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004231 if (CXTokens.empty())
4232 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004233
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004234 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4235 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4236 *NumTokens = CXTokens.size();
4237}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004238
Ted Kremenek6db61092010-05-05 00:55:15 +00004239void clang_disposeTokens(CXTranslationUnit TU,
4240 CXToken *Tokens, unsigned NumTokens) {
4241 free(Tokens);
4242}
4243
4244} // end: extern "C"
4245
4246//===----------------------------------------------------------------------===//
4247// Token annotation APIs.
4248//===----------------------------------------------------------------------===//
4249
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004250typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004251static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4252 CXCursor parent,
4253 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004254namespace {
4255class AnnotateTokensWorker {
4256 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004257 CXToken *Tokens;
4258 CXCursor *Cursors;
4259 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004260 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004261 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004262 CursorVisitor AnnotateVis;
4263 SourceManager &SrcMgr;
4264
4265 bool MoreTokens() const { return TokIdx < NumTokens; }
4266 unsigned NextToken() const { return TokIdx; }
4267 void AdvanceToken() { ++TokIdx; }
4268 SourceLocation GetTokenLoc(unsigned tokI) {
4269 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4270 }
4271
Ted Kremenek6db61092010-05-05 00:55:15 +00004272public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004273 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004274 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004275 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004276 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004277 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004278 AnnotateVis(tu,
4279 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004280 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004281 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004282
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004283 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004284 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004286 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004287 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004288 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004289};
4290}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004291
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004292void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4293 // Walk the AST within the region of interest, annotating tokens
4294 // along the way.
4295 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004296
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004297 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4298 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004299 if (Pos != Annotated.end() &&
4300 (clang_isInvalid(Cursors[I].kind) ||
4301 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004302 Cursors[I] = Pos->second;
4303 }
4304
4305 // Finish up annotating any tokens left.
4306 if (!MoreTokens())
4307 return;
4308
4309 const CXCursor &C = clang_getNullCursor();
4310 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4311 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4312 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004313 }
4314}
4315
Ted Kremenek6db61092010-05-05 00:55:15 +00004316enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004317AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004318 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004319 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004320 if (cursorRange.isInvalid())
4321 return CXChildVisit_Recurse;
4322
Douglas Gregor4419b672010-10-21 06:10:04 +00004323 if (clang_isPreprocessing(cursor.kind)) {
4324 // For macro instantiations, just note where the beginning of the macro
4325 // instantiation occurs.
4326 if (cursor.kind == CXCursor_MacroInstantiation) {
4327 Annotated[Loc.int_data] = cursor;
4328 return CXChildVisit_Recurse;
4329 }
4330
Douglas Gregor4419b672010-10-21 06:10:04 +00004331 // Items in the preprocessing record are kept separate from items in
4332 // declarations, so we keep a separate token index.
4333 unsigned SavedTokIdx = TokIdx;
4334 TokIdx = PreprocessingTokIdx;
4335
4336 // Skip tokens up until we catch up to the beginning of the preprocessing
4337 // entry.
4338 while (MoreTokens()) {
4339 const unsigned I = NextToken();
4340 SourceLocation TokLoc = GetTokenLoc(I);
4341 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4342 case RangeBefore:
4343 AdvanceToken();
4344 continue;
4345 case RangeAfter:
4346 case RangeOverlap:
4347 break;
4348 }
4349 break;
4350 }
4351
4352 // Look at all of the tokens within this range.
4353 while (MoreTokens()) {
4354 const unsigned I = NextToken();
4355 SourceLocation TokLoc = GetTokenLoc(I);
4356 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4357 case RangeBefore:
4358 assert(0 && "Infeasible");
4359 case RangeAfter:
4360 break;
4361 case RangeOverlap:
4362 Cursors[I] = cursor;
4363 AdvanceToken();
4364 continue;
4365 }
4366 break;
4367 }
4368
4369 // Save the preprocessing token index; restore the non-preprocessing
4370 // token index.
4371 PreprocessingTokIdx = TokIdx;
4372 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004373 return CXChildVisit_Recurse;
4374 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004375
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004376 if (cursorRange.isInvalid())
4377 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004378
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004379 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4380
Ted Kremeneka333c662010-05-12 05:29:33 +00004381 // Adjust the annotated range based specific declarations.
4382 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4383 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004384 Decl *D = cxcursor::getCursorDecl(cursor);
4385 // Don't visit synthesized ObjC methods, since they have no syntatic
4386 // representation in the source.
4387 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4388 if (MD->isSynthesized())
4389 return CXChildVisit_Continue;
4390 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004391
4392 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004393 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004394 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4395 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4396 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4397 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4398 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004399 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004400
4401 if (StartLoc.isValid() && L.isValid() &&
4402 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4403 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004404 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004405
Ted Kremenek3f404602010-08-14 01:14:06 +00004406 // If the location of the cursor occurs within a macro instantiation, record
4407 // the spelling location of the cursor in our annotation map. We can then
4408 // paper over the token labelings during a post-processing step to try and
4409 // get cursor mappings for tokens that are the *arguments* of a macro
4410 // instantiation.
4411 if (L.isMacroID()) {
4412 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4413 // Only invalidate the old annotation if it isn't part of a preprocessing
4414 // directive. Here we assume that the default construction of CXCursor
4415 // results in CXCursor.kind being an initialized value (i.e., 0). If
4416 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004417
Ted Kremenek3f404602010-08-14 01:14:06 +00004418 CXCursor &oldC = Annotated[rawEncoding];
4419 if (!clang_isPreprocessing(oldC.kind))
4420 oldC = cursor;
4421 }
4422
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004423 const enum CXCursorKind K = clang_getCursorKind(parent);
4424 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004425 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4426 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004427
4428 while (MoreTokens()) {
4429 const unsigned I = NextToken();
4430 SourceLocation TokLoc = GetTokenLoc(I);
4431 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4432 case RangeBefore:
4433 Cursors[I] = updateC;
4434 AdvanceToken();
4435 continue;
4436 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004437 case RangeOverlap:
4438 break;
4439 }
4440 break;
4441 }
4442
4443 // Visit children to get their cursor information.
4444 const unsigned BeforeChildren = NextToken();
4445 VisitChildren(cursor);
4446 const unsigned AfterChildren = NextToken();
4447
4448 // Adjust 'Last' to the last token within the extent of the cursor.
4449 while (MoreTokens()) {
4450 const unsigned I = NextToken();
4451 SourceLocation TokLoc = GetTokenLoc(I);
4452 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4453 case RangeBefore:
4454 assert(0 && "Infeasible");
4455 case RangeAfter:
4456 break;
4457 case RangeOverlap:
4458 Cursors[I] = updateC;
4459 AdvanceToken();
4460 continue;
4461 }
4462 break;
4463 }
4464 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004465
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004466 // Scan the tokens that are at the beginning of the cursor, but are not
4467 // capture by the child cursors.
4468
4469 // For AST elements within macros, rely on a post-annotate pass to
4470 // to correctly annotate the tokens with cursors. Otherwise we can
4471 // get confusing results of having tokens that map to cursors that really
4472 // are expanded by an instantiation.
4473 if (L.isMacroID())
4474 cursor = clang_getNullCursor();
4475
4476 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4477 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4478 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004479
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004480 Cursors[I] = cursor;
4481 }
4482 // Scan the tokens that are at the end of the cursor, but are not captured
4483 // but the child cursors.
4484 for (unsigned I = AfterChildren; I != Last; ++I)
4485 Cursors[I] = cursor;
4486
4487 TokIdx = Last;
4488 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004489}
4490
Ted Kremenek6db61092010-05-05 00:55:15 +00004491static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4492 CXCursor parent,
4493 CXClientData client_data) {
4494 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4495}
4496
Ted Kremenekab979612010-11-11 08:05:23 +00004497// This gets run a separate thread to avoid stack blowout.
4498static void runAnnotateTokensWorker(void *UserData) {
4499 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4500}
4501
Ted Kremenek6db61092010-05-05 00:55:15 +00004502extern "C" {
4503
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004504void clang_annotateTokens(CXTranslationUnit TU,
4505 CXToken *Tokens, unsigned NumTokens,
4506 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004507
4508 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004509 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004510
Douglas Gregor4419b672010-10-21 06:10:04 +00004511 // Any token we don't specifically annotate will have a NULL cursor.
4512 CXCursor C = clang_getNullCursor();
4513 for (unsigned I = 0; I != NumTokens; ++I)
4514 Cursors[I] = C;
4515
Ted Kremeneka60ed472010-11-16 08:15:36 +00004516 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004517 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004518 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004519
Douglas Gregorbdf60622010-03-05 21:16:25 +00004520 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004521
Douglas Gregor0396f462010-03-19 05:22:59 +00004522 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004523 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004524 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4525 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004526 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4527 clang_getTokenLocation(TU,
4528 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004529
Douglas Gregor0396f462010-03-19 05:22:59 +00004530 // A mapping from the source locations found when re-lexing or traversing the
4531 // region of interest to the corresponding cursors.
4532 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004533
4534 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004535 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004536 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4537 std::pair<FileID, unsigned> BeginLocInfo
4538 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4539 std::pair<FileID, unsigned> EndLocInfo
4540 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004541
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004542 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004543 bool Invalid = false;
4544 if (BeginLocInfo.first == EndLocInfo.first &&
4545 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4546 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004547 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4548 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004549 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004550 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004551 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004552
4553 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004554 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004555 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004556 Token Tok;
4557 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004558
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004559 reprocess:
4560 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4561 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004562 // don't see it while preprocessing these tokens later, but keep track
4563 // of all of the token locations inside this preprocessing directive so
4564 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004565 //
4566 // FIXME: Some simple tests here could identify macro definitions and
4567 // #undefs, to provide specific cursor kinds for those.
4568 std::vector<SourceLocation> Locations;
4569 do {
4570 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004571 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004572 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004573
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004574 using namespace cxcursor;
4575 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004576 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4577 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004578 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004579 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4580 Annotated[Locations[I].getRawEncoding()] = Cursor;
4581 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004582
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004583 if (Tok.isAtStartOfLine())
4584 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004585
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004586 continue;
4587 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004588
Douglas Gregor48072312010-03-18 15:23:44 +00004589 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004590 break;
4591 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004592 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004593
Douglas Gregor0396f462010-03-19 05:22:59 +00004594 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004595 // a specific cursor.
4596 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004597 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004598
4599 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004600 // FIXME: We use a ridiculous stack size here because the data-recursion
4601 // algorithm uses a large stack frame than the non-data recursive version,
4602 // and AnnotationTokensWorker currently transforms the data-recursion
4603 // algorithm back into a traditional recursion by explicitly calling
4604 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004605 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004606 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4607 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004608 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4609 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004610}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004611} // end: extern "C"
4612
4613//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004614// Operations for querying linkage of a cursor.
4615//===----------------------------------------------------------------------===//
4616
4617extern "C" {
4618CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004619 if (!clang_isDeclaration(cursor.kind))
4620 return CXLinkage_Invalid;
4621
Ted Kremenek16b42592010-03-03 06:36:57 +00004622 Decl *D = cxcursor::getCursorDecl(cursor);
4623 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4624 switch (ND->getLinkage()) {
4625 case NoLinkage: return CXLinkage_NoLinkage;
4626 case InternalLinkage: return CXLinkage_Internal;
4627 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4628 case ExternalLinkage: return CXLinkage_External;
4629 };
4630
4631 return CXLinkage_Invalid;
4632}
4633} // end: extern "C"
4634
4635//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004636// Operations for querying language of a cursor.
4637//===----------------------------------------------------------------------===//
4638
4639static CXLanguageKind getDeclLanguage(const Decl *D) {
4640 switch (D->getKind()) {
4641 default:
4642 break;
4643 case Decl::ImplicitParam:
4644 case Decl::ObjCAtDefsField:
4645 case Decl::ObjCCategory:
4646 case Decl::ObjCCategoryImpl:
4647 case Decl::ObjCClass:
4648 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004649 case Decl::ObjCForwardProtocol:
4650 case Decl::ObjCImplementation:
4651 case Decl::ObjCInterface:
4652 case Decl::ObjCIvar:
4653 case Decl::ObjCMethod:
4654 case Decl::ObjCProperty:
4655 case Decl::ObjCPropertyImpl:
4656 case Decl::ObjCProtocol:
4657 return CXLanguage_ObjC;
4658 case Decl::CXXConstructor:
4659 case Decl::CXXConversion:
4660 case Decl::CXXDestructor:
4661 case Decl::CXXMethod:
4662 case Decl::CXXRecord:
4663 case Decl::ClassTemplate:
4664 case Decl::ClassTemplatePartialSpecialization:
4665 case Decl::ClassTemplateSpecialization:
4666 case Decl::Friend:
4667 case Decl::FriendTemplate:
4668 case Decl::FunctionTemplate:
4669 case Decl::LinkageSpec:
4670 case Decl::Namespace:
4671 case Decl::NamespaceAlias:
4672 case Decl::NonTypeTemplateParm:
4673 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004674 case Decl::TemplateTemplateParm:
4675 case Decl::TemplateTypeParm:
4676 case Decl::UnresolvedUsingTypename:
4677 case Decl::UnresolvedUsingValue:
4678 case Decl::Using:
4679 case Decl::UsingDirective:
4680 case Decl::UsingShadow:
4681 return CXLanguage_CPlusPlus;
4682 }
4683
4684 return CXLanguage_C;
4685}
4686
4687extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004688
4689enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4690 if (clang_isDeclaration(cursor.kind))
4691 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4692 if (D->hasAttr<UnavailableAttr>() ||
4693 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4694 return CXAvailability_Available;
4695
4696 if (D->hasAttr<DeprecatedAttr>())
4697 return CXAvailability_Deprecated;
4698 }
4699
4700 return CXAvailability_Available;
4701}
4702
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004703CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4704 if (clang_isDeclaration(cursor.kind))
4705 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4706
4707 return CXLanguage_Invalid;
4708}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004709
4710 /// \brief If the given cursor is the "templated" declaration
4711 /// descibing a class or function template, return the class or
4712 /// function template.
4713static Decl *maybeGetTemplateCursor(Decl *D) {
4714 if (!D)
4715 return 0;
4716
4717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4718 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4719 return FunTmpl;
4720
4721 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4722 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4723 return ClassTmpl;
4724
4725 return D;
4726}
4727
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004728CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4729 if (clang_isDeclaration(cursor.kind)) {
4730 if (Decl *D = getCursorDecl(cursor)) {
4731 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004732 if (!DC)
4733 return clang_getNullCursor();
4734
4735 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4736 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004737 }
4738 }
4739
4740 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4741 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004742 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004743 }
4744
4745 return clang_getNullCursor();
4746}
4747
4748CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4749 if (clang_isDeclaration(cursor.kind)) {
4750 if (Decl *D = getCursorDecl(cursor)) {
4751 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004752 if (!DC)
4753 return clang_getNullCursor();
4754
4755 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4756 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004757 }
4758 }
4759
4760 // FIXME: Note that we can't easily compute the lexical context of a
4761 // statement or expression, so we return nothing.
4762 return clang_getNullCursor();
4763}
4764
Douglas Gregor9f592342010-10-01 20:25:15 +00004765static void CollectOverriddenMethods(DeclContext *Ctx,
4766 ObjCMethodDecl *Method,
4767 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4768 if (!Ctx)
4769 return;
4770
4771 // If we have a class or category implementation, jump straight to the
4772 // interface.
4773 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4774 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4775
4776 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4777 if (!Container)
4778 return;
4779
4780 // Check whether we have a matching method at this level.
4781 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4782 Method->isInstanceMethod()))
4783 if (Method != Overridden) {
4784 // We found an override at this level; there is no need to look
4785 // into other protocols or categories.
4786 Methods.push_back(Overridden);
4787 return;
4788 }
4789
4790 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4791 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4792 PEnd = Protocol->protocol_end();
4793 P != PEnd; ++P)
4794 CollectOverriddenMethods(*P, Method, Methods);
4795 }
4796
4797 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4798 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4799 PEnd = Category->protocol_end();
4800 P != PEnd; ++P)
4801 CollectOverriddenMethods(*P, Method, Methods);
4802 }
4803
4804 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4805 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4806 PEnd = Interface->protocol_end();
4807 P != PEnd; ++P)
4808 CollectOverriddenMethods(*P, Method, Methods);
4809
4810 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4811 Category; Category = Category->getNextClassCategory())
4812 CollectOverriddenMethods(Category, Method, Methods);
4813
4814 // We only look into the superclass if we haven't found anything yet.
4815 if (Methods.empty())
4816 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4817 return CollectOverriddenMethods(Super, Method, Methods);
4818 }
4819}
4820
4821void clang_getOverriddenCursors(CXCursor cursor,
4822 CXCursor **overridden,
4823 unsigned *num_overridden) {
4824 if (overridden)
4825 *overridden = 0;
4826 if (num_overridden)
4827 *num_overridden = 0;
4828 if (!overridden || !num_overridden)
4829 return;
4830
4831 if (!clang_isDeclaration(cursor.kind))
4832 return;
4833
4834 Decl *D = getCursorDecl(cursor);
4835 if (!D)
4836 return;
4837
4838 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004839 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004840 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4841 *num_overridden = CXXMethod->size_overridden_methods();
4842 if (!*num_overridden)
4843 return;
4844
4845 *overridden = new CXCursor [*num_overridden];
4846 unsigned I = 0;
4847 for (CXXMethodDecl::method_iterator
4848 M = CXXMethod->begin_overridden_methods(),
4849 MEnd = CXXMethod->end_overridden_methods();
4850 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004851 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004852 return;
4853 }
4854
4855 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4856 if (!Method)
4857 return;
4858
4859 // Handle Objective-C methods.
4860 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4861 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4862
4863 if (Methods.empty())
4864 return;
4865
4866 *num_overridden = Methods.size();
4867 *overridden = new CXCursor [Methods.size()];
4868 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004869 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004870}
4871
4872void clang_disposeOverriddenCursors(CXCursor *overridden) {
4873 delete [] overridden;
4874}
4875
Douglas Gregorecdcb882010-10-20 22:00:55 +00004876CXFile clang_getIncludedFile(CXCursor cursor) {
4877 if (cursor.kind != CXCursor_InclusionDirective)
4878 return 0;
4879
4880 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4881 return (void *)ID->getFile();
4882}
4883
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004884} // end: extern "C"
4885
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004886
4887//===----------------------------------------------------------------------===//
4888// C++ AST instrospection.
4889//===----------------------------------------------------------------------===//
4890
4891extern "C" {
4892unsigned clang_CXXMethod_isStatic(CXCursor C) {
4893 if (!clang_isDeclaration(C.kind))
4894 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004895
4896 CXXMethodDecl *Method = 0;
4897 Decl *D = cxcursor::getCursorDecl(C);
4898 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4899 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4900 else
4901 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4902 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004903}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004904
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004905} // end: extern "C"
4906
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004907//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004908// Attribute introspection.
4909//===----------------------------------------------------------------------===//
4910
4911extern "C" {
4912CXType clang_getIBOutletCollectionType(CXCursor C) {
4913 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004914 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004915
4916 IBOutletCollectionAttr *A =
4917 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4918
Douglas Gregor841b2382011-03-06 18:55:32 +00004919 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004920}
4921} // end: extern "C"
4922
4923//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004924// Misc. utility functions.
4925//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004926
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004927/// Default to using an 8 MB stack size on "safety" threads.
4928static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004929
4930namespace clang {
4931
4932bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004933 void (*Fn)(void*), void *UserData,
4934 unsigned Size) {
4935 if (!Size)
4936 Size = GetSafetyThreadStackSize();
4937 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004938 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4939 return CRC.RunSafely(Fn, UserData);
4940}
4941
4942unsigned GetSafetyThreadStackSize() {
4943 return SafetyStackThreadSize;
4944}
4945
4946void SetSafetyThreadStackSize(unsigned Value) {
4947 SafetyStackThreadSize = Value;
4948}
4949
4950}
4951
Ted Kremenek04bb7162010-01-22 22:44:15 +00004952extern "C" {
4953
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004954CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004955 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004956}
4957
4958} // end: extern "C"