blob: d29e459827763102035747bf248623bb99c5133c [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.
1982 if (CXXThisExpr *This
1983 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1984 if (This->isImplicit())
1985 return;
1986
Ted Kremenek28a71942010-11-13 00:36:47 +00001987 AddStmt(M->getBase());
1988}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001989void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1990 AddTypeLoc(E->getEncodedTypeSourceInfo());
1991}
Ted Kremenek28a71942010-11-13 00:36:47 +00001992void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1993 EnqueueChildren(M);
1994 AddTypeLoc(M->getClassReceiverTypeInfo());
1995}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001996void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1997 // Visit the components of the offsetof expression.
1998 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1999 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2000 const OffsetOfNode &Node = E->getComponent(I-1);
2001 switch (Node.getKind()) {
2002 case OffsetOfNode::Array:
2003 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2004 break;
2005 case OffsetOfNode::Field:
2006 AddMemberRef(Node.getField(), Node.getRange().getEnd());
2007 break;
2008 case OffsetOfNode::Identifier:
2009 case OffsetOfNode::Base:
2010 continue;
2011 }
2012 }
2013 // Visit the type into which we're computing the offset.
2014 AddTypeLoc(E->getTypeSourceInfo());
2015}
Ted Kremenek28a71942010-11-13 00:36:47 +00002016void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002017 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002018 WL.push_back(OverloadExprParts(E, Parent));
2019}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002020void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
2021 EnqueueChildren(E);
2022 if (E->isArgumentType())
2023 AddTypeLoc(E->getArgumentTypeInfo());
2024}
Ted Kremenek28a71942010-11-13 00:36:47 +00002025void EnqueueVisitor::VisitStmt(Stmt *S) {
2026 EnqueueChildren(S);
2027}
2028void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2029 AddStmt(S->getBody());
2030 AddStmt(S->getCond());
2031 AddDecl(S->getConditionVariable());
2032}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002033
Ted Kremenek28a71942010-11-13 00:36:47 +00002034void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2035 AddStmt(W->getBody());
2036 AddStmt(W->getCond());
2037 AddDecl(W->getConditionVariable());
2038}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002039void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2040 AddTypeLoc(E->getQueriedTypeSourceInfo());
2041}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002042
2043void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002044 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002045 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002046}
2047
Ted Kremenek28a71942010-11-13 00:36:47 +00002048void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2049 VisitOverloadExpr(U);
2050 if (!U->isImplicitAccess())
2051 AddStmt(U->getBase());
2052}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002053void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2054 AddStmt(E->getSubExpr());
2055 AddTypeLoc(E->getWrittenTypeInfo());
2056}
Douglas Gregor94d96292011-01-19 20:34:17 +00002057void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2058 WL.push_back(SizeOfPackExprParts(E, Parent));
2059}
Ted Kremenek60458782010-11-12 21:34:16 +00002060
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002061void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002062 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002063}
2064
2065bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2066 if (RegionOfInterest.isValid()) {
2067 SourceRange Range = getRawCursorExtent(C);
2068 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2069 return false;
2070 }
2071 return true;
2072}
2073
2074bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2075 while (!WL.empty()) {
2076 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002077 VisitorJob LI = WL.back();
2078 WL.pop_back();
2079
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002080 // Set the Parent field, then back to its old value once we're done.
2081 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2082
2083 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002084 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002085 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002086 if (!D)
2087 continue;
2088
2089 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002090 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002091 return true;
2092
2093 continue;
2094 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002095 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2096 const ExplicitTemplateArgumentList *ArgList =
2097 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2098 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2099 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2100 Arg != ArgEnd; ++Arg) {
2101 if (VisitTemplateArgumentLoc(*Arg))
2102 return true;
2103 }
2104 continue;
2105 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002106 case VisitorJob::TypeLocVisitKind: {
2107 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002108 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002109 return true;
2110 continue;
2111 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002112 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002113 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002114 if (LabelStmt *stmt = LS->getStmt()) {
2115 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2116 TU))) {
2117 return true;
2118 }
2119 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002120 continue;
2121 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002122
Ted Kremenekf64d8032010-11-18 00:02:32 +00002123 case VisitorJob::NestedNameSpecifierVisitKind: {
2124 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2125 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2126 return true;
2127 continue;
2128 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002129
2130 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2131 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2132 if (VisitNestedNameSpecifierLoc(V->get()))
2133 return true;
2134 continue;
2135 }
2136
Ted Kremenekf64d8032010-11-18 00:02:32 +00002137 case VisitorJob::DeclarationNameInfoVisitKind: {
2138 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2139 ->get()))
2140 return true;
2141 continue;
2142 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002143 case VisitorJob::MemberRefVisitKind: {
2144 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2145 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2146 return true;
2147 continue;
2148 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002149 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002150 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002151 if (!S)
2152 continue;
2153
Ted Kremenekf1107452010-11-12 18:26:56 +00002154 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002155 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002156 if (!IsInRegionOfInterest(Cursor))
2157 continue;
2158 switch (Visitor(Cursor, Parent, ClientData)) {
2159 case CXChildVisit_Break: return true;
2160 case CXChildVisit_Continue: break;
2161 case CXChildVisit_Recurse:
2162 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002163 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002164 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002165 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002166 }
2167 case VisitorJob::MemberExprPartsKind: {
2168 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002169 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002170
2171 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002172 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2173 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002174 return true;
2175
2176 // Visit the declaration name.
2177 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2178 return true;
2179
2180 // Visit the explicitly-specified template arguments, if any.
2181 if (M->hasExplicitTemplateArgs()) {
2182 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2183 *ArgEnd = Arg + M->getNumTemplateArgs();
2184 Arg != ArgEnd; ++Arg) {
2185 if (VisitTemplateArgumentLoc(*Arg))
2186 return true;
2187 }
2188 }
2189 continue;
2190 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002191 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002192 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002193 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002194 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2195 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002196 return true;
2197 // Visit declaration name.
2198 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2199 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002200 continue;
2201 }
Ted Kremenek60458782010-11-12 21:34:16 +00002202 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002203 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002204 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002205 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2206 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002207 return true;
2208 // Visit the declaration name.
2209 if (VisitDeclarationNameInfo(O->getNameInfo()))
2210 return true;
2211 // Visit the overloaded declaration reference.
2212 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2213 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002214 continue;
2215 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002216 case VisitorJob::SizeOfPackExprPartsKind: {
2217 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2218 NamedDecl *Pack = E->getPack();
2219 if (isa<TemplateTypeParmDecl>(Pack)) {
2220 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2221 E->getPackLoc(), TU)))
2222 return true;
2223
2224 continue;
2225 }
2226
2227 if (isa<TemplateTemplateParmDecl>(Pack)) {
2228 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2229 E->getPackLoc(), TU)))
2230 return true;
2231
2232 continue;
2233 }
2234
2235 // Non-type template parameter packs and function parameter packs are
2236 // treated like DeclRefExpr cursors.
2237 continue;
2238 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002239 }
2240 }
2241 return false;
2242}
2243
Ted Kremenekcdba6592010-11-18 00:42:18 +00002244bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002245 VisitorWorkList *WL = 0;
2246 if (!WorkListFreeList.empty()) {
2247 WL = WorkListFreeList.back();
2248 WL->clear();
2249 WorkListFreeList.pop_back();
2250 }
2251 else {
2252 WL = new VisitorWorkList();
2253 WorkListCache.push_back(WL);
2254 }
2255 EnqueueWorkList(*WL, S);
2256 bool result = RunVisitorWorkList(*WL);
2257 WorkListFreeList.push_back(WL);
2258 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002259}
2260
2261//===----------------------------------------------------------------------===//
2262// Misc. API hooks.
2263//===----------------------------------------------------------------------===//
2264
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002265static llvm::sys::Mutex EnableMultithreadingMutex;
2266static bool EnabledMultithreading;
2267
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002268extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002269CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2270 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002271 // Disable pretty stack trace functionality, which will otherwise be a very
2272 // poor citizen of the world and set up all sorts of signal handlers.
2273 llvm::DisablePrettyStackTrace = true;
2274
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002275 // We use crash recovery to make some of our APIs more reliable, implicitly
2276 // enable it.
2277 llvm::CrashRecoveryContext::Enable();
2278
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002279 // Enable support for multithreading in LLVM.
2280 {
2281 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2282 if (!EnabledMultithreading) {
2283 llvm::llvm_start_multithreaded();
2284 EnabledMultithreading = true;
2285 }
2286 }
2287
Douglas Gregora030b7c2010-01-22 20:35:53 +00002288 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002289 if (excludeDeclarationsFromPCH)
2290 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002291 if (displayDiagnostics)
2292 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002293 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002294}
2295
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002296void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002297 if (CIdx)
2298 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002299}
2300
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002301CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002302 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002303 if (!CIdx)
2304 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002305
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002306 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002307 FileSystemOptions FileSystemOpts;
2308 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002309
Douglas Gregor28019772010-04-05 23:52:57 +00002310 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002311 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002312 CXXIdx->getOnlyLocalDecls(),
2313 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002314 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002315}
2316
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002317unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002318 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002319 CXTranslationUnit_CacheCompletionResults |
2320 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002321}
2322
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002323CXTranslationUnit
2324clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2325 const char *source_filename,
2326 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002327 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002328 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002329 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002330 return clang_parseTranslationUnit(CIdx, source_filename,
2331 command_line_args, num_command_line_args,
2332 unsaved_files, num_unsaved_files,
2333 CXTranslationUnit_DetailedPreprocessingRecord);
2334}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002335
2336struct ParseTranslationUnitInfo {
2337 CXIndex CIdx;
2338 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002339 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002340 int num_command_line_args;
2341 struct CXUnsavedFile *unsaved_files;
2342 unsigned num_unsaved_files;
2343 unsigned options;
2344 CXTranslationUnit result;
2345};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002346static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002347 ParseTranslationUnitInfo *PTUI =
2348 static_cast<ParseTranslationUnitInfo*>(UserData);
2349 CXIndex CIdx = PTUI->CIdx;
2350 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002351 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002352 int num_command_line_args = PTUI->num_command_line_args;
2353 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2354 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2355 unsigned options = PTUI->options;
2356 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002357
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002358 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002359 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002360
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002361 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2362
Douglas Gregor44c181a2010-07-23 00:33:23 +00002363 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002364 bool CompleteTranslationUnit
2365 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002366 bool CacheCodeCompetionResults
2367 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002368 bool CXXPrecompilePreamble
2369 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2370 bool CXXChainedPCH
2371 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002372
Douglas Gregor5352ac02010-01-28 00:27:43 +00002373 // Configure the diagnostics.
2374 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002375 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002376 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2377 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002378
Douglas Gregor4db64a42010-01-23 00:14:00 +00002379 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2380 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002381 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002382 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002383 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002384 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2385 Buffer));
2386 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002387
Douglas Gregorb10daed2010-10-11 16:52:23 +00002388 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002389
Ted Kremenek139ba862009-10-22 00:03:57 +00002390 // The 'source_filename' argument is optional. If the caller does not
2391 // specify it then it is assumed that the source file is specified
2392 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002393 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002394 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002395
2396 // Since the Clang C library is primarily used by batch tools dealing with
2397 // (often very broken) source code, where spell-checking can have a
2398 // significant negative impact on performance (particularly when
2399 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002400 // Only do this if we haven't found a spell-checking-related argument.
2401 bool FoundSpellCheckingArgument = false;
2402 for (int I = 0; I != num_command_line_args; ++I) {
2403 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2404 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2405 FoundSpellCheckingArgument = true;
2406 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002407 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002408 }
2409 if (!FoundSpellCheckingArgument)
2410 Args.push_back("-fno-spell-checking");
2411
2412 Args.insert(Args.end(), command_line_args,
2413 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002414
Douglas Gregor44c181a2010-07-23 00:33:23 +00002415 // Do we need the detailed preprocessing record?
2416 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002417 Args.push_back("-Xclang");
2418 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002419 }
2420
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002421 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002422 llvm::OwningPtr<ASTUnit> Unit(
2423 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2424 Diags,
2425 CXXIdx->getClangResourcesPath(),
2426 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002427 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002428 RemappedFiles.data(),
2429 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002430 PrecompilePreamble,
2431 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002432 CacheCodeCompetionResults,
2433 CXXPrecompilePreamble,
2434 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002435
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002436 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002437 // Make sure to check that 'Unit' is non-NULL.
2438 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2439 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2440 DEnd = Unit->stored_diag_end();
2441 D != DEnd; ++D) {
2442 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2443 CXString Msg = clang_formatDiagnostic(&Diag,
2444 clang_defaultDiagnosticDisplayOptions());
2445 fprintf(stderr, "%s\n", clang_getCString(Msg));
2446 clang_disposeString(Msg);
2447 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002448#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002449 // On Windows, force a flush, since there may be multiple copies of
2450 // stderr and stdout in the file system, all with different buffers
2451 // but writing to the same device.
2452 fflush(stderr);
2453#endif
2454 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002455 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002456
Ted Kremeneka60ed472010-11-16 08:15:36 +00002457 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002458}
2459CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2460 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002461 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002462 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002463 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002464 unsigned num_unsaved_files,
2465 unsigned options) {
2466 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002467 num_command_line_args, unsaved_files,
2468 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002469 llvm::CrashRecoveryContext CRC;
2470
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002471 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002472 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2473 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2474 fprintf(stderr, " 'command_line_args' : [");
2475 for (int i = 0; i != num_command_line_args; ++i) {
2476 if (i)
2477 fprintf(stderr, ", ");
2478 fprintf(stderr, "'%s'", command_line_args[i]);
2479 }
2480 fprintf(stderr, "],\n");
2481 fprintf(stderr, " 'unsaved_files' : [");
2482 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2483 if (i)
2484 fprintf(stderr, ", ");
2485 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2486 unsaved_files[i].Length);
2487 }
2488 fprintf(stderr, "],\n");
2489 fprintf(stderr, " 'options' : %d,\n", options);
2490 fprintf(stderr, "}\n");
2491
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002492 return 0;
2493 }
2494
2495 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002496}
2497
Douglas Gregor19998442010-08-13 15:35:05 +00002498unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2499 return CXSaveTranslationUnit_None;
2500}
2501
2502int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2503 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002504 if (!TU)
2505 return 1;
2506
Ted Kremeneka60ed472010-11-16 08:15:36 +00002507 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002508}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002509
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002510void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002511 if (CTUnit) {
2512 // If the translation unit has been marked as unsafe to free, just discard
2513 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002514 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002515 return;
2516
Ted Kremeneka60ed472010-11-16 08:15:36 +00002517 delete static_cast<ASTUnit *>(CTUnit->TUData);
2518 disposeCXStringPool(CTUnit->StringPool);
2519 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002520 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002521}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002522
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002523unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2524 return CXReparse_None;
2525}
2526
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002527struct ReparseTranslationUnitInfo {
2528 CXTranslationUnit TU;
2529 unsigned num_unsaved_files;
2530 struct CXUnsavedFile *unsaved_files;
2531 unsigned options;
2532 int result;
2533};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002534
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002535static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002536 ReparseTranslationUnitInfo *RTUI =
2537 static_cast<ReparseTranslationUnitInfo*>(UserData);
2538 CXTranslationUnit TU = RTUI->TU;
2539 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2540 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2541 unsigned options = RTUI->options;
2542 (void) options;
2543 RTUI->result = 1;
2544
Douglas Gregorabc563f2010-07-19 21:46:24 +00002545 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002546 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002547
Ted Kremeneka60ed472010-11-16 08:15:36 +00002548 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002549 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002550
2551 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2552 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2553 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2554 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002555 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002556 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2557 Buffer));
2558 }
2559
Douglas Gregor593b0c12010-09-23 18:47:53 +00002560 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2561 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002562}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002563
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002564int clang_reparseTranslationUnit(CXTranslationUnit TU,
2565 unsigned num_unsaved_files,
2566 struct CXUnsavedFile *unsaved_files,
2567 unsigned options) {
2568 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2569 options, 0 };
2570 llvm::CrashRecoveryContext CRC;
2571
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002572 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002573 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002574 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002575 return 1;
2576 }
2577
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002578
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002579 return RTUI.result;
2580}
2581
Douglas Gregordf95a132010-08-09 20:45:32 +00002582
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002583CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002584 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002585 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002586
Ted Kremeneka60ed472010-11-16 08:15:36 +00002587 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002588 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002589}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002590
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002591CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002592 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002593 return Result;
2594}
2595
Ted Kremenekfb480492010-01-13 21:46:36 +00002596} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002597
Ted Kremenekfb480492010-01-13 21:46:36 +00002598//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002599// CXSourceLocation and CXSourceRange Operations.
2600//===----------------------------------------------------------------------===//
2601
Douglas Gregorb9790342010-01-22 21:44:22 +00002602extern "C" {
2603CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002604 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002605 return Result;
2606}
2607
2608unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002609 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2610 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2611 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002612}
2613
2614CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2615 CXFile file,
2616 unsigned line,
2617 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002618 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002619 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002620
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002621 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002622 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002623 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002624 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002625 = CXXUnit->getSourceManager().getLocation(File, line, column);
2626 if (SLoc.isInvalid()) {
2627 if (Logging)
2628 llvm::errs() << "clang_getLocation(\"" << File->getName()
2629 << "\", " << line << ", " << column << ") = invalid\n";
2630 return clang_getNullLocation();
2631 }
2632
2633 if (Logging)
2634 llvm::errs() << "clang_getLocation(\"" << File->getName()
2635 << "\", " << line << ", " << column << ") = "
2636 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002637
2638 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2639}
2640
2641CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2642 CXFile file,
2643 unsigned offset) {
2644 if (!tu || !file)
2645 return clang_getNullLocation();
2646
Ted Kremeneka60ed472010-11-16 08:15:36 +00002647 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002648 SourceLocation Start
2649 = CXXUnit->getSourceManager().getLocation(
2650 static_cast<const FileEntry *>(file),
2651 1, 1);
2652 if (Start.isInvalid()) return clang_getNullLocation();
2653
2654 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2655
2656 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002657
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002658 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002659}
2660
Douglas Gregor5352ac02010-01-28 00:27:43 +00002661CXSourceRange clang_getNullRange() {
2662 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2663 return Result;
2664}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002665
Douglas Gregor5352ac02010-01-28 00:27:43 +00002666CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2667 if (begin.ptr_data[0] != end.ptr_data[0] ||
2668 begin.ptr_data[1] != end.ptr_data[1])
2669 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002670
2671 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002672 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002673 return Result;
2674}
2675
Douglas Gregor46766dc2010-01-26 19:19:08 +00002676void clang_getInstantiationLocation(CXSourceLocation location,
2677 CXFile *file,
2678 unsigned *line,
2679 unsigned *column,
2680 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002681 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2682
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002683 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002684 if (file)
2685 *file = 0;
2686 if (line)
2687 *line = 0;
2688 if (column)
2689 *column = 0;
2690 if (offset)
2691 *offset = 0;
2692 return;
2693 }
2694
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002695 const SourceManager &SM =
2696 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002697 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002698
2699 if (file)
2700 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2701 if (line)
2702 *line = SM.getInstantiationLineNumber(InstLoc);
2703 if (column)
2704 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002705 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002706 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002707}
2708
Douglas Gregora9b06d42010-11-09 06:24:54 +00002709void clang_getSpellingLocation(CXSourceLocation location,
2710 CXFile *file,
2711 unsigned *line,
2712 unsigned *column,
2713 unsigned *offset) {
2714 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2715
2716 if (!location.ptr_data[0] || Loc.isInvalid()) {
2717 if (file)
2718 *file = 0;
2719 if (line)
2720 *line = 0;
2721 if (column)
2722 *column = 0;
2723 if (offset)
2724 *offset = 0;
2725 return;
2726 }
2727
2728 const SourceManager &SM =
2729 *static_cast<const SourceManager*>(location.ptr_data[0]);
2730 SourceLocation SpellLoc = Loc;
2731 if (SpellLoc.isMacroID()) {
2732 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2733 if (SimpleSpellingLoc.isFileID() &&
2734 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2735 SpellLoc = SimpleSpellingLoc;
2736 else
2737 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2738 }
2739
2740 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2741 FileID FID = LocInfo.first;
2742 unsigned FileOffset = LocInfo.second;
2743
2744 if (file)
2745 *file = (void *)SM.getFileEntryForID(FID);
2746 if (line)
2747 *line = SM.getLineNumber(FID, FileOffset);
2748 if (column)
2749 *column = SM.getColumnNumber(FID, FileOffset);
2750 if (offset)
2751 *offset = FileOffset;
2752}
2753
Douglas Gregor1db19de2010-01-19 21:36:55 +00002754CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002755 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002756 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002757 return Result;
2758}
2759
2760CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002761 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002762 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002763 return Result;
2764}
2765
Douglas Gregorb9790342010-01-22 21:44:22 +00002766} // end: extern "C"
2767
Douglas Gregor1db19de2010-01-19 21:36:55 +00002768//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002769// CXFile Operations.
2770//===----------------------------------------------------------------------===//
2771
2772extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002773CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002774 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002775 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002776
Steve Naroff88145032009-10-27 14:35:18 +00002777 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002778 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002779}
2780
2781time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002782 if (!SFile)
2783 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002784
Steve Naroff88145032009-10-27 14:35:18 +00002785 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2786 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002787}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002788
Douglas Gregorb9790342010-01-22 21:44:22 +00002789CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2790 if (!tu)
2791 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002792
Ted Kremeneka60ed472010-11-16 08:15:36 +00002793 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002794
Douglas Gregorb9790342010-01-22 21:44:22 +00002795 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002796 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002797}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002798
Ted Kremenekfb480492010-01-13 21:46:36 +00002799} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002800
Ted Kremenekfb480492010-01-13 21:46:36 +00002801//===----------------------------------------------------------------------===//
2802// CXCursor Operations.
2803//===----------------------------------------------------------------------===//
2804
Ted Kremenekfb480492010-01-13 21:46:36 +00002805static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002806 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2807 return getDeclFromExpr(CE->getSubExpr());
2808
Ted Kremenekfb480492010-01-13 21:46:36 +00002809 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2810 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002811 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2812 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002813 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2814 return ME->getMemberDecl();
2815 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2816 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002817 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002818 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002819
Ted Kremenekfb480492010-01-13 21:46:36 +00002820 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2821 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002822 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2823 if (!CE->isElidable())
2824 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002825 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2826 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002827
Douglas Gregordb1314e2010-10-01 21:11:22 +00002828 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2829 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002830 if (SubstNonTypeTemplateParmPackExpr *NTTP
2831 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2832 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002833 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2834 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2835 isa<ParmVarDecl>(SizeOfPack->getPack()))
2836 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002837
Ted Kremenekfb480492010-01-13 21:46:36 +00002838 return 0;
2839}
2840
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002841static SourceLocation getLocationFromExpr(Expr *E) {
2842 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2843 return /*FIXME:*/Msg->getLeftLoc();
2844 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2845 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002846 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2847 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002848 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2849 return Member->getMemberLoc();
2850 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2851 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002852 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2853 return SizeOfPack->getPackLoc();
2854
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002855 return E->getLocStart();
2856}
2857
Ted Kremenekfb480492010-01-13 21:46:36 +00002858extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002859
2860unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002861 CXCursorVisitor visitor,
2862 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002863 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2864 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002865 return CursorVis.VisitChildren(parent);
2866}
2867
David Chisnall3387c652010-11-03 14:12:26 +00002868#ifndef __has_feature
2869#define __has_feature(x) 0
2870#endif
2871#if __has_feature(blocks)
2872typedef enum CXChildVisitResult
2873 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2874
2875static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2876 CXClientData client_data) {
2877 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2878 return block(cursor, parent);
2879}
2880#else
2881// If we are compiled with a compiler that doesn't have native blocks support,
2882// define and call the block manually, so the
2883typedef struct _CXChildVisitResult
2884{
2885 void *isa;
2886 int flags;
2887 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002888 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2889 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002890} *CXCursorVisitorBlock;
2891
2892static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2893 CXClientData client_data) {
2894 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2895 return block->invoke(block, cursor, parent);
2896}
2897#endif
2898
2899
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002900unsigned clang_visitChildrenWithBlock(CXCursor parent,
2901 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002902 return clang_visitChildren(parent, visitWithBlock, block);
2903}
2904
Douglas Gregor78205d42010-01-20 21:45:58 +00002905static CXString getDeclSpelling(Decl *D) {
2906 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002907 if (!ND) {
2908 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2909 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2910 return createCXString(Property->getIdentifier()->getName());
2911
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002912 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002913 }
2914
Douglas Gregor78205d42010-01-20 21:45:58 +00002915 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002916 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002917
Douglas Gregor78205d42010-01-20 21:45:58 +00002918 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2919 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2920 // and returns different names. NamedDecl returns the class name and
2921 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002922 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002923
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002924 if (isa<UsingDirectiveDecl>(D))
2925 return createCXString("");
2926
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002927 llvm::SmallString<1024> S;
2928 llvm::raw_svector_ostream os(S);
2929 ND->printName(os);
2930
2931 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002932}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002933
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002934CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002935 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002936 return clang_getTranslationUnitSpelling(
2937 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002938
Steve Narofff334b4e2009-09-02 18:26:48 +00002939 if (clang_isReference(C.kind)) {
2940 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002941 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002942 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002943 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002944 }
2945 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002946 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002947 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002948 }
2949 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002950 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002951 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002952 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002953 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002954 case CXCursor_CXXBaseSpecifier: {
2955 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2956 return createCXString(B->getType().getAsString());
2957 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002958 case CXCursor_TypeRef: {
2959 TypeDecl *Type = getCursorTypeRef(C).first;
2960 assert(Type && "Missing type decl");
2961
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002962 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2963 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002964 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002965 case CXCursor_TemplateRef: {
2966 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002967 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002968
2969 return createCXString(Template->getNameAsString());
2970 }
Douglas Gregor69319002010-08-31 23:48:11 +00002971
2972 case CXCursor_NamespaceRef: {
2973 NamedDecl *NS = getCursorNamespaceRef(C).first;
2974 assert(NS && "Missing namespace decl");
2975
2976 return createCXString(NS->getNameAsString());
2977 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002978
Douglas Gregora67e03f2010-09-09 21:42:20 +00002979 case CXCursor_MemberRef: {
2980 FieldDecl *Field = getCursorMemberRef(C).first;
2981 assert(Field && "Missing member decl");
2982
2983 return createCXString(Field->getNameAsString());
2984 }
2985
Douglas Gregor36897b02010-09-10 00:22:18 +00002986 case CXCursor_LabelRef: {
2987 LabelStmt *Label = getCursorLabelRef(C).first;
2988 assert(Label && "Missing label");
2989
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002990 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002991 }
2992
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002993 case CXCursor_OverloadedDeclRef: {
2994 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2995 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2996 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2997 return createCXString(ND->getNameAsString());
2998 return createCXString("");
2999 }
3000 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3001 return createCXString(E->getName().getAsString());
3002 OverloadedTemplateStorage *Ovl
3003 = Storage.get<OverloadedTemplateStorage*>();
3004 if (Ovl->size() == 0)
3005 return createCXString("");
3006 return createCXString((*Ovl->begin())->getNameAsString());
3007 }
3008
Daniel Dunbaracca7252009-11-30 20:42:49 +00003009 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003010 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003011 }
3012 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003013
3014 if (clang_isExpression(C.kind)) {
3015 Decl *D = getDeclFromExpr(getCursorExpr(C));
3016 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003017 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003018 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003019 }
3020
Douglas Gregor36897b02010-09-10 00:22:18 +00003021 if (clang_isStatement(C.kind)) {
3022 Stmt *S = getCursorStmt(C);
3023 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003024 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003025
3026 return createCXString("");
3027 }
3028
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003029 if (C.kind == CXCursor_MacroInstantiation)
3030 return createCXString(getCursorMacroInstantiation(C)->getName()
3031 ->getNameStart());
3032
Douglas Gregor572feb22010-03-18 18:04:21 +00003033 if (C.kind == CXCursor_MacroDefinition)
3034 return createCXString(getCursorMacroDefinition(C)->getName()
3035 ->getNameStart());
3036
Douglas Gregorecdcb882010-10-20 22:00:55 +00003037 if (C.kind == CXCursor_InclusionDirective)
3038 return createCXString(getCursorInclusionDirective(C)->getFileName());
3039
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003040 if (clang_isDeclaration(C.kind))
3041 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003042
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003043 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003044}
3045
Douglas Gregor358559d2010-10-02 22:49:11 +00003046CXString clang_getCursorDisplayName(CXCursor C) {
3047 if (!clang_isDeclaration(C.kind))
3048 return clang_getCursorSpelling(C);
3049
3050 Decl *D = getCursorDecl(C);
3051 if (!D)
3052 return createCXString("");
3053
3054 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3055 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3056 D = FunTmpl->getTemplatedDecl();
3057
3058 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3059 llvm::SmallString<64> Str;
3060 llvm::raw_svector_ostream OS(Str);
3061 OS << Function->getNameAsString();
3062 if (Function->getPrimaryTemplate())
3063 OS << "<>";
3064 OS << "(";
3065 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3066 if (I)
3067 OS << ", ";
3068 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3069 }
3070
3071 if (Function->isVariadic()) {
3072 if (Function->getNumParams())
3073 OS << ", ";
3074 OS << "...";
3075 }
3076 OS << ")";
3077 return createCXString(OS.str());
3078 }
3079
3080 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3081 llvm::SmallString<64> Str;
3082 llvm::raw_svector_ostream OS(Str);
3083 OS << ClassTemplate->getNameAsString();
3084 OS << "<";
3085 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3086 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3087 if (I)
3088 OS << ", ";
3089
3090 NamedDecl *Param = Params->getParam(I);
3091 if (Param->getIdentifier()) {
3092 OS << Param->getIdentifier()->getName();
3093 continue;
3094 }
3095
3096 // There is no parameter name, which makes this tricky. Try to come up
3097 // with something useful that isn't too long.
3098 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3099 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3100 else if (NonTypeTemplateParmDecl *NTTP
3101 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3102 OS << NTTP->getType().getAsString(Policy);
3103 else
3104 OS << "template<...> class";
3105 }
3106
3107 OS << ">";
3108 return createCXString(OS.str());
3109 }
3110
3111 if (ClassTemplateSpecializationDecl *ClassSpec
3112 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3113 // If the type was explicitly written, use that.
3114 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3115 return createCXString(TSInfo->getType().getAsString(Policy));
3116
3117 llvm::SmallString<64> Str;
3118 llvm::raw_svector_ostream OS(Str);
3119 OS << ClassSpec->getNameAsString();
3120 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003121 ClassSpec->getTemplateArgs().data(),
3122 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003123 Policy);
3124 return createCXString(OS.str());
3125 }
3126
3127 return clang_getCursorSpelling(C);
3128}
3129
Ted Kremeneke68fff62010-02-17 00:41:32 +00003130CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003131 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003132 case CXCursor_FunctionDecl:
3133 return createCXString("FunctionDecl");
3134 case CXCursor_TypedefDecl:
3135 return createCXString("TypedefDecl");
3136 case CXCursor_EnumDecl:
3137 return createCXString("EnumDecl");
3138 case CXCursor_EnumConstantDecl:
3139 return createCXString("EnumConstantDecl");
3140 case CXCursor_StructDecl:
3141 return createCXString("StructDecl");
3142 case CXCursor_UnionDecl:
3143 return createCXString("UnionDecl");
3144 case CXCursor_ClassDecl:
3145 return createCXString("ClassDecl");
3146 case CXCursor_FieldDecl:
3147 return createCXString("FieldDecl");
3148 case CXCursor_VarDecl:
3149 return createCXString("VarDecl");
3150 case CXCursor_ParmDecl:
3151 return createCXString("ParmDecl");
3152 case CXCursor_ObjCInterfaceDecl:
3153 return createCXString("ObjCInterfaceDecl");
3154 case CXCursor_ObjCCategoryDecl:
3155 return createCXString("ObjCCategoryDecl");
3156 case CXCursor_ObjCProtocolDecl:
3157 return createCXString("ObjCProtocolDecl");
3158 case CXCursor_ObjCPropertyDecl:
3159 return createCXString("ObjCPropertyDecl");
3160 case CXCursor_ObjCIvarDecl:
3161 return createCXString("ObjCIvarDecl");
3162 case CXCursor_ObjCInstanceMethodDecl:
3163 return createCXString("ObjCInstanceMethodDecl");
3164 case CXCursor_ObjCClassMethodDecl:
3165 return createCXString("ObjCClassMethodDecl");
3166 case CXCursor_ObjCImplementationDecl:
3167 return createCXString("ObjCImplementationDecl");
3168 case CXCursor_ObjCCategoryImplDecl:
3169 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003170 case CXCursor_CXXMethod:
3171 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003172 case CXCursor_UnexposedDecl:
3173 return createCXString("UnexposedDecl");
3174 case CXCursor_ObjCSuperClassRef:
3175 return createCXString("ObjCSuperClassRef");
3176 case CXCursor_ObjCProtocolRef:
3177 return createCXString("ObjCProtocolRef");
3178 case CXCursor_ObjCClassRef:
3179 return createCXString("ObjCClassRef");
3180 case CXCursor_TypeRef:
3181 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003182 case CXCursor_TemplateRef:
3183 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003184 case CXCursor_NamespaceRef:
3185 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003186 case CXCursor_MemberRef:
3187 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003188 case CXCursor_LabelRef:
3189 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003190 case CXCursor_OverloadedDeclRef:
3191 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003192 case CXCursor_UnexposedExpr:
3193 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003194 case CXCursor_BlockExpr:
3195 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003196 case CXCursor_DeclRefExpr:
3197 return createCXString("DeclRefExpr");
3198 case CXCursor_MemberRefExpr:
3199 return createCXString("MemberRefExpr");
3200 case CXCursor_CallExpr:
3201 return createCXString("CallExpr");
3202 case CXCursor_ObjCMessageExpr:
3203 return createCXString("ObjCMessageExpr");
3204 case CXCursor_UnexposedStmt:
3205 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003206 case CXCursor_LabelStmt:
3207 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003208 case CXCursor_InvalidFile:
3209 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003210 case CXCursor_InvalidCode:
3211 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003212 case CXCursor_NoDeclFound:
3213 return createCXString("NoDeclFound");
3214 case CXCursor_NotImplemented:
3215 return createCXString("NotImplemented");
3216 case CXCursor_TranslationUnit:
3217 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003218 case CXCursor_UnexposedAttr:
3219 return createCXString("UnexposedAttr");
3220 case CXCursor_IBActionAttr:
3221 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003222 case CXCursor_IBOutletAttr:
3223 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003224 case CXCursor_IBOutletCollectionAttr:
3225 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003226 case CXCursor_PreprocessingDirective:
3227 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003228 case CXCursor_MacroDefinition:
3229 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003230 case CXCursor_MacroInstantiation:
3231 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003232 case CXCursor_InclusionDirective:
3233 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003234 case CXCursor_Namespace:
3235 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003236 case CXCursor_LinkageSpec:
3237 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003238 case CXCursor_CXXBaseSpecifier:
3239 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003240 case CXCursor_Constructor:
3241 return createCXString("CXXConstructor");
3242 case CXCursor_Destructor:
3243 return createCXString("CXXDestructor");
3244 case CXCursor_ConversionFunction:
3245 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003246 case CXCursor_TemplateTypeParameter:
3247 return createCXString("TemplateTypeParameter");
3248 case CXCursor_NonTypeTemplateParameter:
3249 return createCXString("NonTypeTemplateParameter");
3250 case CXCursor_TemplateTemplateParameter:
3251 return createCXString("TemplateTemplateParameter");
3252 case CXCursor_FunctionTemplate:
3253 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003254 case CXCursor_ClassTemplate:
3255 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003256 case CXCursor_ClassTemplatePartialSpecialization:
3257 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003258 case CXCursor_NamespaceAlias:
3259 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003260 case CXCursor_UsingDirective:
3261 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003262 case CXCursor_UsingDeclaration:
3263 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003264 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003265
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003266 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003267 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003268}
Steve Naroff89922f82009-08-31 00:59:03 +00003269
Ted Kremeneke68fff62010-02-17 00:41:32 +00003270enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3271 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003272 CXClientData client_data) {
3273 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003274
3275 // If our current best cursor is the construction of a temporary object,
3276 // don't replace that cursor with a type reference, because we want
3277 // clang_getCursor() to point at the constructor.
3278 if (clang_isExpression(BestCursor->kind) &&
3279 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3280 cursor.kind == CXCursor_TypeRef)
3281 return CXChildVisit_Recurse;
3282
Douglas Gregor85fe1562010-12-10 07:23:11 +00003283 // Don't override a preprocessing cursor with another preprocessing
3284 // cursor; we want the outermost preprocessing cursor.
3285 if (clang_isPreprocessing(cursor.kind) &&
3286 clang_isPreprocessing(BestCursor->kind))
3287 return CXChildVisit_Recurse;
3288
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003289 *BestCursor = cursor;
3290 return CXChildVisit_Recurse;
3291}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003292
Douglas Gregorb9790342010-01-22 21:44:22 +00003293CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3294 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003295 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003296
Ted Kremeneka60ed472010-11-16 08:15:36 +00003297 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003298 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3299
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003300 // Translate the given source location to make it point at the beginning of
3301 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003302 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003303
3304 // Guard against an invalid SourceLocation, or we may assert in one
3305 // of the following calls.
3306 if (SLoc.isInvalid())
3307 return clang_getNullCursor();
3308
Douglas Gregor40749ee2010-11-03 00:35:38 +00003309 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003310 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3311 CXXUnit->getASTContext().getLangOptions());
3312
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003313 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3314 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003315 // FIXME: Would be great to have a "hint" cursor, then walk from that
3316 // hint cursor upward until we find a cursor whose source range encloses
3317 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003318 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3319 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003320 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003321 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003322 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003323
3324 if (Logging) {
3325 CXFile SearchFile;
3326 unsigned SearchLine, SearchColumn;
3327 CXFile ResultFile;
3328 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003329 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3330 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003331 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3332
3333 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3334 0);
3335 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3336 &ResultColumn, 0);
3337 SearchFileName = clang_getFileName(SearchFile);
3338 ResultFileName = clang_getFileName(ResultFile);
3339 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003340 USR = clang_getCursorUSR(Result);
3341 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003342 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3343 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003344 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3345 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003346 clang_disposeString(SearchFileName);
3347 clang_disposeString(ResultFileName);
3348 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003349 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003350
3351 CXCursor Definition = clang_getCursorDefinition(Result);
3352 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3353 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3354 CXString DefinitionKindSpelling
3355 = clang_getCursorKindSpelling(Definition.kind);
3356 CXFile DefinitionFile;
3357 unsigned DefinitionLine, DefinitionColumn;
3358 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3359 &DefinitionLine, &DefinitionColumn, 0);
3360 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3361 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3362 clang_getCString(DefinitionKindSpelling),
3363 clang_getCString(DefinitionFileName),
3364 DefinitionLine, DefinitionColumn);
3365 clang_disposeString(DefinitionFileName);
3366 clang_disposeString(DefinitionKindSpelling);
3367 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003368 }
3369
Ted Kremeneke68fff62010-02-17 00:41:32 +00003370 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003371}
3372
Ted Kremenek73885552009-11-17 19:28:59 +00003373CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003374 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003375}
3376
3377unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003378 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003379}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003380
Douglas Gregor9ce55842010-11-20 00:09:34 +00003381unsigned clang_hashCursor(CXCursor C) {
3382 unsigned Index = 0;
3383 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3384 Index = 1;
3385
3386 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3387 std::make_pair(C.kind, C.data[Index]));
3388}
3389
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003390unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003391 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3392}
3393
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003394unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003395 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3396}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003397
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003398unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003399 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3400}
3401
Douglas Gregor97b98722010-01-19 23:20:36 +00003402unsigned clang_isExpression(enum CXCursorKind K) {
3403 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3404}
3405
3406unsigned clang_isStatement(enum CXCursorKind K) {
3407 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3408}
3409
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003410unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3411 return K == CXCursor_TranslationUnit;
3412}
3413
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003414unsigned clang_isPreprocessing(enum CXCursorKind K) {
3415 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3416}
3417
Ted Kremenekad6eff62010-03-08 21:17:29 +00003418unsigned clang_isUnexposed(enum CXCursorKind K) {
3419 switch (K) {
3420 case CXCursor_UnexposedDecl:
3421 case CXCursor_UnexposedExpr:
3422 case CXCursor_UnexposedStmt:
3423 case CXCursor_UnexposedAttr:
3424 return true;
3425 default:
3426 return false;
3427 }
3428}
3429
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003430CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003431 return C.kind;
3432}
3433
Douglas Gregor98258af2010-01-18 22:46:11 +00003434CXSourceLocation clang_getCursorLocation(CXCursor C) {
3435 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003436 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003437 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003438 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3439 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003440 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003441 }
3442
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003443 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003444 std::pair<ObjCProtocolDecl *, SourceLocation> P
3445 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003446 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003447 }
3448
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003449 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003450 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3451 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003452 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003453 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003454
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003455 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003456 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003457 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003458 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003459
3460 case CXCursor_TemplateRef: {
3461 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3462 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3463 }
3464
Douglas Gregor69319002010-08-31 23:48:11 +00003465 case CXCursor_NamespaceRef: {
3466 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3467 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3468 }
3469
Douglas Gregora67e03f2010-09-09 21:42:20 +00003470 case CXCursor_MemberRef: {
3471 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3472 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3473 }
3474
Ted Kremenek3064ef92010-08-27 21:34:58 +00003475 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003476 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3477 if (!BaseSpec)
3478 return clang_getNullLocation();
3479
3480 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3481 return cxloc::translateSourceLocation(getCursorContext(C),
3482 TSInfo->getTypeLoc().getBeginLoc());
3483
3484 return cxloc::translateSourceLocation(getCursorContext(C),
3485 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003487
Douglas Gregor36897b02010-09-10 00:22:18 +00003488 case CXCursor_LabelRef: {
3489 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3490 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3491 }
3492
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003493 case CXCursor_OverloadedDeclRef:
3494 return cxloc::translateSourceLocation(getCursorContext(C),
3495 getCursorOverloadedDeclRef(C).second);
3496
Douglas Gregorf46034a2010-01-18 23:41:10 +00003497 default:
3498 // FIXME: Need a way to enumerate all non-reference cases.
3499 llvm_unreachable("Missed a reference kind");
3500 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003501 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003502
3503 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003504 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003505 getLocationFromExpr(getCursorExpr(C)));
3506
Douglas Gregor36897b02010-09-10 00:22:18 +00003507 if (clang_isStatement(C.kind))
3508 return cxloc::translateSourceLocation(getCursorContext(C),
3509 getCursorStmt(C)->getLocStart());
3510
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003511 if (C.kind == CXCursor_PreprocessingDirective) {
3512 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3513 return cxloc::translateSourceLocation(getCursorContext(C), L);
3514 }
Douglas Gregor48072312010-03-18 15:23:44 +00003515
3516 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003517 SourceLocation L
3518 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003519 return cxloc::translateSourceLocation(getCursorContext(C), L);
3520 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003521
3522 if (C.kind == CXCursor_MacroDefinition) {
3523 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3524 return cxloc::translateSourceLocation(getCursorContext(C), L);
3525 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003526
3527 if (C.kind == CXCursor_InclusionDirective) {
3528 SourceLocation L
3529 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3530 return cxloc::translateSourceLocation(getCursorContext(C), L);
3531 }
3532
Ted Kremenek9a700d22010-05-12 06:16:13 +00003533 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003534 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003535
Douglas Gregorf46034a2010-01-18 23:41:10 +00003536 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003537 SourceLocation Loc = D->getLocation();
3538 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3539 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003540 // FIXME: Multiple variables declared in a single declaration
3541 // currently lack the information needed to correctly determine their
3542 // ranges when accounting for the type-specifier. We use context
3543 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3544 // and if so, whether it is the first decl.
3545 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3546 if (!cxcursor::isFirstInDeclGroup(C))
3547 Loc = VD->getLocation();
3548 }
3549
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003550 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003551}
Douglas Gregora7bde202010-01-19 00:34:46 +00003552
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003553} // end extern "C"
3554
3555static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003556 if (clang_isReference(C.kind)) {
3557 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003558 case CXCursor_ObjCSuperClassRef:
3559 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003560
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003561 case CXCursor_ObjCProtocolRef:
3562 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003563
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003564 case CXCursor_ObjCClassRef:
3565 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003566
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003567 case CXCursor_TypeRef:
3568 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003569
3570 case CXCursor_TemplateRef:
3571 return getCursorTemplateRef(C).second;
3572
Douglas Gregor69319002010-08-31 23:48:11 +00003573 case CXCursor_NamespaceRef:
3574 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003575
3576 case CXCursor_MemberRef:
3577 return getCursorMemberRef(C).second;
3578
Ted Kremenek3064ef92010-08-27 21:34:58 +00003579 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003580 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003581
Douglas Gregor36897b02010-09-10 00:22:18 +00003582 case CXCursor_LabelRef:
3583 return getCursorLabelRef(C).second;
3584
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003585 case CXCursor_OverloadedDeclRef:
3586 return getCursorOverloadedDeclRef(C).second;
3587
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003588 default:
3589 // FIXME: Need a way to enumerate all non-reference cases.
3590 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003591 }
3592 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003593
3594 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003595 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003596
3597 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003598 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003599
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003600 if (C.kind == CXCursor_PreprocessingDirective)
3601 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003602
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003603 if (C.kind == CXCursor_MacroInstantiation)
3604 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003605
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003606 if (C.kind == CXCursor_MacroDefinition)
3607 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003608
3609 if (C.kind == CXCursor_InclusionDirective)
3610 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3611
Ted Kremenek007a7c92010-11-01 23:26:51 +00003612 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3613 Decl *D = cxcursor::getCursorDecl(C);
3614 SourceRange R = D->getSourceRange();
3615 // FIXME: Multiple variables declared in a single declaration
3616 // currently lack the information needed to correctly determine their
3617 // ranges when accounting for the type-specifier. We use context
3618 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3619 // and if so, whether it is the first decl.
3620 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3621 if (!cxcursor::isFirstInDeclGroup(C))
3622 R.setBegin(VD->getLocation());
3623 }
3624 return R;
3625 }
Douglas Gregor66537982010-11-17 17:14:07 +00003626 return SourceRange();
3627}
3628
3629/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3630/// the decl-specifier-seq for declarations.
3631static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3632 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3633 Decl *D = cxcursor::getCursorDecl(C);
3634 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003635
Douglas Gregor2494dd02011-03-01 01:34:45 +00003636 // Adjust the start of the location for declarations preceded by
3637 // declaration specifiers.
3638 SourceLocation StartLoc;
3639 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3640 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3641 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3642 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3643 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3644 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3645 }
3646
3647 if (StartLoc.isValid() && R.getBegin().isValid() &&
3648 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3649 R.setBegin(StartLoc);
3650
3651 // FIXME: Multiple variables declared in a single declaration
3652 // currently lack the information needed to correctly determine their
3653 // ranges when accounting for the type-specifier. We use context
3654 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3655 // and if so, whether it is the first decl.
3656 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3657 if (!cxcursor::isFirstInDeclGroup(C))
3658 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003659 }
3660
3661 return R;
3662 }
3663
3664 return getRawCursorExtent(C);
3665}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003666
3667extern "C" {
3668
3669CXSourceRange clang_getCursorExtent(CXCursor C) {
3670 SourceRange R = getRawCursorExtent(C);
3671 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003672 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003673
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003674 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003675}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003676
3677CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003678 if (clang_isInvalid(C.kind))
3679 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003680
Ted Kremeneka60ed472010-11-16 08:15:36 +00003681 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003682 if (clang_isDeclaration(C.kind)) {
3683 Decl *D = getCursorDecl(C);
3684 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003685 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003686 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003687 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003688 if (ObjCForwardProtocolDecl *Protocols
3689 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003690 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003691 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3692 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3693 return MakeCXCursor(Property, tu);
3694
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003695 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003696 }
3697
Douglas Gregor97b98722010-01-19 23:20:36 +00003698 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003699 Expr *E = getCursorExpr(C);
3700 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003701 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003702 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003703
3704 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003705 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003706
Douglas Gregor97b98722010-01-19 23:20:36 +00003707 return clang_getNullCursor();
3708 }
3709
Douglas Gregor36897b02010-09-10 00:22:18 +00003710 if (clang_isStatement(C.kind)) {
3711 Stmt *S = getCursorStmt(C);
3712 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003713 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003714
3715 return clang_getNullCursor();
3716 }
3717
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003718 if (C.kind == CXCursor_MacroInstantiation) {
3719 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003720 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003721 }
3722
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003723 if (!clang_isReference(C.kind))
3724 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003725
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003726 switch (C.kind) {
3727 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003728 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003729
3730 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003731 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003732
3733 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003734 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003735
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003736 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003737 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003738
3739 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003740 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003741
Douglas Gregor69319002010-08-31 23:48:11 +00003742 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003743 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003744
Douglas Gregora67e03f2010-09-09 21:42:20 +00003745 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003746 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003747
Ted Kremenek3064ef92010-08-27 21:34:58 +00003748 case CXCursor_CXXBaseSpecifier: {
3749 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3750 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003751 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003752 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003753
Douglas Gregor36897b02010-09-10 00:22:18 +00003754 case CXCursor_LabelRef:
3755 // FIXME: We end up faking the "parent" declaration here because we
3756 // don't want to make CXCursor larger.
3757 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003758 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3759 .getTranslationUnitDecl(),
3760 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003761
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003762 case CXCursor_OverloadedDeclRef:
3763 return C;
3764
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003765 default:
3766 // We would prefer to enumerate all non-reference cursor kinds here.
3767 llvm_unreachable("Unhandled reference cursor kind");
3768 break;
3769 }
3770 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003771
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003772 return clang_getNullCursor();
3773}
3774
Douglas Gregorb6998662010-01-19 19:34:47 +00003775CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003776 if (clang_isInvalid(C.kind))
3777 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003778
Ted Kremeneka60ed472010-11-16 08:15:36 +00003779 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003780
Douglas Gregorb6998662010-01-19 19:34:47 +00003781 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003782 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003783 C = clang_getCursorReferenced(C);
3784 WasReference = true;
3785 }
3786
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003787 if (C.kind == CXCursor_MacroInstantiation)
3788 return clang_getCursorReferenced(C);
3789
Douglas Gregorb6998662010-01-19 19:34:47 +00003790 if (!clang_isDeclaration(C.kind))
3791 return clang_getNullCursor();
3792
3793 Decl *D = getCursorDecl(C);
3794 if (!D)
3795 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003796
Douglas Gregorb6998662010-01-19 19:34:47 +00003797 switch (D->getKind()) {
3798 // Declaration kinds that don't really separate the notions of
3799 // declaration and definition.
3800 case Decl::Namespace:
3801 case Decl::Typedef:
3802 case Decl::TemplateTypeParm:
3803 case Decl::EnumConstant:
3804 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003805 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003806 case Decl::ObjCIvar:
3807 case Decl::ObjCAtDefsField:
3808 case Decl::ImplicitParam:
3809 case Decl::ParmVar:
3810 case Decl::NonTypeTemplateParm:
3811 case Decl::TemplateTemplateParm:
3812 case Decl::ObjCCategoryImpl:
3813 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003814 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003815 case Decl::LinkageSpec:
3816 case Decl::ObjCPropertyImpl:
3817 case Decl::FileScopeAsm:
3818 case Decl::StaticAssert:
3819 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003820 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003821 return C;
3822
3823 // Declaration kinds that don't make any sense here, but are
3824 // nonetheless harmless.
3825 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003826 break;
3827
3828 // Declaration kinds for which the definition is not resolvable.
3829 case Decl::UnresolvedUsingTypename:
3830 case Decl::UnresolvedUsingValue:
3831 break;
3832
3833 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003834 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003835 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003836
3837 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003838 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003839
3840 case Decl::Enum:
3841 case Decl::Record:
3842 case Decl::CXXRecord:
3843 case Decl::ClassTemplateSpecialization:
3844 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003845 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003846 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003847 return clang_getNullCursor();
3848
3849 case Decl::Function:
3850 case Decl::CXXMethod:
3851 case Decl::CXXConstructor:
3852 case Decl::CXXDestructor:
3853 case Decl::CXXConversion: {
3854 const FunctionDecl *Def = 0;
3855 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003856 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003857 return clang_getNullCursor();
3858 }
3859
3860 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003861 // Ask the variable if it has a definition.
3862 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003863 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003864 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003865 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003866
Douglas Gregorb6998662010-01-19 19:34:47 +00003867 case Decl::FunctionTemplate: {
3868 const FunctionDecl *Def = 0;
3869 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003870 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003871 return clang_getNullCursor();
3872 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003873
Douglas Gregorb6998662010-01-19 19:34:47 +00003874 case Decl::ClassTemplate: {
3875 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003876 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003877 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003878 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003879 return clang_getNullCursor();
3880 }
3881
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003882 case Decl::Using:
3883 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003884 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003885
3886 case Decl::UsingShadow:
3887 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003888 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003889 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003890
3891 case Decl::ObjCMethod: {
3892 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3893 if (Method->isThisDeclarationADefinition())
3894 return C;
3895
3896 // Dig out the method definition in the associated
3897 // @implementation, if we have it.
3898 // FIXME: The ASTs should make finding the definition easier.
3899 if (ObjCInterfaceDecl *Class
3900 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3901 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3902 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3903 Method->isInstanceMethod()))
3904 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003905 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003906
3907 return clang_getNullCursor();
3908 }
3909
3910 case Decl::ObjCCategory:
3911 if (ObjCCategoryImplDecl *Impl
3912 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003913 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003914 return clang_getNullCursor();
3915
3916 case Decl::ObjCProtocol:
3917 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3918 return C;
3919 return clang_getNullCursor();
3920
3921 case Decl::ObjCInterface:
3922 // There are two notions of a "definition" for an Objective-C
3923 // class: the interface and its implementation. When we resolved a
3924 // reference to an Objective-C class, produce the @interface as
3925 // the definition; when we were provided with the interface,
3926 // produce the @implementation as the definition.
3927 if (WasReference) {
3928 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3929 return C;
3930 } else if (ObjCImplementationDecl *Impl
3931 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003932 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003933 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003934
Douglas Gregorb6998662010-01-19 19:34:47 +00003935 case Decl::ObjCProperty:
3936 // FIXME: We don't really know where to find the
3937 // ObjCPropertyImplDecls that implement this property.
3938 return clang_getNullCursor();
3939
3940 case Decl::ObjCCompatibleAlias:
3941 if (ObjCInterfaceDecl *Class
3942 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3943 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003944 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003945
Douglas Gregorb6998662010-01-19 19:34:47 +00003946 return clang_getNullCursor();
3947
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003948 case Decl::ObjCForwardProtocol:
3949 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003950 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003951
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003952 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003953 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003954 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003955
3956 case Decl::Friend:
3957 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003958 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003959 return clang_getNullCursor();
3960
3961 case Decl::FriendTemplate:
3962 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003963 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003964 return clang_getNullCursor();
3965 }
3966
3967 return clang_getNullCursor();
3968}
3969
3970unsigned clang_isCursorDefinition(CXCursor C) {
3971 if (!clang_isDeclaration(C.kind))
3972 return 0;
3973
3974 return clang_getCursorDefinition(C) == C;
3975}
3976
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003977CXCursor clang_getCanonicalCursor(CXCursor C) {
3978 if (!clang_isDeclaration(C.kind))
3979 return C;
3980
3981 if (Decl *D = getCursorDecl(C))
3982 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3983
3984 return C;
3985}
3986
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003987unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003988 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003989 return 0;
3990
3991 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3992 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3993 return E->getNumDecls();
3994
3995 if (OverloadedTemplateStorage *S
3996 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3997 return S->size();
3998
3999 Decl *D = Storage.get<Decl*>();
4000 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004001 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004002 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4003 return Classes->size();
4004 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4005 return Protocols->protocol_size();
4006
4007 return 0;
4008}
4009
4010CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004011 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004012 return clang_getNullCursor();
4013
4014 if (index >= clang_getNumOverloadedDecls(cursor))
4015 return clang_getNullCursor();
4016
Ted Kremeneka60ed472010-11-16 08:15:36 +00004017 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004018 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4019 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004020 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004021
4022 if (OverloadedTemplateStorage *S
4023 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004024 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004025
4026 Decl *D = Storage.get<Decl*>();
4027 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4028 // FIXME: This is, unfortunately, linear time.
4029 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4030 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004031 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004032 }
4033
4034 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004035 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004036
4037 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004038 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004039
4040 return clang_getNullCursor();
4041}
4042
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004043void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004044 const char **startBuf,
4045 const char **endBuf,
4046 unsigned *startLine,
4047 unsigned *startColumn,
4048 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004049 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004050 assert(getCursorDecl(C) && "CXCursor has null decl");
4051 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004052 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4053 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004054
Steve Naroff4ade6d62009-09-23 17:52:52 +00004055 SourceManager &SM = FD->getASTContext().getSourceManager();
4056 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4057 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4058 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4059 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4060 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4061 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4062}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004063
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004064void clang_enableStackTraces(void) {
4065 llvm::sys::PrintStackTraceOnErrorSignal();
4066}
4067
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004068void clang_executeOnThread(void (*fn)(void*), void *user_data,
4069 unsigned stack_size) {
4070 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4071}
4072
Ted Kremenekfb480492010-01-13 21:46:36 +00004073} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004074
Ted Kremenekfb480492010-01-13 21:46:36 +00004075//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004076// Token-based Operations.
4077//===----------------------------------------------------------------------===//
4078
4079/* CXToken layout:
4080 * int_data[0]: a CXTokenKind
4081 * int_data[1]: starting token location
4082 * int_data[2]: token length
4083 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004084 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004085 * otherwise unused.
4086 */
4087extern "C" {
4088
4089CXTokenKind clang_getTokenKind(CXToken CXTok) {
4090 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4091}
4092
4093CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4094 switch (clang_getTokenKind(CXTok)) {
4095 case CXToken_Identifier:
4096 case CXToken_Keyword:
4097 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004098 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4099 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004100
4101 case CXToken_Literal: {
4102 // We have stashed the starting pointer in the ptr_data field. Use it.
4103 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004104 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004105 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004106
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004107 case CXToken_Punctuation:
4108 case CXToken_Comment:
4109 break;
4110 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004111
4112 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004113 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004115 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004116 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004117
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004118 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4119 std::pair<FileID, unsigned> LocInfo
4120 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004121 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004122 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004123 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4124 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004125 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004126
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004127 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004128}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004129
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004130CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004131 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004132 if (!CXXUnit)
4133 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004134
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004135 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4136 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4137}
4138
4139CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004140 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004141 if (!CXXUnit)
4142 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004143
4144 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004145 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4146}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004147
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004148void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4149 CXToken **Tokens, unsigned *NumTokens) {
4150 if (Tokens)
4151 *Tokens = 0;
4152 if (NumTokens)
4153 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004154
Ted Kremeneka60ed472010-11-16 08:15:36 +00004155 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004156 if (!CXXUnit || !Tokens || !NumTokens)
4157 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004158
Douglas Gregorbdf60622010-03-05 21:16:25 +00004159 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4160
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004161 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004162 if (R.isInvalid())
4163 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004164
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004165 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4166 std::pair<FileID, unsigned> BeginLocInfo
4167 = SourceMgr.getDecomposedLoc(R.getBegin());
4168 std::pair<FileID, unsigned> EndLocInfo
4169 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004170
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004171 // Cannot tokenize across files.
4172 if (BeginLocInfo.first != EndLocInfo.first)
4173 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004174
4175 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004176 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004177 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004178 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004179 if (Invalid)
4180 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004181
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004182 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4183 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004184 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004185 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004186
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004187 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004188 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004189 llvm::SmallVector<CXToken, 32> CXTokens;
4190 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004191 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004192 do {
4193 // Lex the next token
4194 Lex.LexFromRawLexer(Tok);
4195 if (Tok.is(tok::eof))
4196 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004197
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004198 // Initialize the CXToken.
4199 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004200
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004201 // - Common fields
4202 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4203 CXTok.int_data[2] = Tok.getLength();
4204 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004205
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004206 // - Kind-specific fields
4207 if (Tok.isLiteral()) {
4208 CXTok.int_data[0] = CXToken_Literal;
4209 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004210 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004211 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004212 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004213 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004214
David Chisnall096428b2010-10-13 21:44:48 +00004215 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004216 CXTok.int_data[0] = CXToken_Keyword;
4217 }
4218 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004219 CXTok.int_data[0] = Tok.is(tok::identifier)
4220 ? CXToken_Identifier
4221 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004222 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004223 CXTok.ptr_data = II;
4224 } else if (Tok.is(tok::comment)) {
4225 CXTok.int_data[0] = CXToken_Comment;
4226 CXTok.ptr_data = 0;
4227 } else {
4228 CXTok.int_data[0] = CXToken_Punctuation;
4229 CXTok.ptr_data = 0;
4230 }
4231 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004232 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004233 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004234
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004235 if (CXTokens.empty())
4236 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004237
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004238 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4239 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4240 *NumTokens = CXTokens.size();
4241}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004242
Ted Kremenek6db61092010-05-05 00:55:15 +00004243void clang_disposeTokens(CXTranslationUnit TU,
4244 CXToken *Tokens, unsigned NumTokens) {
4245 free(Tokens);
4246}
4247
4248} // end: extern "C"
4249
4250//===----------------------------------------------------------------------===//
4251// Token annotation APIs.
4252//===----------------------------------------------------------------------===//
4253
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004254typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004255static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4256 CXCursor parent,
4257 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004258namespace {
4259class AnnotateTokensWorker {
4260 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004261 CXToken *Tokens;
4262 CXCursor *Cursors;
4263 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004264 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004265 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004266 CursorVisitor AnnotateVis;
4267 SourceManager &SrcMgr;
4268
4269 bool MoreTokens() const { return TokIdx < NumTokens; }
4270 unsigned NextToken() const { return TokIdx; }
4271 void AdvanceToken() { ++TokIdx; }
4272 SourceLocation GetTokenLoc(unsigned tokI) {
4273 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4274 }
4275
Ted Kremenek6db61092010-05-05 00:55:15 +00004276public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004277 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004278 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004279 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004280 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004281 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004282 AnnotateVis(tu,
4283 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004284 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004285 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004286
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004287 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004288 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004289 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004290 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004291 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004292 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004293};
4294}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004295
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004296void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4297 // Walk the AST within the region of interest, annotating tokens
4298 // along the way.
4299 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004300
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004301 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4302 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004303 if (Pos != Annotated.end() &&
4304 (clang_isInvalid(Cursors[I].kind) ||
4305 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004306 Cursors[I] = Pos->second;
4307 }
4308
4309 // Finish up annotating any tokens left.
4310 if (!MoreTokens())
4311 return;
4312
4313 const CXCursor &C = clang_getNullCursor();
4314 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4315 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4316 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004317 }
4318}
4319
Ted Kremenek6db61092010-05-05 00:55:15 +00004320enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004321AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004322 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004323 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004324 if (cursorRange.isInvalid())
4325 return CXChildVisit_Recurse;
4326
Douglas Gregor4419b672010-10-21 06:10:04 +00004327 if (clang_isPreprocessing(cursor.kind)) {
4328 // For macro instantiations, just note where the beginning of the macro
4329 // instantiation occurs.
4330 if (cursor.kind == CXCursor_MacroInstantiation) {
4331 Annotated[Loc.int_data] = cursor;
4332 return CXChildVisit_Recurse;
4333 }
4334
Douglas Gregor4419b672010-10-21 06:10:04 +00004335 // Items in the preprocessing record are kept separate from items in
4336 // declarations, so we keep a separate token index.
4337 unsigned SavedTokIdx = TokIdx;
4338 TokIdx = PreprocessingTokIdx;
4339
4340 // Skip tokens up until we catch up to the beginning of the preprocessing
4341 // entry.
4342 while (MoreTokens()) {
4343 const unsigned I = NextToken();
4344 SourceLocation TokLoc = GetTokenLoc(I);
4345 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4346 case RangeBefore:
4347 AdvanceToken();
4348 continue;
4349 case RangeAfter:
4350 case RangeOverlap:
4351 break;
4352 }
4353 break;
4354 }
4355
4356 // Look at all of the tokens within this range.
4357 while (MoreTokens()) {
4358 const unsigned I = NextToken();
4359 SourceLocation TokLoc = GetTokenLoc(I);
4360 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4361 case RangeBefore:
4362 assert(0 && "Infeasible");
4363 case RangeAfter:
4364 break;
4365 case RangeOverlap:
4366 Cursors[I] = cursor;
4367 AdvanceToken();
4368 continue;
4369 }
4370 break;
4371 }
4372
4373 // Save the preprocessing token index; restore the non-preprocessing
4374 // token index.
4375 PreprocessingTokIdx = TokIdx;
4376 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004377 return CXChildVisit_Recurse;
4378 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004379
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004380 if (cursorRange.isInvalid())
4381 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004382
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004383 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4384
Ted Kremeneka333c662010-05-12 05:29:33 +00004385 // Adjust the annotated range based specific declarations.
4386 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4387 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004388 Decl *D = cxcursor::getCursorDecl(cursor);
4389 // Don't visit synthesized ObjC methods, since they have no syntatic
4390 // representation in the source.
4391 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4392 if (MD->isSynthesized())
4393 return CXChildVisit_Continue;
4394 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004395
4396 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004397 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004398 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4399 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4400 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4401 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4402 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004403 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004404
4405 if (StartLoc.isValid() && L.isValid() &&
4406 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4407 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004408 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004409
Ted Kremenek3f404602010-08-14 01:14:06 +00004410 // If the location of the cursor occurs within a macro instantiation, record
4411 // the spelling location of the cursor in our annotation map. We can then
4412 // paper over the token labelings during a post-processing step to try and
4413 // get cursor mappings for tokens that are the *arguments* of a macro
4414 // instantiation.
4415 if (L.isMacroID()) {
4416 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4417 // Only invalidate the old annotation if it isn't part of a preprocessing
4418 // directive. Here we assume that the default construction of CXCursor
4419 // results in CXCursor.kind being an initialized value (i.e., 0). If
4420 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004421
Ted Kremenek3f404602010-08-14 01:14:06 +00004422 CXCursor &oldC = Annotated[rawEncoding];
4423 if (!clang_isPreprocessing(oldC.kind))
4424 oldC = cursor;
4425 }
4426
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004427 const enum CXCursorKind K = clang_getCursorKind(parent);
4428 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004429 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4430 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004431
4432 while (MoreTokens()) {
4433 const unsigned I = NextToken();
4434 SourceLocation TokLoc = GetTokenLoc(I);
4435 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4436 case RangeBefore:
4437 Cursors[I] = updateC;
4438 AdvanceToken();
4439 continue;
4440 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004441 case RangeOverlap:
4442 break;
4443 }
4444 break;
4445 }
4446
4447 // Visit children to get their cursor information.
4448 const unsigned BeforeChildren = NextToken();
4449 VisitChildren(cursor);
4450 const unsigned AfterChildren = NextToken();
4451
4452 // Adjust 'Last' to the last token within the extent of the cursor.
4453 while (MoreTokens()) {
4454 const unsigned I = NextToken();
4455 SourceLocation TokLoc = GetTokenLoc(I);
4456 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4457 case RangeBefore:
4458 assert(0 && "Infeasible");
4459 case RangeAfter:
4460 break;
4461 case RangeOverlap:
4462 Cursors[I] = updateC;
4463 AdvanceToken();
4464 continue;
4465 }
4466 break;
4467 }
4468 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004469
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004470 // Scan the tokens that are at the beginning of the cursor, but are not
4471 // capture by the child cursors.
4472
4473 // For AST elements within macros, rely on a post-annotate pass to
4474 // to correctly annotate the tokens with cursors. Otherwise we can
4475 // get confusing results of having tokens that map to cursors that really
4476 // are expanded by an instantiation.
4477 if (L.isMacroID())
4478 cursor = clang_getNullCursor();
4479
4480 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4481 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4482 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004483
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004484 Cursors[I] = cursor;
4485 }
4486 // Scan the tokens that are at the end of the cursor, but are not captured
4487 // but the child cursors.
4488 for (unsigned I = AfterChildren; I != Last; ++I)
4489 Cursors[I] = cursor;
4490
4491 TokIdx = Last;
4492 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004493}
4494
Ted Kremenek6db61092010-05-05 00:55:15 +00004495static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4496 CXCursor parent,
4497 CXClientData client_data) {
4498 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4499}
4500
Ted Kremenekab979612010-11-11 08:05:23 +00004501// This gets run a separate thread to avoid stack blowout.
4502static void runAnnotateTokensWorker(void *UserData) {
4503 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4504}
4505
Ted Kremenek6db61092010-05-05 00:55:15 +00004506extern "C" {
4507
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004508void clang_annotateTokens(CXTranslationUnit TU,
4509 CXToken *Tokens, unsigned NumTokens,
4510 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004511
4512 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004513 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004514
Douglas Gregor4419b672010-10-21 06:10:04 +00004515 // Any token we don't specifically annotate will have a NULL cursor.
4516 CXCursor C = clang_getNullCursor();
4517 for (unsigned I = 0; I != NumTokens; ++I)
4518 Cursors[I] = C;
4519
Ted Kremeneka60ed472010-11-16 08:15:36 +00004520 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004521 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004522 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004523
Douglas Gregorbdf60622010-03-05 21:16:25 +00004524 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004525
Douglas Gregor0396f462010-03-19 05:22:59 +00004526 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004527 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004528 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4529 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004530 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4531 clang_getTokenLocation(TU,
4532 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004533
Douglas Gregor0396f462010-03-19 05:22:59 +00004534 // A mapping from the source locations found when re-lexing or traversing the
4535 // region of interest to the corresponding cursors.
4536 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004537
4538 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004539 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004540 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4541 std::pair<FileID, unsigned> BeginLocInfo
4542 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4543 std::pair<FileID, unsigned> EndLocInfo
4544 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004545
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004546 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004547 bool Invalid = false;
4548 if (BeginLocInfo.first == EndLocInfo.first &&
4549 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4550 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004551 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4552 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004553 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004554 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004555 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004556
4557 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004558 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004559 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004560 Token Tok;
4561 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004562
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004563 reprocess:
4564 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4565 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004566 // don't see it while preprocessing these tokens later, but keep track
4567 // of all of the token locations inside this preprocessing directive so
4568 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004569 //
4570 // FIXME: Some simple tests here could identify macro definitions and
4571 // #undefs, to provide specific cursor kinds for those.
4572 std::vector<SourceLocation> Locations;
4573 do {
4574 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004575 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004576 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004577
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004578 using namespace cxcursor;
4579 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004580 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4581 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004582 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004583 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4584 Annotated[Locations[I].getRawEncoding()] = Cursor;
4585 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004586
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004587 if (Tok.isAtStartOfLine())
4588 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004589
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004590 continue;
4591 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004592
Douglas Gregor48072312010-03-18 15:23:44 +00004593 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004594 break;
4595 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004596 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004597
Douglas Gregor0396f462010-03-19 05:22:59 +00004598 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004599 // a specific cursor.
4600 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004601 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004602
4603 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004604 // FIXME: We use a ridiculous stack size here because the data-recursion
4605 // algorithm uses a large stack frame than the non-data recursive version,
4606 // and AnnotationTokensWorker currently transforms the data-recursion
4607 // algorithm back into a traditional recursion by explicitly calling
4608 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004609 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004610 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4611 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004612 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4613 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004614}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004615} // end: extern "C"
4616
4617//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004618// Operations for querying linkage of a cursor.
4619//===----------------------------------------------------------------------===//
4620
4621extern "C" {
4622CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004623 if (!clang_isDeclaration(cursor.kind))
4624 return CXLinkage_Invalid;
4625
Ted Kremenek16b42592010-03-03 06:36:57 +00004626 Decl *D = cxcursor::getCursorDecl(cursor);
4627 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4628 switch (ND->getLinkage()) {
4629 case NoLinkage: return CXLinkage_NoLinkage;
4630 case InternalLinkage: return CXLinkage_Internal;
4631 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4632 case ExternalLinkage: return CXLinkage_External;
4633 };
4634
4635 return CXLinkage_Invalid;
4636}
4637} // end: extern "C"
4638
4639//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004640// Operations for querying language of a cursor.
4641//===----------------------------------------------------------------------===//
4642
4643static CXLanguageKind getDeclLanguage(const Decl *D) {
4644 switch (D->getKind()) {
4645 default:
4646 break;
4647 case Decl::ImplicitParam:
4648 case Decl::ObjCAtDefsField:
4649 case Decl::ObjCCategory:
4650 case Decl::ObjCCategoryImpl:
4651 case Decl::ObjCClass:
4652 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004653 case Decl::ObjCForwardProtocol:
4654 case Decl::ObjCImplementation:
4655 case Decl::ObjCInterface:
4656 case Decl::ObjCIvar:
4657 case Decl::ObjCMethod:
4658 case Decl::ObjCProperty:
4659 case Decl::ObjCPropertyImpl:
4660 case Decl::ObjCProtocol:
4661 return CXLanguage_ObjC;
4662 case Decl::CXXConstructor:
4663 case Decl::CXXConversion:
4664 case Decl::CXXDestructor:
4665 case Decl::CXXMethod:
4666 case Decl::CXXRecord:
4667 case Decl::ClassTemplate:
4668 case Decl::ClassTemplatePartialSpecialization:
4669 case Decl::ClassTemplateSpecialization:
4670 case Decl::Friend:
4671 case Decl::FriendTemplate:
4672 case Decl::FunctionTemplate:
4673 case Decl::LinkageSpec:
4674 case Decl::Namespace:
4675 case Decl::NamespaceAlias:
4676 case Decl::NonTypeTemplateParm:
4677 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004678 case Decl::TemplateTemplateParm:
4679 case Decl::TemplateTypeParm:
4680 case Decl::UnresolvedUsingTypename:
4681 case Decl::UnresolvedUsingValue:
4682 case Decl::Using:
4683 case Decl::UsingDirective:
4684 case Decl::UsingShadow:
4685 return CXLanguage_CPlusPlus;
4686 }
4687
4688 return CXLanguage_C;
4689}
4690
4691extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004692
4693enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4694 if (clang_isDeclaration(cursor.kind))
4695 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4696 if (D->hasAttr<UnavailableAttr>() ||
4697 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4698 return CXAvailability_Available;
4699
4700 if (D->hasAttr<DeprecatedAttr>())
4701 return CXAvailability_Deprecated;
4702 }
4703
4704 return CXAvailability_Available;
4705}
4706
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004707CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4708 if (clang_isDeclaration(cursor.kind))
4709 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4710
4711 return CXLanguage_Invalid;
4712}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004713
4714 /// \brief If the given cursor is the "templated" declaration
4715 /// descibing a class or function template, return the class or
4716 /// function template.
4717static Decl *maybeGetTemplateCursor(Decl *D) {
4718 if (!D)
4719 return 0;
4720
4721 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4722 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4723 return FunTmpl;
4724
4725 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4726 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4727 return ClassTmpl;
4728
4729 return D;
4730}
4731
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004732CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4733 if (clang_isDeclaration(cursor.kind)) {
4734 if (Decl *D = getCursorDecl(cursor)) {
4735 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004736 if (!DC)
4737 return clang_getNullCursor();
4738
4739 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4740 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004741 }
4742 }
4743
4744 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4745 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004746 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004747 }
4748
4749 return clang_getNullCursor();
4750}
4751
4752CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4753 if (clang_isDeclaration(cursor.kind)) {
4754 if (Decl *D = getCursorDecl(cursor)) {
4755 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004756 if (!DC)
4757 return clang_getNullCursor();
4758
4759 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4760 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004761 }
4762 }
4763
4764 // FIXME: Note that we can't easily compute the lexical context of a
4765 // statement or expression, so we return nothing.
4766 return clang_getNullCursor();
4767}
4768
Douglas Gregor9f592342010-10-01 20:25:15 +00004769static void CollectOverriddenMethods(DeclContext *Ctx,
4770 ObjCMethodDecl *Method,
4771 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4772 if (!Ctx)
4773 return;
4774
4775 // If we have a class or category implementation, jump straight to the
4776 // interface.
4777 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4778 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4779
4780 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4781 if (!Container)
4782 return;
4783
4784 // Check whether we have a matching method at this level.
4785 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4786 Method->isInstanceMethod()))
4787 if (Method != Overridden) {
4788 // We found an override at this level; there is no need to look
4789 // into other protocols or categories.
4790 Methods.push_back(Overridden);
4791 return;
4792 }
4793
4794 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4795 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4796 PEnd = Protocol->protocol_end();
4797 P != PEnd; ++P)
4798 CollectOverriddenMethods(*P, Method, Methods);
4799 }
4800
4801 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4802 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4803 PEnd = Category->protocol_end();
4804 P != PEnd; ++P)
4805 CollectOverriddenMethods(*P, Method, Methods);
4806 }
4807
4808 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4809 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4810 PEnd = Interface->protocol_end();
4811 P != PEnd; ++P)
4812 CollectOverriddenMethods(*P, Method, Methods);
4813
4814 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4815 Category; Category = Category->getNextClassCategory())
4816 CollectOverriddenMethods(Category, Method, Methods);
4817
4818 // We only look into the superclass if we haven't found anything yet.
4819 if (Methods.empty())
4820 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4821 return CollectOverriddenMethods(Super, Method, Methods);
4822 }
4823}
4824
4825void clang_getOverriddenCursors(CXCursor cursor,
4826 CXCursor **overridden,
4827 unsigned *num_overridden) {
4828 if (overridden)
4829 *overridden = 0;
4830 if (num_overridden)
4831 *num_overridden = 0;
4832 if (!overridden || !num_overridden)
4833 return;
4834
4835 if (!clang_isDeclaration(cursor.kind))
4836 return;
4837
4838 Decl *D = getCursorDecl(cursor);
4839 if (!D)
4840 return;
4841
4842 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004843 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004844 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4845 *num_overridden = CXXMethod->size_overridden_methods();
4846 if (!*num_overridden)
4847 return;
4848
4849 *overridden = new CXCursor [*num_overridden];
4850 unsigned I = 0;
4851 for (CXXMethodDecl::method_iterator
4852 M = CXXMethod->begin_overridden_methods(),
4853 MEnd = CXXMethod->end_overridden_methods();
4854 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004855 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004856 return;
4857 }
4858
4859 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4860 if (!Method)
4861 return;
4862
4863 // Handle Objective-C methods.
4864 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4865 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4866
4867 if (Methods.empty())
4868 return;
4869
4870 *num_overridden = Methods.size();
4871 *overridden = new CXCursor [Methods.size()];
4872 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004873 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004874}
4875
4876void clang_disposeOverriddenCursors(CXCursor *overridden) {
4877 delete [] overridden;
4878}
4879
Douglas Gregorecdcb882010-10-20 22:00:55 +00004880CXFile clang_getIncludedFile(CXCursor cursor) {
4881 if (cursor.kind != CXCursor_InclusionDirective)
4882 return 0;
4883
4884 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4885 return (void *)ID->getFile();
4886}
4887
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004888} // end: extern "C"
4889
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004890
4891//===----------------------------------------------------------------------===//
4892// C++ AST instrospection.
4893//===----------------------------------------------------------------------===//
4894
4895extern "C" {
4896unsigned clang_CXXMethod_isStatic(CXCursor C) {
4897 if (!clang_isDeclaration(C.kind))
4898 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004899
4900 CXXMethodDecl *Method = 0;
4901 Decl *D = cxcursor::getCursorDecl(C);
4902 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4903 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4904 else
4905 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4906 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004907}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004908
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004909} // end: extern "C"
4910
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004911//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004912// Attribute introspection.
4913//===----------------------------------------------------------------------===//
4914
4915extern "C" {
4916CXType clang_getIBOutletCollectionType(CXCursor C) {
4917 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004918 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004919
4920 IBOutletCollectionAttr *A =
4921 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4922
Ted Kremeneka60ed472010-11-16 08:15:36 +00004923 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004924}
4925} // end: extern "C"
4926
4927//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004928// Misc. utility functions.
4929//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004930
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004931/// Default to using an 8 MB stack size on "safety" threads.
4932static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004933
4934namespace clang {
4935
4936bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004937 void (*Fn)(void*), void *UserData,
4938 unsigned Size) {
4939 if (!Size)
4940 Size = GetSafetyThreadStackSize();
4941 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004942 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4943 return CRC.RunSafely(Fn, UserData);
4944}
4945
4946unsigned GetSafetyThreadStackSize() {
4947 return SafetyStackThreadSize;
4948}
4949
4950void SetSafetyThreadStackSize(unsigned Value) {
4951 SafetyStackThreadSize = Value;
4952}
4953
4954}
4955
Ted Kremenek04bb7162010-01-22 22:44:15 +00004956extern "C" {
4957
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004958CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004959 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004960}
4961
4962} // end: extern "C"