blob: e6c208b2eaac330e6840dbeee8fdf81d795ee155 [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 Kremeneked122732010-11-16 01:56:27 +000017#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000018#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000019#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000020#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000021
Ted Kremenek04bb7162010-01-22 22:44:15 +000022#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000023
Steve Naroff50398192009-08-28 15:28:48 +000024#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000026#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000027#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000030#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000031#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000032#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000033#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000034#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000035#include "llvm/ADT/Optional.h"
36#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000037#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000038#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000039#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000041#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000042#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000043#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000044#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000045#include "llvm/System/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000046#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000047
Steve Naroff50398192009-08-28 15:28:48 +000048using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000049using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000050using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000051
Ted Kremeneka60ed472010-11-16 08:15:36 +000052static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
53 if (!TU)
54 return 0;
55 CXTranslationUnit D = new CXTranslationUnitImpl();
56 D->TUData = TU;
57 D->StringPool = createCXStringPool();
58 return D;
59}
60
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061/// \brief The result of comparing two source ranges.
62enum RangeComparisonResult {
63 /// \brief Either the ranges overlap or one of the ranges is invalid.
64 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066 /// \brief The first range ends before the second range starts.
67 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000068
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 /// \brief The first range starts after the second range ends.
70 RangeAfter
71};
72
Ted Kremenekf0e23e82010-02-17 00:41:40 +000073/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075static RangeComparisonResult RangeCompare(SourceManager &SM,
76 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 SourceRange R2) {
78 assert(R1.isValid() && "First range is invalid?");
79 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000083 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000084 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000085 return RangeAfter;
86 return RangeOverlap;
87}
88
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089/// \brief Determine if a source location falls within, before, or after a
90/// a given source range.
91static RangeComparisonResult LocationCompare(SourceManager &SM,
92 SourceLocation L, SourceRange R) {
93 assert(R.isValid() && "First range is invalid?");
94 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000095 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000096 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
98 return RangeBefore;
99 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
100 return RangeAfter;
101 return RangeOverlap;
102}
103
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000104/// \brief Translate a Clang source range into a CIndex source range.
105///
106/// Clang internally represents ranges where the end location points to the
107/// start of the token at the end. However, for external clients it is more
108/// useful to have a CXSourceRange be a proper half-open interval. This routine
109/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000110CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000112 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000113 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000114 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000115 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000116 if (EndLoc.isValid() && EndLoc.isMacroID())
117 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000118 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000119 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000120 EndLoc = EndLoc.getFileLocWithOffset(Length);
121 }
122
123 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
124 R.getBegin().getRawEncoding(),
125 EndLoc.getRawEncoding() };
126 return Result;
127}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000128
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000130// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000131//===----------------------------------------------------------------------===//
132
Steve Naroff89922f82009-08-31 00:59:03 +0000133namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000134
135class VisitorJob {
136public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000137 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000138 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000139 DeclRefExprPartsKind, LabelRefVisitKind,
140 ExplicitTemplateArgsVisitKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000141protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000142 void *dataA;
143 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000144 CXCursor parent;
145 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000146 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
147 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000148public:
149 Kind getKind() const { return K; }
150 const CXCursor &getParent() const { return parent; }
151 static bool classof(VisitorJob *VJ) { return true; }
152};
153
154typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
155
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000157class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000158 public TypeLocVisitor<CursorVisitor, bool>,
159 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000160{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000162 CXTranslationUnit TU;
163 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000167
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 /// \brief The declaration that serves at the parent of any statement or
169 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000170 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000171
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000176 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000178 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
179 // to the visitor. Declarations with a PCH level greater than this value will
180 // be suppressed.
181 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182
183 /// \brief When valid, a source range to which the cursor should restrict
184 /// its search.
185 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000186
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000187 // FIXME: Eventually remove. This part of a hack to support proper
188 // iteration over all Decls contained lexically within an ObjC container.
189 DeclContext::decl_iterator *DI_current;
190 DeclContext::decl_iterator DE_current;
191
Ted Kremenekd1ded662010-11-15 23:31:32 +0000192 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
193 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
194 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
195
Douglas Gregorb1373d02010-01-20 20:59:29 +0000196 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000197 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000198 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
200 /// \brief Determine whether this particular source range comes before, comes
201 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000202 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000203 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000204 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
205
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000206 class SetParentRAII {
207 CXCursor &Parent;
208 Decl *&StmtParent;
209 CXCursor OldParent;
210
211 public:
212 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
213 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
214 {
215 Parent = NewParent;
216 if (clang_isDeclaration(Parent.kind))
217 StmtParent = getCursorDecl(Parent);
218 }
219
220 ~SetParentRAII() {
221 Parent = OldParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225 };
226
Steve Naroff89922f82009-08-31 00:59:03 +0000227public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000228 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
229 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000230 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000231 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000232 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
233 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000234 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
235 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000236 {
237 Parent.kind = CXCursor_NoDeclFound;
238 Parent.data[0] = 0;
239 Parent.data[1] = 0;
240 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000241 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000243
Ted Kremenekd1ded662010-11-15 23:31:32 +0000244 ~CursorVisitor() {
245 // Free the pre-allocated worklists for data-recursion.
246 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
247 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
248 delete *I;
249 }
250 }
251
Ted Kremeneka60ed472010-11-16 08:15:36 +0000252 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
253 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000254
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000255 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000256
257 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
258 getPreprocessedEntities();
259
Douglas Gregorb1373d02010-01-20 20:59:29 +0000260 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000261
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000262 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000263 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000264 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000265 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000266 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000267 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000268 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
269 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000270 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000271 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000272 bool VisitClassTemplatePartialSpecializationDecl(
273 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000274 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitEnumConstantDecl(EnumConstantDecl *D);
276 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
277 bool VisitFunctionDecl(FunctionDecl *ND);
278 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000279 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000280 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000281 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000282 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000283 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000284 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
285 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
286 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
287 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000288 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
290 bool VisitObjCImplDecl(ObjCImplDecl *D);
291 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
292 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000293 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
294 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
295 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000296 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000297 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000298 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000299 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000300 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000301 bool VisitUsingDecl(UsingDecl *D);
302 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
303 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000304
Douglas Gregor01829d32010-08-31 14:41:23 +0000305 // Name visitor
306 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000307 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000308
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000309 // Template visitors
310 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000311 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000312 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
313
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000314 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000315 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000316 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000317 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000318 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
319 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000320 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000322 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
324 bool VisitPointerTypeLoc(PointerTypeLoc TL);
325 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
326 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
327 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
328 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000329 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000331 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000332 // FIXME: Implement visitors here when the unimplemented TypeLocs get
333 // implemented
334 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
335 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000336
Douglas Gregora59e3902010-01-21 23:27:09 +0000337 // Statement visitors
338 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000339
Douglas Gregor336fd812010-01-23 00:40:08 +0000340 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000341 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000342 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000343 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000344 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000345 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000346
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000347 // Data-recursive visitor functions.
348 bool IsInRegionOfInterest(CXCursor C);
349 bool RunVisitorWorkList(VisitorWorkList &WL);
350 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Benjamin Kramere645c722010-11-16 15:45:46 +0000351 LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000352};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000353
Ted Kremenekab188932010-01-05 19:32:54 +0000354} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000355
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000356static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000357static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
358
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000359
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000361 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362}
363
Douglas Gregorb1373d02010-01-20 20:59:29 +0000364/// \brief Visit the given cursor and, if requested by the visitor,
365/// its children.
366///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367/// \param Cursor the cursor to visit.
368///
369/// \param CheckRegionOfInterest if true, then the caller already checked that
370/// this cursor is within the region of interest.
371///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372/// \returns true if the visitation should be aborted, false if it
373/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 if (clang_isInvalid(Cursor.kind))
376 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000377
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378 if (clang_isDeclaration(Cursor.kind)) {
379 Decl *D = getCursorDecl(Cursor);
380 assert(D && "Invalid declaration cursor");
381 if (D->getPCHLevel() > MaxPCHLevel)
382 return false;
383
384 if (D->isImplicit())
385 return false;
386 }
387
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388 // If we have a range of interest, and this cursor doesn't intersect with it,
389 // we're done.
390 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000391 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000392 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 return false;
394 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000395
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 switch (Visitor(Cursor, Parent, ClientData)) {
397 case CXChildVisit_Break:
398 return true;
399
400 case CXChildVisit_Continue:
401 return false;
402
403 case CXChildVisit_Recurse:
404 return VisitChildren(Cursor);
405 }
406
Douglas Gregorfd643772010-01-25 16:45:46 +0000407 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408}
409
Douglas Gregor788f5a12010-03-20 00:41:21 +0000410std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
411CursorVisitor::getPreprocessedEntities() {
412 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000413 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000414
415 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000416 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000417
418 // There is no region of interest; we have to walk everything.
419 if (RegionOfInterest.isInvalid())
420 return std::make_pair(PPRec.begin(OnlyLocalDecls),
421 PPRec.end(OnlyLocalDecls));
422
423 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000424 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000425 std::pair<FileID, unsigned> Begin
426 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
427 std::pair<FileID, unsigned> End
428 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
429
430 // The region of interest spans files; we have to walk everything.
431 if (Begin.first != End.first)
432 return std::make_pair(PPRec.begin(OnlyLocalDecls),
433 PPRec.end(OnlyLocalDecls));
434
435 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000436 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000437 if (ByFileMap.empty()) {
438 // Build the mapping from files to sets of preprocessed entities.
439 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
440 EEnd = PPRec.end(OnlyLocalDecls);
441 E != EEnd; ++E) {
442 std::pair<FileID, unsigned> P
443 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
444 ByFileMap[P.first].push_back(*E);
445 }
446 }
447
448 return std::make_pair(ByFileMap[Begin.first].begin(),
449 ByFileMap[Begin.first].end());
450}
451
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000453///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454/// \returns true if the visitation should be aborted, false if it
455/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000457 if (clang_isReference(Cursor.kind)) {
458 // By definition, references have no children.
459 return false;
460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461
462 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000464 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 if (clang_isDeclaration(Cursor.kind)) {
467 Decl *D = getCursorDecl(Cursor);
468 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000469 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregora59e3902010-01-21 23:27:09 +0000472 if (clang_isStatement(Cursor.kind))
473 return Visit(getCursorStmt(Cursor));
474 if (clang_isExpression(Cursor.kind))
475 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000478 CXTranslationUnit tu = getCursorTU(Cursor);
479 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000480 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
481 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000482 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
483 TLEnd = CXXUnit->top_level_end();
484 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000485 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000486 return true;
487 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000488 } else if (VisitDeclContext(
489 CXXUnit->getASTContext().getTranslationUnitDecl()))
490 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000491
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000493 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 // FIXME: Once we have the ability to deserialize a preprocessing record,
495 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000496 PreprocessingRecord::iterator E, EEnd;
497 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000499 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000501
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 continue;
503 }
504
505 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000506 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 return true;
508
509 continue;
510 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000511
512 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000513 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000514 return true;
515
516 continue;
517 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 }
519 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000520 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000522
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 return false;
525}
526
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000527bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000528 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
529 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530
Ted Kremenek664cffd2010-07-22 11:30:19 +0000531 if (Stmt *Body = B->getBody())
532 return Visit(MakeCXCursor(Body, StmtParent, TU));
533
534 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000535}
536
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000537llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
538 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000539 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000540 if (Range.isInvalid())
541 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000542
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543 switch (CompareRegionOfInterest(Range)) {
544 case RangeBefore:
545 // This declaration comes before the region of interest; skip it.
546 return llvm::Optional<bool>();
547
548 case RangeAfter:
549 // This declaration comes after the region of interest; we're done.
550 return false;
551
552 case RangeOverlap:
553 // This declaration overlaps the region of interest; visit it.
554 break;
555 }
556 }
557 return true;
558}
559
560bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
561 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
562
563 // FIXME: Eventually remove. This part of a hack to support proper
564 // iteration over all Decls contained lexically within an ObjC container.
565 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
566 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
567
568 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000569 Decl *D = *I;
570 if (D->getLexicalDeclContext() != DC)
571 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000572 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000573 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
574 if (!V.hasValue())
575 continue;
576 if (!V.getValue())
577 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000578 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000579 return true;
580 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000582}
583
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000584bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
585 llvm_unreachable("Translation units are visited directly by Visit()");
586 return false;
587}
588
589bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
590 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
591 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000592
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000593 return false;
594}
595
596bool CursorVisitor::VisitTagDecl(TagDecl *D) {
597 return VisitDeclContext(D);
598}
599
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000600bool CursorVisitor::VisitClassTemplateSpecializationDecl(
601 ClassTemplateSpecializationDecl *D) {
602 bool ShouldVisitBody = false;
603 switch (D->getSpecializationKind()) {
604 case TSK_Undeclared:
605 case TSK_ImplicitInstantiation:
606 // Nothing to visit
607 return false;
608
609 case TSK_ExplicitInstantiationDeclaration:
610 case TSK_ExplicitInstantiationDefinition:
611 break;
612
613 case TSK_ExplicitSpecialization:
614 ShouldVisitBody = true;
615 break;
616 }
617
618 // Visit the template arguments used in the specialization.
619 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
620 TypeLoc TL = SpecType->getTypeLoc();
621 if (TemplateSpecializationTypeLoc *TSTLoc
622 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
623 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
624 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
625 return true;
626 }
627 }
628
629 if (ShouldVisitBody && VisitCXXRecordDecl(D))
630 return true;
631
632 return false;
633}
634
Douglas Gregor74dbe642010-08-31 19:31:58 +0000635bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
636 ClassTemplatePartialSpecializationDecl *D) {
637 // FIXME: Visit the "outer" template parameter lists on the TagDecl
638 // before visiting these template parameters.
639 if (VisitTemplateParameters(D->getTemplateParameters()))
640 return true;
641
642 // Visit the partial specialization arguments.
643 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
644 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
645 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
646 return true;
647
648 return VisitCXXRecordDecl(D);
649}
650
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000651bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000652 // Visit the default argument.
653 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
654 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
655 if (Visit(DefArg->getTypeLoc()))
656 return true;
657
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000658 return false;
659}
660
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000661bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
662 if (Expr *Init = D->getInitExpr())
663 return Visit(MakeCXCursor(Init, StmtParent, TU));
664 return false;
665}
666
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000667bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
668 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
669 if (Visit(TSInfo->getTypeLoc()))
670 return true;
671
672 return false;
673}
674
Douglas Gregora67e03f2010-09-09 21:42:20 +0000675/// \brief Compare two base or member initializers based on their source order.
676static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
677 CXXBaseOrMemberInitializer const * const *X
678 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
679 CXXBaseOrMemberInitializer const * const *Y
680 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
681
682 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
683 return -1;
684 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
685 return 1;
686 else
687 return 0;
688}
689
Douglas Gregorb1373d02010-01-20 20:59:29 +0000690bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000691 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
692 // Visit the function declaration's syntactic components in the order
693 // written. This requires a bit of work.
694 TypeLoc TL = TSInfo->getTypeLoc();
695 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
696
697 // If we have a function declared directly (without the use of a typedef),
698 // visit just the return type. Otherwise, just visit the function's type
699 // now.
700 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
701 (!FTL && Visit(TL)))
702 return true;
703
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000704 // Visit the nested-name-specifier, if present.
705 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
706 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
707 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000708
709 // Visit the declaration name.
710 if (VisitDeclarationNameInfo(ND->getNameInfo()))
711 return true;
712
713 // FIXME: Visit explicitly-specified template arguments!
714
715 // Visit the function parameters, if we have a function type.
716 if (FTL && VisitFunctionTypeLoc(*FTL, true))
717 return true;
718
719 // FIXME: Attributes?
720 }
721
Douglas Gregora67e03f2010-09-09 21:42:20 +0000722 if (ND->isThisDeclarationADefinition()) {
723 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
724 // Find the initializers that were written in the source.
725 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
726 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
727 IEnd = Constructor->init_end();
728 I != IEnd; ++I) {
729 if (!(*I)->isWritten())
730 continue;
731
732 WrittenInits.push_back(*I);
733 }
734
735 // Sort the initializers in source order
736 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
737 &CompareCXXBaseOrMemberInitializers);
738
739 // Visit the initializers in source order
740 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
741 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
742 if (Init->isMemberInitializer()) {
743 if (Visit(MakeCursorMemberRef(Init->getMember(),
744 Init->getMemberLocation(), TU)))
745 return true;
746 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
747 if (Visit(BaseInfo->getTypeLoc()))
748 return true;
749 }
750
751 // Visit the initializer value.
752 if (Expr *Initializer = Init->getInit())
753 if (Visit(MakeCXCursor(Initializer, ND, TU)))
754 return true;
755 }
756 }
757
758 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
759 return true;
760 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761
Douglas Gregorb1373d02010-01-20 20:59:29 +0000762 return false;
763}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000764
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000765bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
766 if (VisitDeclaratorDecl(D))
767 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000768
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000769 if (Expr *BitWidth = D->getBitWidth())
770 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772 return false;
773}
774
775bool CursorVisitor::VisitVarDecl(VarDecl *D) {
776 if (VisitDeclaratorDecl(D))
777 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000778
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000779 if (Expr *Init = D->getInit())
780 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000781
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000782 return false;
783}
784
Douglas Gregor84b51d72010-09-01 20:16:53 +0000785bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
786 if (VisitDeclaratorDecl(D))
787 return true;
788
789 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
790 if (Expr *DefArg = D->getDefaultArgument())
791 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
792
793 return false;
794}
795
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000796bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
797 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
798 // before visiting these template parameters.
799 if (VisitTemplateParameters(D->getTemplateParameters()))
800 return true;
801
802 return VisitFunctionDecl(D->getTemplatedDecl());
803}
804
Douglas Gregor39d6f072010-08-31 19:02:00 +0000805bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
806 // FIXME: Visit the "outer" template parameter lists on the TagDecl
807 // before visiting these template parameters.
808 if (VisitTemplateParameters(D->getTemplateParameters()))
809 return true;
810
811 return VisitCXXRecordDecl(D->getTemplatedDecl());
812}
813
Douglas Gregor84b51d72010-09-01 20:16:53 +0000814bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
815 if (VisitTemplateParameters(D->getTemplateParameters()))
816 return true;
817
818 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
819 VisitTemplateArgumentLoc(D->getDefaultArgument()))
820 return true;
821
822 return false;
823}
824
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000825bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000826 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
827 if (Visit(TSInfo->getTypeLoc()))
828 return true;
829
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000830 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000831 PEnd = ND->param_end();
832 P != PEnd; ++P) {
833 if (Visit(MakeCXCursor(*P, TU)))
834 return true;
835 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000836
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000837 if (ND->isThisDeclarationADefinition() &&
838 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
839 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841 return false;
842}
843
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000844namespace {
845 struct ContainerDeclsSort {
846 SourceManager &SM;
847 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
848 bool operator()(Decl *A, Decl *B) {
849 SourceLocation L_A = A->getLocStart();
850 SourceLocation L_B = B->getLocStart();
851 assert(L_A.isValid() && L_B.isValid());
852 return SM.isBeforeInTranslationUnit(L_A, L_B);
853 }
854 };
855}
856
Douglas Gregora59e3902010-01-21 23:27:09 +0000857bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000858 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
859 // an @implementation can lexically contain Decls that are not properly
860 // nested in the AST. When we identify such cases, we need to retrofit
861 // this nesting here.
862 if (!DI_current)
863 return VisitDeclContext(D);
864
865 // Scan the Decls that immediately come after the container
866 // in the current DeclContext. If any fall within the
867 // container's lexical region, stash them into a vector
868 // for later processing.
869 llvm::SmallVector<Decl *, 24> DeclsInContainer;
870 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000871 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000872 if (EndLoc.isValid()) {
873 DeclContext::decl_iterator next = *DI_current;
874 while (++next != DE_current) {
875 Decl *D_next = *next;
876 if (!D_next)
877 break;
878 SourceLocation L = D_next->getLocStart();
879 if (!L.isValid())
880 break;
881 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
882 *DI_current = next;
883 DeclsInContainer.push_back(D_next);
884 continue;
885 }
886 break;
887 }
888 }
889
890 // The common case.
891 if (DeclsInContainer.empty())
892 return VisitDeclContext(D);
893
894 // Get all the Decls in the DeclContext, and sort them with the
895 // additional ones we've collected. Then visit them.
896 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
897 I!=E; ++I) {
898 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000899 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
900 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000901 continue;
902 DeclsInContainer.push_back(subDecl);
903 }
904
905 // Now sort the Decls so that they appear in lexical order.
906 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
907 ContainerDeclsSort(SM));
908
909 // Now visit the decls.
910 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
911 E = DeclsInContainer.end(); I != E; ++I) {
912 CXCursor Cursor = MakeCXCursor(*I, TU);
913 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
914 if (!V.hasValue())
915 continue;
916 if (!V.getValue())
917 return false;
918 if (Visit(Cursor, true))
919 return true;
920 }
921 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000922}
923
Douglas Gregorb1373d02010-01-20 20:59:29 +0000924bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000925 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
926 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000927 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000928
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000929 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
930 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
931 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000932 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregora59e3902010-01-21 23:27:09 +0000935 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000936}
937
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000938bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
939 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
940 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
941 E = PID->protocol_end(); I != E; ++I, ++PL)
942 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
943 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000944
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000945 return VisitObjCContainerDecl(PID);
946}
947
Ted Kremenek23173d72010-05-18 21:09:07 +0000948bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000949 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000950 return true;
951
Ted Kremenek23173d72010-05-18 21:09:07 +0000952 // FIXME: This implements a workaround with @property declarations also being
953 // installed in the DeclContext for the @interface. Eventually this code
954 // should be removed.
955 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
956 if (!CDecl || !CDecl->IsClassExtension())
957 return false;
958
959 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
960 if (!ID)
961 return false;
962
963 IdentifierInfo *PropertyId = PD->getIdentifier();
964 ObjCPropertyDecl *prevDecl =
965 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
966
967 if (!prevDecl)
968 return false;
969
970 // Visit synthesized methods since they will be skipped when visiting
971 // the @interface.
972 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000973 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000974 if (Visit(MakeCXCursor(MD, TU)))
975 return true;
976
977 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000978 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000979 if (Visit(MakeCXCursor(MD, TU)))
980 return true;
981
982 return false;
983}
984
Douglas Gregorb1373d02010-01-20 20:59:29 +0000985bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000986 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000987 if (D->getSuperClass() &&
988 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000990 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000991 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000993 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
994 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
995 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000996 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000997 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998
Douglas Gregora59e3902010-01-21 23:27:09 +0000999 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001000}
1001
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001002bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1003 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001004}
1005
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001006bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001007 // 'ID' could be null when dealing with invalid code.
1008 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1009 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1010 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001011
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001012 return VisitObjCImplDecl(D);
1013}
1014
1015bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1016#if 0
1017 // Issue callbacks for super class.
1018 // FIXME: No source location information!
1019 if (D->getSuperClass() &&
1020 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022 TU)))
1023 return true;
1024#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026 return VisitObjCImplDecl(D);
1027}
1028
1029bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1030 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1031 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1032 E = D->protocol_end();
1033 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001034 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001035 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001036
1037 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001038}
1039
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001040bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1041 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1042 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1043 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001046}
1047
Douglas Gregora4ffd852010-11-17 01:03:52 +00001048bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1049 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1050 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1051
1052 return false;
1053}
1054
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001055bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1056 return VisitDeclContext(D);
1057}
1058
Douglas Gregor69319002010-08-31 23:48:11 +00001059bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001060 // Visit nested-name-specifier.
1061 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1062 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1063 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001064
1065 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1066 D->getTargetNameLoc(), TU));
1067}
1068
Douglas Gregor7e242562010-09-01 19:52:22 +00001069bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001070 // Visit nested-name-specifier.
1071 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1072 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1073 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001074
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001075 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1076 return true;
1077
Douglas Gregor7e242562010-09-01 19:52:22 +00001078 return VisitDeclarationNameInfo(D->getNameInfo());
1079}
1080
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001081bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001082 // Visit nested-name-specifier.
1083 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1084 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1085 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001086
1087 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1088 D->getIdentLocation(), TU));
1089}
1090
Douglas Gregor7e242562010-09-01 19:52:22 +00001091bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001092 // Visit nested-name-specifier.
1093 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1094 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1095 return true;
1096
Douglas Gregor7e242562010-09-01 19:52:22 +00001097 return VisitDeclarationNameInfo(D->getNameInfo());
1098}
1099
1100bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1101 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001102 // Visit nested-name-specifier.
1103 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1104 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1105 return true;
1106
Douglas Gregor7e242562010-09-01 19:52:22 +00001107 return false;
1108}
1109
Douglas Gregor01829d32010-08-31 14:41:23 +00001110bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1111 switch (Name.getName().getNameKind()) {
1112 case clang::DeclarationName::Identifier:
1113 case clang::DeclarationName::CXXLiteralOperatorName:
1114 case clang::DeclarationName::CXXOperatorName:
1115 case clang::DeclarationName::CXXUsingDirective:
1116 return false;
1117
1118 case clang::DeclarationName::CXXConstructorName:
1119 case clang::DeclarationName::CXXDestructorName:
1120 case clang::DeclarationName::CXXConversionFunctionName:
1121 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1122 return Visit(TSInfo->getTypeLoc());
1123 return false;
1124
1125 case clang::DeclarationName::ObjCZeroArgSelector:
1126 case clang::DeclarationName::ObjCOneArgSelector:
1127 case clang::DeclarationName::ObjCMultiArgSelector:
1128 // FIXME: Per-identifier location info?
1129 return false;
1130 }
1131
1132 return false;
1133}
1134
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001135bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1136 SourceRange Range) {
1137 // FIXME: This whole routine is a hack to work around the lack of proper
1138 // source information in nested-name-specifiers (PR5791). Since we do have
1139 // a beginning source location, we can visit the first component of the
1140 // nested-name-specifier, if it's a single-token component.
1141 if (!NNS)
1142 return false;
1143
1144 // Get the first component in the nested-name-specifier.
1145 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1146 NNS = Prefix;
1147
1148 switch (NNS->getKind()) {
1149 case NestedNameSpecifier::Namespace:
1150 // FIXME: The token at this source location might actually have been a
1151 // namespace alias, but we don't model that. Lame!
1152 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1153 TU));
1154
1155 case NestedNameSpecifier::TypeSpec: {
1156 // If the type has a form where we know that the beginning of the source
1157 // range matches up with a reference cursor. Visit the appropriate reference
1158 // cursor.
1159 Type *T = NNS->getAsType();
1160 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1161 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1162 if (const TagType *Tag = dyn_cast<TagType>(T))
1163 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1164 if (const TemplateSpecializationType *TST
1165 = dyn_cast<TemplateSpecializationType>(T))
1166 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1167 break;
1168 }
1169
1170 case NestedNameSpecifier::TypeSpecWithTemplate:
1171 case NestedNameSpecifier::Global:
1172 case NestedNameSpecifier::Identifier:
1173 break;
1174 }
1175
1176 return false;
1177}
1178
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001179bool CursorVisitor::VisitTemplateParameters(
1180 const TemplateParameterList *Params) {
1181 if (!Params)
1182 return false;
1183
1184 for (TemplateParameterList::const_iterator P = Params->begin(),
1185 PEnd = Params->end();
1186 P != PEnd; ++P) {
1187 if (Visit(MakeCXCursor(*P, TU)))
1188 return true;
1189 }
1190
1191 return false;
1192}
1193
Douglas Gregor0b36e612010-08-31 20:37:03 +00001194bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1195 switch (Name.getKind()) {
1196 case TemplateName::Template:
1197 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1198
1199 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001200 // Visit the overloaded template set.
1201 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1202 return true;
1203
Douglas Gregor0b36e612010-08-31 20:37:03 +00001204 return false;
1205
1206 case TemplateName::DependentTemplate:
1207 // FIXME: Visit nested-name-specifier.
1208 return false;
1209
1210 case TemplateName::QualifiedTemplate:
1211 // FIXME: Visit nested-name-specifier.
1212 return Visit(MakeCursorTemplateRef(
1213 Name.getAsQualifiedTemplateName()->getDecl(),
1214 Loc, TU));
1215 }
1216
1217 return false;
1218}
1219
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001220bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1221 switch (TAL.getArgument().getKind()) {
1222 case TemplateArgument::Null:
1223 case TemplateArgument::Integral:
1224 return false;
1225
1226 case TemplateArgument::Pack:
1227 // FIXME: Implement when variadic templates come along.
1228 return false;
1229
1230 case TemplateArgument::Type:
1231 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1232 return Visit(TSInfo->getTypeLoc());
1233 return false;
1234
1235 case TemplateArgument::Declaration:
1236 if (Expr *E = TAL.getSourceDeclExpression())
1237 return Visit(MakeCXCursor(E, StmtParent, TU));
1238 return false;
1239
1240 case TemplateArgument::Expression:
1241 if (Expr *E = TAL.getSourceExpression())
1242 return Visit(MakeCXCursor(E, StmtParent, TU));
1243 return false;
1244
1245 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001246 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1247 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001248 }
1249
1250 return false;
1251}
1252
Ted Kremeneka0536d82010-05-07 01:04:29 +00001253bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1254 return VisitDeclContext(D);
1255}
1256
Douglas Gregor01829d32010-08-31 14:41:23 +00001257bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1258 return Visit(TL.getUnqualifiedLoc());
1259}
1260
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001261bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001262 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001263
1264 // Some builtin types (such as Objective-C's "id", "sel", and
1265 // "Class") have associated declarations. Create cursors for those.
1266 QualType VisitType;
1267 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001268 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001269 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001270 case BuiltinType::Char_U:
1271 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001272 case BuiltinType::Char16:
1273 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001274 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001275 case BuiltinType::UInt:
1276 case BuiltinType::ULong:
1277 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001278 case BuiltinType::UInt128:
1279 case BuiltinType::Char_S:
1280 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001281 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001282 case BuiltinType::Short:
1283 case BuiltinType::Int:
1284 case BuiltinType::Long:
1285 case BuiltinType::LongLong:
1286 case BuiltinType::Int128:
1287 case BuiltinType::Float:
1288 case BuiltinType::Double:
1289 case BuiltinType::LongDouble:
1290 case BuiltinType::NullPtr:
1291 case BuiltinType::Overload:
1292 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001293 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001294
1295 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001296 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001297
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001298 case BuiltinType::ObjCId:
1299 VisitType = Context.getObjCIdType();
1300 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001301
1302 case BuiltinType::ObjCClass:
1303 VisitType = Context.getObjCClassType();
1304 break;
1305
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001306 case BuiltinType::ObjCSel:
1307 VisitType = Context.getObjCSelType();
1308 break;
1309 }
1310
1311 if (!VisitType.isNull()) {
1312 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001313 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001314 TU));
1315 }
1316
1317 return false;
1318}
1319
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001320bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1321 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1322}
1323
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001324bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1325 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1326}
1327
1328bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1329 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1330}
1331
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001332bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001333 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001334 // no context information with which we can match up the depth/index in the
1335 // type to the appropriate
1336 return false;
1337}
1338
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001339bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1340 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1341 return true;
1342
John McCallc12c5bb2010-05-15 11:32:37 +00001343 return false;
1344}
1345
1346bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1347 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1348 return true;
1349
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001350 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1351 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1352 TU)))
1353 return true;
1354 }
1355
1356 return false;
1357}
1358
1359bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001360 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001361}
1362
1363bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1364 return Visit(TL.getPointeeLoc());
1365}
1366
1367bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1368 return Visit(TL.getPointeeLoc());
1369}
1370
1371bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1372 return Visit(TL.getPointeeLoc());
1373}
1374
1375bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001376 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001377}
1378
1379bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001380 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381}
1382
Douglas Gregor01829d32010-08-31 14:41:23 +00001383bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1384 bool SkipResultType) {
1385 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386 return true;
1387
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001389 if (Decl *D = TL.getArg(I))
1390 if (Visit(MakeCXCursor(D, TU)))
1391 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392
1393 return false;
1394}
1395
1396bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1397 if (Visit(TL.getElementLoc()))
1398 return true;
1399
1400 if (Expr *Size = TL.getSizeExpr())
1401 return Visit(MakeCXCursor(Size, StmtParent, TU));
1402
1403 return false;
1404}
1405
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001406bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1407 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001408 // Visit the template name.
1409 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1410 TL.getTemplateNameLoc()))
1411 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001412
1413 // Visit the template arguments.
1414 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1415 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1416 return true;
1417
1418 return false;
1419}
1420
Douglas Gregor2332c112010-01-21 20:48:56 +00001421bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1422 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1423}
1424
1425bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1426 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1427 return Visit(TSInfo->getTypeLoc());
1428
1429 return false;
1430}
1431
Douglas Gregora59e3902010-01-21 23:27:09 +00001432bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001433 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001434}
1435
Ted Kremenek3064ef92010-08-27 21:34:58 +00001436bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1437 if (D->isDefinition()) {
1438 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1439 E = D->bases_end(); I != E; ++I) {
1440 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1441 return true;
1442 }
1443 }
1444
1445 return VisitTagDecl(D);
1446}
1447
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001448bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001449 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001450 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1451 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001452
1453 // Visit the components of the offsetof expression.
1454 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1455 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1456 const OffsetOfNode &Node = E->getComponent(I);
1457 switch (Node.getKind()) {
1458 case OffsetOfNode::Array:
1459 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1460 StmtParent, TU)))
1461 return true;
1462 break;
1463
1464 case OffsetOfNode::Field:
1465 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1466 TU)))
1467 return true;
1468 break;
1469
1470 case OffsetOfNode::Identifier:
1471 case OffsetOfNode::Base:
1472 continue;
1473 }
1474 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001475
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001476 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001477}
1478
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001479bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1480 // Visit the designators.
1481 typedef DesignatedInitExpr::Designator Designator;
1482 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1483 DEnd = E->designators_end();
1484 D != DEnd; ++D) {
1485 if (D->isFieldDesignator()) {
1486 if (FieldDecl *Field = D->getField())
1487 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1488 return true;
1489
1490 continue;
1491 }
1492
1493 if (D->isArrayDesignator()) {
1494 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1495 return true;
1496
1497 continue;
1498 }
1499
1500 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1501 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1502 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1503 return true;
1504 }
1505
1506 // Visit the initializer value itself.
1507 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1508}
1509
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001510bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1511 // Visit base expression.
1512 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1513 return true;
1514
1515 // Visit the nested-name-specifier.
1516 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1517 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1518 return true;
1519
1520 // Visit the scope type that looks disturbingly like the nested-name-specifier
1521 // but isn't.
1522 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1523 if (Visit(TSInfo->getTypeLoc()))
1524 return true;
1525
1526 // Visit the name of the type being destroyed.
1527 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1528 if (Visit(TSInfo->getTypeLoc()))
1529 return true;
1530
1531 return false;
1532}
1533
Douglas Gregorbfebed22010-09-03 17:24:10 +00001534bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1535 DependentScopeDeclRefExpr *E) {
1536 // Visit the nested-name-specifier.
1537 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1538 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1539 return true;
1540
1541 // Visit the declaration name.
1542 if (VisitDeclarationNameInfo(E->getNameInfo()))
1543 return true;
1544
1545 // Visit the explicitly-specified template arguments.
1546 if (const ExplicitTemplateArgumentList *ArgList
1547 = E->getOptionalExplicitTemplateArgs()) {
1548 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1549 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1550 Arg != ArgEnd; ++Arg) {
1551 if (VisitTemplateArgumentLoc(*Arg))
1552 return true;
1553 }
1554 }
1555
1556 return false;
1557}
1558
Douglas Gregor25d63622010-09-03 17:35:34 +00001559bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1560 CXXDependentScopeMemberExpr *E) {
1561 // Visit the base expression, if there is one.
1562 if (!E->isImplicitAccess() &&
1563 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1564 return true;
1565
1566 // Visit the nested-name-specifier.
1567 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1568 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1569 return true;
1570
1571 // Visit the declaration name.
1572 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1573 return true;
1574
1575 // Visit the explicitly-specified template arguments.
1576 if (const ExplicitTemplateArgumentList *ArgList
1577 = E->getOptionalExplicitTemplateArgs()) {
1578 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1579 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1580 Arg != ArgEnd; ++Arg) {
1581 if (VisitTemplateArgumentLoc(*Arg))
1582 return true;
1583 }
1584 }
1585
1586 return false;
1587}
1588
Ted Kremenek09dfa372010-02-18 05:46:33 +00001589bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001590 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1591 i != e; ++i)
1592 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001593 return true;
1594
1595 return false;
1596}
1597
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001598//===----------------------------------------------------------------------===//
1599// Data-recursive visitor methods.
1600//===----------------------------------------------------------------------===//
1601
Ted Kremenek28a71942010-11-13 00:36:47 +00001602namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001603#define DEF_JOB(NAME, DATA, KIND)\
1604class NAME : public VisitorJob {\
1605public:\
1606 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1607 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1608 DATA *get() const { return static_cast<DATA*>(dataA); }\
1609};
1610
1611DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1612DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001613DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001614DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001615DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1616 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001617#undef DEF_JOB
1618
1619class DeclVisit : public VisitorJob {
1620public:
1621 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1622 VisitorJob(parent, VisitorJob::DeclVisitKind,
1623 d, isFirst ? (void*) 1 : (void*) 0) {}
1624 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001625 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001626 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001627 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001628 bool isFirst() const { return dataB ? true : false; }
1629};
Ted Kremenek035dc412010-11-13 00:36:50 +00001630class TypeLocVisit : public VisitorJob {
1631public:
1632 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1633 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1634 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1635
1636 static bool classof(const VisitorJob *VJ) {
1637 return VJ->getKind() == TypeLocVisitKind;
1638 }
1639
Ted Kremenek82f3c502010-11-15 22:23:26 +00001640 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001641 QualType T = QualType::getFromOpaquePtr(dataA);
1642 return TypeLoc(T, dataB);
1643 }
1644};
1645
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001646class LabelRefVisit : public VisitorJob {
1647public:
1648 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1649 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1650 (void*) labelLoc.getRawEncoding()) {}
1651
1652 static bool classof(const VisitorJob *VJ) {
1653 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1654 }
1655 LabelStmt *get() const { return static_cast<LabelStmt*>(dataA); }
1656 SourceLocation getLoc() const {
1657 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) dataB); }
1658};
1659
Ted Kremenek28a71942010-11-13 00:36:47 +00001660class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1661 VisitorWorkList &WL;
1662 CXCursor Parent;
1663public:
1664 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1665 : WL(wl), Parent(parent) {}
1666
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001667 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001668 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001669 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001670 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001671 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1672 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001673 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001674 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001675 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001676 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001677 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001678 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001679 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001680 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001681 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1682 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001683 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001684 void VisitIfStmt(IfStmt *If);
1685 void VisitInitListExpr(InitListExpr *IE);
1686 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001687 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001688 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1689 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001690 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001691 void VisitStmt(Stmt *S);
1692 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001693 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001694 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001695 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001697 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001698
1699private:
Ted Kremenek60608ec2010-11-17 00:50:47 +00001700 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenek28a71942010-11-13 00:36:47 +00001701 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001702 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001703 void AddTypeLoc(TypeSourceInfo *TI);
1704 void EnqueueChildren(Stmt *S);
1705};
1706} // end anonyous namespace
1707
1708void EnqueueVisitor::AddStmt(Stmt *S) {
1709 if (S)
1710 WL.push_back(StmtVisit(S, Parent));
1711}
Ted Kremenek035dc412010-11-13 00:36:50 +00001712void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001713 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001714 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001715}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001716void EnqueueVisitor::
1717 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1718 if (A)
1719 WL.push_back(ExplicitTemplateArgsVisit(
1720 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1721}
Ted Kremenek28a71942010-11-13 00:36:47 +00001722void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1723 if (TI)
1724 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1725 }
1726void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001727 unsigned size = WL.size();
1728 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1729 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001730 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001731 }
1732 if (size == WL.size())
1733 return;
1734 // Now reverse the entries we just added. This will match the DFS
1735 // ordering performed by the worklist.
1736 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1737 std::reverse(I, E);
1738}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001739void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1740 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1741}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001742void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1743 AddDecl(B->getBlockDecl());
1744}
Ted Kremenek28a71942010-11-13 00:36:47 +00001745void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1746 EnqueueChildren(E);
1747 AddTypeLoc(E->getTypeSourceInfo());
1748}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001749void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1750 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1751 E = S->body_rend(); I != E; ++I) {
1752 AddStmt(*I);
1753 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001754}
1755void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1756 // Enqueue the initializer or constructor arguments.
1757 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1758 AddStmt(E->getConstructorArg(I-1));
1759 // Enqueue the array size, if any.
1760 AddStmt(E->getArraySize());
1761 // Enqueue the allocated type.
1762 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1763 // Enqueue the placement arguments.
1764 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1765 AddStmt(E->getPlacementArg(I-1));
1766}
Ted Kremenek28a71942010-11-13 00:36:47 +00001767void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001768 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1769 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001770 AddStmt(CE->getCallee());
1771 AddStmt(CE->getArg(0));
1772}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001773void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1774 AddTypeLoc(E->getTypeSourceInfo());
1775}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001776void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1777 EnqueueChildren(E);
1778 AddTypeLoc(E->getTypeSourceInfo());
1779}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001780void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1781 EnqueueChildren(E);
1782 if (E->isTypeOperand())
1783 AddTypeLoc(E->getTypeOperandSourceInfo());
1784}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001785
1786void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1787 *E) {
1788 EnqueueChildren(E);
1789 AddTypeLoc(E->getTypeSourceInfo());
1790}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001791void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1792 EnqueueChildren(E);
1793 if (E->isTypeOperand())
1794 AddTypeLoc(E->getTypeOperandSourceInfo());
1795}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001796void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001797 if (DR->hasExplicitTemplateArgs()) {
1798 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1799 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001800 WL.push_back(DeclRefExprParts(DR, Parent));
1801}
Ted Kremenek035dc412010-11-13 00:36:50 +00001802void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1803 unsigned size = WL.size();
1804 bool isFirst = true;
1805 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1806 D != DEnd; ++D) {
1807 AddDecl(*D, isFirst);
1808 isFirst = false;
1809 }
1810 if (size == WL.size())
1811 return;
1812 // Now reverse the entries we just added. This will match the DFS
1813 // ordering performed by the worklist.
1814 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1815 std::reverse(I, E);
1816}
Ted Kremenek28a71942010-11-13 00:36:47 +00001817void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1818 EnqueueChildren(E);
1819 AddTypeLoc(E->getTypeInfoAsWritten());
1820}
1821void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1822 AddStmt(FS->getBody());
1823 AddStmt(FS->getInc());
1824 AddStmt(FS->getCond());
1825 AddDecl(FS->getConditionVariable());
1826 AddStmt(FS->getInit());
1827}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001828void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1829 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1830}
Ted Kremenek28a71942010-11-13 00:36:47 +00001831void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1832 AddStmt(If->getElse());
1833 AddStmt(If->getThen());
1834 AddStmt(If->getCond());
1835 AddDecl(If->getConditionVariable());
1836}
1837void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1838 // We care about the syntactic form of the initializer list, only.
1839 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1840 IE = Syntactic;
1841 EnqueueChildren(IE);
1842}
1843void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor66537982010-11-17 17:14:07 +00001844 WL.push_back(MemberExprParts(M, Parent));
Ted Kremenek28a71942010-11-13 00:36:47 +00001845 AddStmt(M->getBase());
1846}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001847void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1848 AddTypeLoc(E->getEncodedTypeSourceInfo());
1849}
Ted Kremenek28a71942010-11-13 00:36:47 +00001850void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1851 EnqueueChildren(M);
1852 AddTypeLoc(M->getClassReceiverTypeInfo());
1853}
1854void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001855 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001856 WL.push_back(OverloadExprParts(E, Parent));
1857}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001858void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1859 EnqueueChildren(E);
1860 if (E->isArgumentType())
1861 AddTypeLoc(E->getArgumentTypeInfo());
1862}
Ted Kremenek28a71942010-11-13 00:36:47 +00001863void EnqueueVisitor::VisitStmt(Stmt *S) {
1864 EnqueueChildren(S);
1865}
1866void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1867 AddStmt(S->getBody());
1868 AddStmt(S->getCond());
1869 AddDecl(S->getConditionVariable());
1870}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001871void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1872 AddTypeLoc(E->getArgTInfo2());
1873 AddTypeLoc(E->getArgTInfo1());
1874}
1875
Ted Kremenek28a71942010-11-13 00:36:47 +00001876void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1877 AddStmt(W->getBody());
1878 AddStmt(W->getCond());
1879 AddDecl(W->getConditionVariable());
1880}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001881void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1882 AddTypeLoc(E->getQueriedTypeSourceInfo());
1883}
Ted Kremenek28a71942010-11-13 00:36:47 +00001884void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1885 VisitOverloadExpr(U);
1886 if (!U->isImplicitAccess())
1887 AddStmt(U->getBase());
1888}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001889void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1890 AddStmt(E->getSubExpr());
1891 AddTypeLoc(E->getWrittenTypeInfo());
1892}
Ted Kremenek60458782010-11-12 21:34:16 +00001893
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001894void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001895 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001896}
1897
1898bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1899 if (RegionOfInterest.isValid()) {
1900 SourceRange Range = getRawCursorExtent(C);
1901 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1902 return false;
1903 }
1904 return true;
1905}
1906
1907bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1908 while (!WL.empty()) {
1909 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001910 VisitorJob LI = WL.back();
1911 WL.pop_back();
1912
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001913 // Set the Parent field, then back to its old value once we're done.
1914 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1915
1916 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001917 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001918 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001919 if (!D)
1920 continue;
1921
1922 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001923 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001924 return true;
1925
1926 continue;
1927 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001928 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1929 const ExplicitTemplateArgumentList *ArgList =
1930 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1931 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1932 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1933 Arg != ArgEnd; ++Arg) {
1934 if (VisitTemplateArgumentLoc(*Arg))
1935 return true;
1936 }
1937 continue;
1938 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001939 case VisitorJob::TypeLocVisitKind: {
1940 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001941 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001942 return true;
1943 continue;
1944 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001945 case VisitorJob::LabelRefVisitKind: {
1946 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1947 if (Visit(MakeCursorLabelRef(LS,
1948 cast<LabelRefVisit>(&LI)->getLoc(),
1949 TU)))
1950 return true;
1951 continue;
1952 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001953 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001954 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001955 if (!S)
1956 continue;
1957
Ted Kremenekf1107452010-11-12 18:26:56 +00001958 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001959 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1960
1961 switch (S->getStmtClass()) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001962 // Cases not yet handled by the data-recursion
1963 // algorithm.
1964 case Stmt::OffsetOfExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001965 case Stmt::DesignatedInitExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001966 case Stmt::CXXPseudoDestructorExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001967 case Stmt::DependentScopeDeclRefExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001968 case Stmt::CXXDependentScopeMemberExprClass:
1969 if (Visit(Cursor))
1970 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001971 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001972 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001973 if (!IsInRegionOfInterest(Cursor))
1974 continue;
1975 switch (Visitor(Cursor, Parent, ClientData)) {
1976 case CXChildVisit_Break:
1977 return true;
1978 case CXChildVisit_Continue:
1979 break;
1980 case CXChildVisit_Recurse:
1981 EnqueueWorkList(WL, S);
1982 break;
1983 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001984 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001985 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001986 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001987 }
1988 case VisitorJob::MemberExprPartsKind: {
1989 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001990 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001991
1992 // Visit the nested-name-specifier
1993 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1994 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1995 return true;
1996
1997 // Visit the declaration name.
1998 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1999 return true;
2000
2001 // Visit the explicitly-specified template arguments, if any.
2002 if (M->hasExplicitTemplateArgs()) {
2003 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2004 *ArgEnd = Arg + M->getNumTemplateArgs();
2005 Arg != ArgEnd; ++Arg) {
2006 if (VisitTemplateArgumentLoc(*Arg))
2007 return true;
2008 }
2009 }
2010 continue;
2011 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002012 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002013 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002014 // Visit nested-name-specifier, if present.
2015 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2016 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2017 return true;
2018 // Visit declaration name.
2019 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2020 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002021 continue;
2022 }
Ted Kremenek60458782010-11-12 21:34:16 +00002023 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002024 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002025 // Visit the nested-name-specifier.
2026 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2027 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2028 return true;
2029 // Visit the declaration name.
2030 if (VisitDeclarationNameInfo(O->getNameInfo()))
2031 return true;
2032 // Visit the overloaded declaration reference.
2033 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2034 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002035 continue;
2036 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002037 }
2038 }
2039 return false;
2040}
2041
2042bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002043 VisitorWorkList *WL = 0;
2044 if (!WorkListFreeList.empty()) {
2045 WL = WorkListFreeList.back();
2046 WL->clear();
2047 WorkListFreeList.pop_back();
2048 }
2049 else {
2050 WL = new VisitorWorkList();
2051 WorkListCache.push_back(WL);
2052 }
2053 EnqueueWorkList(*WL, S);
2054 bool result = RunVisitorWorkList(*WL);
2055 WorkListFreeList.push_back(WL);
2056 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002057}
2058
2059//===----------------------------------------------------------------------===//
2060// Misc. API hooks.
2061//===----------------------------------------------------------------------===//
2062
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002063static llvm::sys::Mutex EnableMultithreadingMutex;
2064static bool EnabledMultithreading;
2065
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002066extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002067CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2068 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002069 // Disable pretty stack trace functionality, which will otherwise be a very
2070 // poor citizen of the world and set up all sorts of signal handlers.
2071 llvm::DisablePrettyStackTrace = true;
2072
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002073 // We use crash recovery to make some of our APIs more reliable, implicitly
2074 // enable it.
2075 llvm::CrashRecoveryContext::Enable();
2076
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002077 // Enable support for multithreading in LLVM.
2078 {
2079 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2080 if (!EnabledMultithreading) {
2081 llvm::llvm_start_multithreaded();
2082 EnabledMultithreading = true;
2083 }
2084 }
2085
Douglas Gregora030b7c2010-01-22 20:35:53 +00002086 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002087 if (excludeDeclarationsFromPCH)
2088 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002089 if (displayDiagnostics)
2090 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002091 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002092}
2093
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002094void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002095 if (CIdx)
2096 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002097}
2098
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002099CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002100 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002101 if (!CIdx)
2102 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002103
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002104 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002105 FileSystemOptions FileSystemOpts;
2106 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002107
Douglas Gregor28019772010-04-05 23:52:57 +00002108 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002109 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002110 CXXIdx->getOnlyLocalDecls(),
2111 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002112 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002113}
2114
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002115unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002116 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002117 CXTranslationUnit_CacheCompletionResults |
2118 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002119}
2120
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002121CXTranslationUnit
2122clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2123 const char *source_filename,
2124 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002125 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002126 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002127 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002128 return clang_parseTranslationUnit(CIdx, source_filename,
2129 command_line_args, num_command_line_args,
2130 unsaved_files, num_unsaved_files,
2131 CXTranslationUnit_DetailedPreprocessingRecord);
2132}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002133
2134struct ParseTranslationUnitInfo {
2135 CXIndex CIdx;
2136 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002137 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002138 int num_command_line_args;
2139 struct CXUnsavedFile *unsaved_files;
2140 unsigned num_unsaved_files;
2141 unsigned options;
2142 CXTranslationUnit result;
2143};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002144static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002145 ParseTranslationUnitInfo *PTUI =
2146 static_cast<ParseTranslationUnitInfo*>(UserData);
2147 CXIndex CIdx = PTUI->CIdx;
2148 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002149 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002150 int num_command_line_args = PTUI->num_command_line_args;
2151 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2152 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2153 unsigned options = PTUI->options;
2154 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002155
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002156 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002157 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002158
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002159 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2160
Douglas Gregor44c181a2010-07-23 00:33:23 +00002161 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002162 bool CompleteTranslationUnit
2163 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002164 bool CacheCodeCompetionResults
2165 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002166 bool CXXPrecompilePreamble
2167 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2168 bool CXXChainedPCH
2169 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002170
Douglas Gregor5352ac02010-01-28 00:27:43 +00002171 // Configure the diagnostics.
2172 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002173 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2174 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002175
Douglas Gregor4db64a42010-01-23 00:14:00 +00002176 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2177 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002178 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002180 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002181 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2182 Buffer));
2183 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002184
Douglas Gregorb10daed2010-10-11 16:52:23 +00002185 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002186
Ted Kremenek139ba862009-10-22 00:03:57 +00002187 // The 'source_filename' argument is optional. If the caller does not
2188 // specify it then it is assumed that the source file is specified
2189 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002190 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002191 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002192
2193 // Since the Clang C library is primarily used by batch tools dealing with
2194 // (often very broken) source code, where spell-checking can have a
2195 // significant negative impact on performance (particularly when
2196 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002197 // Only do this if we haven't found a spell-checking-related argument.
2198 bool FoundSpellCheckingArgument = false;
2199 for (int I = 0; I != num_command_line_args; ++I) {
2200 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2201 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2202 FoundSpellCheckingArgument = true;
2203 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002204 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002205 }
2206 if (!FoundSpellCheckingArgument)
2207 Args.push_back("-fno-spell-checking");
2208
2209 Args.insert(Args.end(), command_line_args,
2210 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002211
Douglas Gregor44c181a2010-07-23 00:33:23 +00002212 // Do we need the detailed preprocessing record?
2213 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002214 Args.push_back("-Xclang");
2215 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002216 }
2217
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002219 llvm::OwningPtr<ASTUnit> Unit(
2220 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2221 Diags,
2222 CXXIdx->getClangResourcesPath(),
2223 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002224 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002225 RemappedFiles.data(),
2226 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002227 PrecompilePreamble,
2228 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002229 CacheCodeCompetionResults,
2230 CXXPrecompilePreamble,
2231 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002232
Douglas Gregorb10daed2010-10-11 16:52:23 +00002233 if (NumErrors != Diags->getNumErrors()) {
2234 // Make sure to check that 'Unit' is non-NULL.
2235 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2236 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2237 DEnd = Unit->stored_diag_end();
2238 D != DEnd; ++D) {
2239 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2240 CXString Msg = clang_formatDiagnostic(&Diag,
2241 clang_defaultDiagnosticDisplayOptions());
2242 fprintf(stderr, "%s\n", clang_getCString(Msg));
2243 clang_disposeString(Msg);
2244 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002245#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002246 // On Windows, force a flush, since there may be multiple copies of
2247 // stderr and stdout in the file system, all with different buffers
2248 // but writing to the same device.
2249 fflush(stderr);
2250#endif
2251 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002252 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002253
Ted Kremeneka60ed472010-11-16 08:15:36 +00002254 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002255}
2256CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2257 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002258 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002259 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002260 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002261 unsigned num_unsaved_files,
2262 unsigned options) {
2263 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002264 num_command_line_args, unsaved_files,
2265 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002266 llvm::CrashRecoveryContext CRC;
2267
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002268 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002269 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2270 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2271 fprintf(stderr, " 'command_line_args' : [");
2272 for (int i = 0; i != num_command_line_args; ++i) {
2273 if (i)
2274 fprintf(stderr, ", ");
2275 fprintf(stderr, "'%s'", command_line_args[i]);
2276 }
2277 fprintf(stderr, "],\n");
2278 fprintf(stderr, " 'unsaved_files' : [");
2279 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2280 if (i)
2281 fprintf(stderr, ", ");
2282 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2283 unsaved_files[i].Length);
2284 }
2285 fprintf(stderr, "],\n");
2286 fprintf(stderr, " 'options' : %d,\n", options);
2287 fprintf(stderr, "}\n");
2288
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002289 return 0;
2290 }
2291
2292 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002293}
2294
Douglas Gregor19998442010-08-13 15:35:05 +00002295unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2296 return CXSaveTranslationUnit_None;
2297}
2298
2299int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2300 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002301 if (!TU)
2302 return 1;
2303
Ted Kremeneka60ed472010-11-16 08:15:36 +00002304 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002305}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002306
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002307void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002308 if (CTUnit) {
2309 // If the translation unit has been marked as unsafe to free, just discard
2310 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002311 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002312 return;
2313
Ted Kremeneka60ed472010-11-16 08:15:36 +00002314 delete static_cast<ASTUnit *>(CTUnit->TUData);
2315 disposeCXStringPool(CTUnit->StringPool);
2316 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002317 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002318}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002319
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002320unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2321 return CXReparse_None;
2322}
2323
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002324struct ReparseTranslationUnitInfo {
2325 CXTranslationUnit TU;
2326 unsigned num_unsaved_files;
2327 struct CXUnsavedFile *unsaved_files;
2328 unsigned options;
2329 int result;
2330};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002331
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002332static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002333 ReparseTranslationUnitInfo *RTUI =
2334 static_cast<ReparseTranslationUnitInfo*>(UserData);
2335 CXTranslationUnit TU = RTUI->TU;
2336 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2337 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2338 unsigned options = RTUI->options;
2339 (void) options;
2340 RTUI->result = 1;
2341
Douglas Gregorabc563f2010-07-19 21:46:24 +00002342 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002343 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002344
Ted Kremeneka60ed472010-11-16 08:15:36 +00002345 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002346 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002347
2348 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2349 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2350 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2351 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002352 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002353 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2354 Buffer));
2355 }
2356
Douglas Gregor593b0c12010-09-23 18:47:53 +00002357 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2358 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002359}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002360
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002361int clang_reparseTranslationUnit(CXTranslationUnit TU,
2362 unsigned num_unsaved_files,
2363 struct CXUnsavedFile *unsaved_files,
2364 unsigned options) {
2365 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2366 options, 0 };
2367 llvm::CrashRecoveryContext CRC;
2368
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002369 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002370 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002371 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002372 return 1;
2373 }
2374
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002375
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002376 return RTUI.result;
2377}
2378
Douglas Gregordf95a132010-08-09 20:45:32 +00002379
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002380CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002381 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002382 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002383
Ted Kremeneka60ed472010-11-16 08:15:36 +00002384 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002385 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002386}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002387
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002388CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002389 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002390 return Result;
2391}
2392
Ted Kremenekfb480492010-01-13 21:46:36 +00002393} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002394
Ted Kremenekfb480492010-01-13 21:46:36 +00002395//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002396// CXSourceLocation and CXSourceRange Operations.
2397//===----------------------------------------------------------------------===//
2398
Douglas Gregorb9790342010-01-22 21:44:22 +00002399extern "C" {
2400CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002401 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002402 return Result;
2403}
2404
2405unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002406 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2407 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2408 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002409}
2410
2411CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2412 CXFile file,
2413 unsigned line,
2414 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002415 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002416 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002417
Ted Kremeneka60ed472010-11-16 08:15:36 +00002418 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002419 SourceLocation SLoc
2420 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002421 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002422 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002423 if (SLoc.isInvalid()) return clang_getNullLocation();
2424
2425 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2426}
2427
2428CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2429 CXFile file,
2430 unsigned offset) {
2431 if (!tu || !file)
2432 return clang_getNullLocation();
2433
Ted Kremeneka60ed472010-11-16 08:15:36 +00002434 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002435 SourceLocation Start
2436 = CXXUnit->getSourceManager().getLocation(
2437 static_cast<const FileEntry *>(file),
2438 1, 1);
2439 if (Start.isInvalid()) return clang_getNullLocation();
2440
2441 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2442
2443 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002444
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002445 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002446}
2447
Douglas Gregor5352ac02010-01-28 00:27:43 +00002448CXSourceRange clang_getNullRange() {
2449 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2450 return Result;
2451}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002452
Douglas Gregor5352ac02010-01-28 00:27:43 +00002453CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2454 if (begin.ptr_data[0] != end.ptr_data[0] ||
2455 begin.ptr_data[1] != end.ptr_data[1])
2456 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
2458 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002459 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002460 return Result;
2461}
2462
Douglas Gregor46766dc2010-01-26 19:19:08 +00002463void clang_getInstantiationLocation(CXSourceLocation location,
2464 CXFile *file,
2465 unsigned *line,
2466 unsigned *column,
2467 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002468 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2469
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002470 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002471 if (file)
2472 *file = 0;
2473 if (line)
2474 *line = 0;
2475 if (column)
2476 *column = 0;
2477 if (offset)
2478 *offset = 0;
2479 return;
2480 }
2481
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002482 const SourceManager &SM =
2483 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002484 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002485
2486 if (file)
2487 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2488 if (line)
2489 *line = SM.getInstantiationLineNumber(InstLoc);
2490 if (column)
2491 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002492 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002493 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002494}
2495
Douglas Gregora9b06d42010-11-09 06:24:54 +00002496void clang_getSpellingLocation(CXSourceLocation location,
2497 CXFile *file,
2498 unsigned *line,
2499 unsigned *column,
2500 unsigned *offset) {
2501 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2502
2503 if (!location.ptr_data[0] || Loc.isInvalid()) {
2504 if (file)
2505 *file = 0;
2506 if (line)
2507 *line = 0;
2508 if (column)
2509 *column = 0;
2510 if (offset)
2511 *offset = 0;
2512 return;
2513 }
2514
2515 const SourceManager &SM =
2516 *static_cast<const SourceManager*>(location.ptr_data[0]);
2517 SourceLocation SpellLoc = Loc;
2518 if (SpellLoc.isMacroID()) {
2519 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2520 if (SimpleSpellingLoc.isFileID() &&
2521 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2522 SpellLoc = SimpleSpellingLoc;
2523 else
2524 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2525 }
2526
2527 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2528 FileID FID = LocInfo.first;
2529 unsigned FileOffset = LocInfo.second;
2530
2531 if (file)
2532 *file = (void *)SM.getFileEntryForID(FID);
2533 if (line)
2534 *line = SM.getLineNumber(FID, FileOffset);
2535 if (column)
2536 *column = SM.getColumnNumber(FID, FileOffset);
2537 if (offset)
2538 *offset = FileOffset;
2539}
2540
Douglas Gregor1db19de2010-01-19 21:36:55 +00002541CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002542 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002543 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002544 return Result;
2545}
2546
2547CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002548 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002549 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002550 return Result;
2551}
2552
Douglas Gregorb9790342010-01-22 21:44:22 +00002553} // end: extern "C"
2554
Douglas Gregor1db19de2010-01-19 21:36:55 +00002555//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002556// CXFile Operations.
2557//===----------------------------------------------------------------------===//
2558
2559extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002560CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002561 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002562 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563
Steve Naroff88145032009-10-27 14:35:18 +00002564 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002565 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002566}
2567
2568time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002569 if (!SFile)
2570 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002571
Steve Naroff88145032009-10-27 14:35:18 +00002572 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2573 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002574}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002575
Douglas Gregorb9790342010-01-22 21:44:22 +00002576CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2577 if (!tu)
2578 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002579
Ted Kremeneka60ed472010-11-16 08:15:36 +00002580 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Douglas Gregorb9790342010-01-22 21:44:22 +00002582 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002583 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2584 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002585 return const_cast<FileEntry *>(File);
2586}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002587
Ted Kremenekfb480492010-01-13 21:46:36 +00002588} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002589
Ted Kremenekfb480492010-01-13 21:46:36 +00002590//===----------------------------------------------------------------------===//
2591// CXCursor Operations.
2592//===----------------------------------------------------------------------===//
2593
Ted Kremenekfb480492010-01-13 21:46:36 +00002594static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002595 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2596 return getDeclFromExpr(CE->getSubExpr());
2597
Ted Kremenekfb480492010-01-13 21:46:36 +00002598 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2599 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002600 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2601 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002602 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2603 return ME->getMemberDecl();
2604 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2605 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002606 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2607 return PRE->getProperty();
2608
Ted Kremenekfb480492010-01-13 21:46:36 +00002609 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2610 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002611 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2612 if (!CE->isElidable())
2613 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002614 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2615 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002616
Douglas Gregordb1314e2010-10-01 21:11:22 +00002617 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2618 return PE->getProtocol();
2619
Ted Kremenekfb480492010-01-13 21:46:36 +00002620 return 0;
2621}
2622
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002623static SourceLocation getLocationFromExpr(Expr *E) {
2624 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2625 return /*FIXME:*/Msg->getLeftLoc();
2626 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2627 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002628 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2629 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002630 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2631 return Member->getMemberLoc();
2632 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2633 return Ivar->getLocation();
2634 return E->getLocStart();
2635}
2636
Ted Kremenekfb480492010-01-13 21:46:36 +00002637extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002638
2639unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002640 CXCursorVisitor visitor,
2641 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002642 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2643 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002644 return CursorVis.VisitChildren(parent);
2645}
2646
David Chisnall3387c652010-11-03 14:12:26 +00002647#ifndef __has_feature
2648#define __has_feature(x) 0
2649#endif
2650#if __has_feature(blocks)
2651typedef enum CXChildVisitResult
2652 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2653
2654static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2655 CXClientData client_data) {
2656 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2657 return block(cursor, parent);
2658}
2659#else
2660// If we are compiled with a compiler that doesn't have native blocks support,
2661// define and call the block manually, so the
2662typedef struct _CXChildVisitResult
2663{
2664 void *isa;
2665 int flags;
2666 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002667 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2668 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002669} *CXCursorVisitorBlock;
2670
2671static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2672 CXClientData client_data) {
2673 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2674 return block->invoke(block, cursor, parent);
2675}
2676#endif
2677
2678
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002679unsigned clang_visitChildrenWithBlock(CXCursor parent,
2680 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002681 return clang_visitChildren(parent, visitWithBlock, block);
2682}
2683
Douglas Gregor78205d42010-01-20 21:45:58 +00002684static CXString getDeclSpelling(Decl *D) {
2685 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002686 if (!ND) {
2687 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2688 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2689 return createCXString(Property->getIdentifier()->getName());
2690
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002691 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002692 }
2693
Douglas Gregor78205d42010-01-20 21:45:58 +00002694 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002695 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002696
Douglas Gregor78205d42010-01-20 21:45:58 +00002697 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2698 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2699 // and returns different names. NamedDecl returns the class name and
2700 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002701 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002702
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002703 if (isa<UsingDirectiveDecl>(D))
2704 return createCXString("");
2705
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002706 llvm::SmallString<1024> S;
2707 llvm::raw_svector_ostream os(S);
2708 ND->printName(os);
2709
2710 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002711}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002712
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002713CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002714 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002715 return clang_getTranslationUnitSpelling(
2716 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002717
Steve Narofff334b4e2009-09-02 18:26:48 +00002718 if (clang_isReference(C.kind)) {
2719 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002720 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002721 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002722 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002723 }
2724 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002725 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002726 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002727 }
2728 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002729 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002730 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002731 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002732 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002733 case CXCursor_CXXBaseSpecifier: {
2734 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2735 return createCXString(B->getType().getAsString());
2736 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002737 case CXCursor_TypeRef: {
2738 TypeDecl *Type = getCursorTypeRef(C).first;
2739 assert(Type && "Missing type decl");
2740
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002741 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2742 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002743 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002744 case CXCursor_TemplateRef: {
2745 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002746 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002747
2748 return createCXString(Template->getNameAsString());
2749 }
Douglas Gregor69319002010-08-31 23:48:11 +00002750
2751 case CXCursor_NamespaceRef: {
2752 NamedDecl *NS = getCursorNamespaceRef(C).first;
2753 assert(NS && "Missing namespace decl");
2754
2755 return createCXString(NS->getNameAsString());
2756 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002757
Douglas Gregora67e03f2010-09-09 21:42:20 +00002758 case CXCursor_MemberRef: {
2759 FieldDecl *Field = getCursorMemberRef(C).first;
2760 assert(Field && "Missing member decl");
2761
2762 return createCXString(Field->getNameAsString());
2763 }
2764
Douglas Gregor36897b02010-09-10 00:22:18 +00002765 case CXCursor_LabelRef: {
2766 LabelStmt *Label = getCursorLabelRef(C).first;
2767 assert(Label && "Missing label");
2768
2769 return createCXString(Label->getID()->getName());
2770 }
2771
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002772 case CXCursor_OverloadedDeclRef: {
2773 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2774 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2775 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2776 return createCXString(ND->getNameAsString());
2777 return createCXString("");
2778 }
2779 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2780 return createCXString(E->getName().getAsString());
2781 OverloadedTemplateStorage *Ovl
2782 = Storage.get<OverloadedTemplateStorage*>();
2783 if (Ovl->size() == 0)
2784 return createCXString("");
2785 return createCXString((*Ovl->begin())->getNameAsString());
2786 }
2787
Daniel Dunbaracca7252009-11-30 20:42:49 +00002788 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002789 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002790 }
2791 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002792
2793 if (clang_isExpression(C.kind)) {
2794 Decl *D = getDeclFromExpr(getCursorExpr(C));
2795 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002796 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002797 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002798 }
2799
Douglas Gregor36897b02010-09-10 00:22:18 +00002800 if (clang_isStatement(C.kind)) {
2801 Stmt *S = getCursorStmt(C);
2802 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2803 return createCXString(Label->getID()->getName());
2804
2805 return createCXString("");
2806 }
2807
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002808 if (C.kind == CXCursor_MacroInstantiation)
2809 return createCXString(getCursorMacroInstantiation(C)->getName()
2810 ->getNameStart());
2811
Douglas Gregor572feb22010-03-18 18:04:21 +00002812 if (C.kind == CXCursor_MacroDefinition)
2813 return createCXString(getCursorMacroDefinition(C)->getName()
2814 ->getNameStart());
2815
Douglas Gregorecdcb882010-10-20 22:00:55 +00002816 if (C.kind == CXCursor_InclusionDirective)
2817 return createCXString(getCursorInclusionDirective(C)->getFileName());
2818
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002819 if (clang_isDeclaration(C.kind))
2820 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002821
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002822 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002823}
2824
Douglas Gregor358559d2010-10-02 22:49:11 +00002825CXString clang_getCursorDisplayName(CXCursor C) {
2826 if (!clang_isDeclaration(C.kind))
2827 return clang_getCursorSpelling(C);
2828
2829 Decl *D = getCursorDecl(C);
2830 if (!D)
2831 return createCXString("");
2832
2833 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2834 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2835 D = FunTmpl->getTemplatedDecl();
2836
2837 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2838 llvm::SmallString<64> Str;
2839 llvm::raw_svector_ostream OS(Str);
2840 OS << Function->getNameAsString();
2841 if (Function->getPrimaryTemplate())
2842 OS << "<>";
2843 OS << "(";
2844 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2845 if (I)
2846 OS << ", ";
2847 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2848 }
2849
2850 if (Function->isVariadic()) {
2851 if (Function->getNumParams())
2852 OS << ", ";
2853 OS << "...";
2854 }
2855 OS << ")";
2856 return createCXString(OS.str());
2857 }
2858
2859 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2860 llvm::SmallString<64> Str;
2861 llvm::raw_svector_ostream OS(Str);
2862 OS << ClassTemplate->getNameAsString();
2863 OS << "<";
2864 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2865 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2866 if (I)
2867 OS << ", ";
2868
2869 NamedDecl *Param = Params->getParam(I);
2870 if (Param->getIdentifier()) {
2871 OS << Param->getIdentifier()->getName();
2872 continue;
2873 }
2874
2875 // There is no parameter name, which makes this tricky. Try to come up
2876 // with something useful that isn't too long.
2877 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2878 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2879 else if (NonTypeTemplateParmDecl *NTTP
2880 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2881 OS << NTTP->getType().getAsString(Policy);
2882 else
2883 OS << "template<...> class";
2884 }
2885
2886 OS << ">";
2887 return createCXString(OS.str());
2888 }
2889
2890 if (ClassTemplateSpecializationDecl *ClassSpec
2891 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2892 // If the type was explicitly written, use that.
2893 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2894 return createCXString(TSInfo->getType().getAsString(Policy));
2895
2896 llvm::SmallString<64> Str;
2897 llvm::raw_svector_ostream OS(Str);
2898 OS << ClassSpec->getNameAsString();
2899 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002900 ClassSpec->getTemplateArgs().data(),
2901 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002902 Policy);
2903 return createCXString(OS.str());
2904 }
2905
2906 return clang_getCursorSpelling(C);
2907}
2908
Ted Kremeneke68fff62010-02-17 00:41:32 +00002909CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002910 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002911 case CXCursor_FunctionDecl:
2912 return createCXString("FunctionDecl");
2913 case CXCursor_TypedefDecl:
2914 return createCXString("TypedefDecl");
2915 case CXCursor_EnumDecl:
2916 return createCXString("EnumDecl");
2917 case CXCursor_EnumConstantDecl:
2918 return createCXString("EnumConstantDecl");
2919 case CXCursor_StructDecl:
2920 return createCXString("StructDecl");
2921 case CXCursor_UnionDecl:
2922 return createCXString("UnionDecl");
2923 case CXCursor_ClassDecl:
2924 return createCXString("ClassDecl");
2925 case CXCursor_FieldDecl:
2926 return createCXString("FieldDecl");
2927 case CXCursor_VarDecl:
2928 return createCXString("VarDecl");
2929 case CXCursor_ParmDecl:
2930 return createCXString("ParmDecl");
2931 case CXCursor_ObjCInterfaceDecl:
2932 return createCXString("ObjCInterfaceDecl");
2933 case CXCursor_ObjCCategoryDecl:
2934 return createCXString("ObjCCategoryDecl");
2935 case CXCursor_ObjCProtocolDecl:
2936 return createCXString("ObjCProtocolDecl");
2937 case CXCursor_ObjCPropertyDecl:
2938 return createCXString("ObjCPropertyDecl");
2939 case CXCursor_ObjCIvarDecl:
2940 return createCXString("ObjCIvarDecl");
2941 case CXCursor_ObjCInstanceMethodDecl:
2942 return createCXString("ObjCInstanceMethodDecl");
2943 case CXCursor_ObjCClassMethodDecl:
2944 return createCXString("ObjCClassMethodDecl");
2945 case CXCursor_ObjCImplementationDecl:
2946 return createCXString("ObjCImplementationDecl");
2947 case CXCursor_ObjCCategoryImplDecl:
2948 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002949 case CXCursor_CXXMethod:
2950 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002951 case CXCursor_UnexposedDecl:
2952 return createCXString("UnexposedDecl");
2953 case CXCursor_ObjCSuperClassRef:
2954 return createCXString("ObjCSuperClassRef");
2955 case CXCursor_ObjCProtocolRef:
2956 return createCXString("ObjCProtocolRef");
2957 case CXCursor_ObjCClassRef:
2958 return createCXString("ObjCClassRef");
2959 case CXCursor_TypeRef:
2960 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002961 case CXCursor_TemplateRef:
2962 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002963 case CXCursor_NamespaceRef:
2964 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002965 case CXCursor_MemberRef:
2966 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002967 case CXCursor_LabelRef:
2968 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002969 case CXCursor_OverloadedDeclRef:
2970 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002971 case CXCursor_UnexposedExpr:
2972 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002973 case CXCursor_BlockExpr:
2974 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002975 case CXCursor_DeclRefExpr:
2976 return createCXString("DeclRefExpr");
2977 case CXCursor_MemberRefExpr:
2978 return createCXString("MemberRefExpr");
2979 case CXCursor_CallExpr:
2980 return createCXString("CallExpr");
2981 case CXCursor_ObjCMessageExpr:
2982 return createCXString("ObjCMessageExpr");
2983 case CXCursor_UnexposedStmt:
2984 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002985 case CXCursor_LabelStmt:
2986 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002987 case CXCursor_InvalidFile:
2988 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002989 case CXCursor_InvalidCode:
2990 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002991 case CXCursor_NoDeclFound:
2992 return createCXString("NoDeclFound");
2993 case CXCursor_NotImplemented:
2994 return createCXString("NotImplemented");
2995 case CXCursor_TranslationUnit:
2996 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002997 case CXCursor_UnexposedAttr:
2998 return createCXString("UnexposedAttr");
2999 case CXCursor_IBActionAttr:
3000 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003001 case CXCursor_IBOutletAttr:
3002 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003003 case CXCursor_IBOutletCollectionAttr:
3004 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003005 case CXCursor_PreprocessingDirective:
3006 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003007 case CXCursor_MacroDefinition:
3008 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003009 case CXCursor_MacroInstantiation:
3010 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003011 case CXCursor_InclusionDirective:
3012 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003013 case CXCursor_Namespace:
3014 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003015 case CXCursor_LinkageSpec:
3016 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003017 case CXCursor_CXXBaseSpecifier:
3018 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003019 case CXCursor_Constructor:
3020 return createCXString("CXXConstructor");
3021 case CXCursor_Destructor:
3022 return createCXString("CXXDestructor");
3023 case CXCursor_ConversionFunction:
3024 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003025 case CXCursor_TemplateTypeParameter:
3026 return createCXString("TemplateTypeParameter");
3027 case CXCursor_NonTypeTemplateParameter:
3028 return createCXString("NonTypeTemplateParameter");
3029 case CXCursor_TemplateTemplateParameter:
3030 return createCXString("TemplateTemplateParameter");
3031 case CXCursor_FunctionTemplate:
3032 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003033 case CXCursor_ClassTemplate:
3034 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003035 case CXCursor_ClassTemplatePartialSpecialization:
3036 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003037 case CXCursor_NamespaceAlias:
3038 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003039 case CXCursor_UsingDirective:
3040 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003041 case CXCursor_UsingDeclaration:
3042 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003043 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003044
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003045 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003046 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003047}
Steve Naroff89922f82009-08-31 00:59:03 +00003048
Ted Kremeneke68fff62010-02-17 00:41:32 +00003049enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3050 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003051 CXClientData client_data) {
3052 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003053
3054 // If our current best cursor is the construction of a temporary object,
3055 // don't replace that cursor with a type reference, because we want
3056 // clang_getCursor() to point at the constructor.
3057 if (clang_isExpression(BestCursor->kind) &&
3058 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3059 cursor.kind == CXCursor_TypeRef)
3060 return CXChildVisit_Recurse;
3061
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003062 *BestCursor = cursor;
3063 return CXChildVisit_Recurse;
3064}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003065
Douglas Gregorb9790342010-01-22 21:44:22 +00003066CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3067 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003068 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003069
Ted Kremeneka60ed472010-11-16 08:15:36 +00003070 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003071 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3072
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003073 // Translate the given source location to make it point at the beginning of
3074 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003075 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003076
3077 // Guard against an invalid SourceLocation, or we may assert in one
3078 // of the following calls.
3079 if (SLoc.isInvalid())
3080 return clang_getNullCursor();
3081
Douglas Gregor40749ee2010-11-03 00:35:38 +00003082 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003083 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3084 CXXUnit->getASTContext().getLangOptions());
3085
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003086 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3087 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003088 // FIXME: Would be great to have a "hint" cursor, then walk from that
3089 // hint cursor upward until we find a cursor whose source range encloses
3090 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003091 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3092 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003093 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003094 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003095 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003096
3097 if (Logging) {
3098 CXFile SearchFile;
3099 unsigned SearchLine, SearchColumn;
3100 CXFile ResultFile;
3101 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003102 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3103 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003104 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3105
3106 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3107 0);
3108 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3109 &ResultColumn, 0);
3110 SearchFileName = clang_getFileName(SearchFile);
3111 ResultFileName = clang_getFileName(ResultFile);
3112 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003113 USR = clang_getCursorUSR(Result);
3114 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003115 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3116 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003117 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3118 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003119 clang_disposeString(SearchFileName);
3120 clang_disposeString(ResultFileName);
3121 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003122 clang_disposeString(USR);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003123 }
3124
Ted Kremeneke68fff62010-02-17 00:41:32 +00003125 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003126}
3127
Ted Kremenek73885552009-11-17 19:28:59 +00003128CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003129 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003130}
3131
3132unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003133 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003134}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003135
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003136unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003137 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3138}
3139
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003140unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003141 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3142}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003143
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003144unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003145 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3146}
3147
Douglas Gregor97b98722010-01-19 23:20:36 +00003148unsigned clang_isExpression(enum CXCursorKind K) {
3149 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3150}
3151
3152unsigned clang_isStatement(enum CXCursorKind K) {
3153 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3154}
3155
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003156unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3157 return K == CXCursor_TranslationUnit;
3158}
3159
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003160unsigned clang_isPreprocessing(enum CXCursorKind K) {
3161 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3162}
3163
Ted Kremenekad6eff62010-03-08 21:17:29 +00003164unsigned clang_isUnexposed(enum CXCursorKind K) {
3165 switch (K) {
3166 case CXCursor_UnexposedDecl:
3167 case CXCursor_UnexposedExpr:
3168 case CXCursor_UnexposedStmt:
3169 case CXCursor_UnexposedAttr:
3170 return true;
3171 default:
3172 return false;
3173 }
3174}
3175
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003176CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003177 return C.kind;
3178}
3179
Douglas Gregor98258af2010-01-18 22:46:11 +00003180CXSourceLocation clang_getCursorLocation(CXCursor C) {
3181 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003182 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003183 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003184 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3185 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003186 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003187 }
3188
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003189 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003190 std::pair<ObjCProtocolDecl *, SourceLocation> P
3191 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003192 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003193 }
3194
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003195 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003196 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3197 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003198 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003199 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003200
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003201 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003202 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003203 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003204 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003205
3206 case CXCursor_TemplateRef: {
3207 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3208 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3209 }
3210
Douglas Gregor69319002010-08-31 23:48:11 +00003211 case CXCursor_NamespaceRef: {
3212 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3213 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3214 }
3215
Douglas Gregora67e03f2010-09-09 21:42:20 +00003216 case CXCursor_MemberRef: {
3217 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3218 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3219 }
3220
Ted Kremenek3064ef92010-08-27 21:34:58 +00003221 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003222 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3223 if (!BaseSpec)
3224 return clang_getNullLocation();
3225
3226 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3227 return cxloc::translateSourceLocation(getCursorContext(C),
3228 TSInfo->getTypeLoc().getBeginLoc());
3229
3230 return cxloc::translateSourceLocation(getCursorContext(C),
3231 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003232 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003233
Douglas Gregor36897b02010-09-10 00:22:18 +00003234 case CXCursor_LabelRef: {
3235 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3236 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3237 }
3238
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003239 case CXCursor_OverloadedDeclRef:
3240 return cxloc::translateSourceLocation(getCursorContext(C),
3241 getCursorOverloadedDeclRef(C).second);
3242
Douglas Gregorf46034a2010-01-18 23:41:10 +00003243 default:
3244 // FIXME: Need a way to enumerate all non-reference cases.
3245 llvm_unreachable("Missed a reference kind");
3246 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003247 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003248
3249 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003250 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003251 getLocationFromExpr(getCursorExpr(C)));
3252
Douglas Gregor36897b02010-09-10 00:22:18 +00003253 if (clang_isStatement(C.kind))
3254 return cxloc::translateSourceLocation(getCursorContext(C),
3255 getCursorStmt(C)->getLocStart());
3256
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003257 if (C.kind == CXCursor_PreprocessingDirective) {
3258 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3259 return cxloc::translateSourceLocation(getCursorContext(C), L);
3260 }
Douglas Gregor48072312010-03-18 15:23:44 +00003261
3262 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003263 SourceLocation L
3264 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003265 return cxloc::translateSourceLocation(getCursorContext(C), L);
3266 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003267
3268 if (C.kind == CXCursor_MacroDefinition) {
3269 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3270 return cxloc::translateSourceLocation(getCursorContext(C), L);
3271 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003272
3273 if (C.kind == CXCursor_InclusionDirective) {
3274 SourceLocation L
3275 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3276 return cxloc::translateSourceLocation(getCursorContext(C), L);
3277 }
3278
Ted Kremenek9a700d22010-05-12 06:16:13 +00003279 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003280 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003281
Douglas Gregorf46034a2010-01-18 23:41:10 +00003282 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003283 SourceLocation Loc = D->getLocation();
3284 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3285 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003286 // FIXME: Multiple variables declared in a single declaration
3287 // currently lack the information needed to correctly determine their
3288 // ranges when accounting for the type-specifier. We use context
3289 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3290 // and if so, whether it is the first decl.
3291 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3292 if (!cxcursor::isFirstInDeclGroup(C))
3293 Loc = VD->getLocation();
3294 }
3295
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003296 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003297}
Douglas Gregora7bde202010-01-19 00:34:46 +00003298
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003299} // end extern "C"
3300
3301static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003302 if (clang_isReference(C.kind)) {
3303 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003304 case CXCursor_ObjCSuperClassRef:
3305 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003306
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003307 case CXCursor_ObjCProtocolRef:
3308 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003309
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003310 case CXCursor_ObjCClassRef:
3311 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003312
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003313 case CXCursor_TypeRef:
3314 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003315
3316 case CXCursor_TemplateRef:
3317 return getCursorTemplateRef(C).second;
3318
Douglas Gregor69319002010-08-31 23:48:11 +00003319 case CXCursor_NamespaceRef:
3320 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003321
3322 case CXCursor_MemberRef:
3323 return getCursorMemberRef(C).second;
3324
Ted Kremenek3064ef92010-08-27 21:34:58 +00003325 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003326 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003327
Douglas Gregor36897b02010-09-10 00:22:18 +00003328 case CXCursor_LabelRef:
3329 return getCursorLabelRef(C).second;
3330
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003331 case CXCursor_OverloadedDeclRef:
3332 return getCursorOverloadedDeclRef(C).second;
3333
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003334 default:
3335 // FIXME: Need a way to enumerate all non-reference cases.
3336 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003337 }
3338 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003339
3340 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003341 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003342
3343 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003344 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003345
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003346 if (C.kind == CXCursor_PreprocessingDirective)
3347 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003348
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003349 if (C.kind == CXCursor_MacroInstantiation)
3350 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003351
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003352 if (C.kind == CXCursor_MacroDefinition)
3353 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003354
3355 if (C.kind == CXCursor_InclusionDirective)
3356 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3357
Ted Kremenek007a7c92010-11-01 23:26:51 +00003358 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3359 Decl *D = cxcursor::getCursorDecl(C);
3360 SourceRange R = D->getSourceRange();
3361 // FIXME: Multiple variables declared in a single declaration
3362 // currently lack the information needed to correctly determine their
3363 // ranges when accounting for the type-specifier. We use context
3364 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3365 // and if so, whether it is the first decl.
3366 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3367 if (!cxcursor::isFirstInDeclGroup(C))
3368 R.setBegin(VD->getLocation());
3369 }
3370 return R;
3371 }
Douglas Gregor66537982010-11-17 17:14:07 +00003372 return SourceRange();
3373}
3374
3375/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3376/// the decl-specifier-seq for declarations.
3377static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3378 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3379 Decl *D = cxcursor::getCursorDecl(C);
3380 SourceRange R = D->getSourceRange();
3381
3382 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3383 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3384 TypeLoc TL = TI->getTypeLoc();
3385 SourceLocation TLoc = TL.getSourceRange().getBegin();
3386 if (TLoc.isValid() && R.getBegin().isValid() &&
3387 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3388 R.setBegin(TLoc);
3389 }
3390
3391 // FIXME: Multiple variables declared in a single declaration
3392 // currently lack the information needed to correctly determine their
3393 // ranges when accounting for the type-specifier. We use context
3394 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3395 // and if so, whether it is the first decl.
3396 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3397 if (!cxcursor::isFirstInDeclGroup(C))
3398 R.setBegin(VD->getLocation());
3399 }
3400 }
3401
3402 return R;
3403 }
3404
3405 return getRawCursorExtent(C);
3406}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003407
3408extern "C" {
3409
3410CXSourceRange clang_getCursorExtent(CXCursor C) {
3411 SourceRange R = getRawCursorExtent(C);
3412 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003413 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003414
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003415 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003416}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003417
3418CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003419 if (clang_isInvalid(C.kind))
3420 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003421
Ted Kremeneka60ed472010-11-16 08:15:36 +00003422 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003423 if (clang_isDeclaration(C.kind)) {
3424 Decl *D = getCursorDecl(C);
3425 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003426 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003427 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003428 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003429 if (ObjCForwardProtocolDecl *Protocols
3430 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003431 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003432 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3433 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3434 return MakeCXCursor(Property, tu);
3435
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003436 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003437 }
3438
Douglas Gregor97b98722010-01-19 23:20:36 +00003439 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003440 Expr *E = getCursorExpr(C);
3441 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003442 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003443 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003444
3445 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003446 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003447
Douglas Gregor97b98722010-01-19 23:20:36 +00003448 return clang_getNullCursor();
3449 }
3450
Douglas Gregor36897b02010-09-10 00:22:18 +00003451 if (clang_isStatement(C.kind)) {
3452 Stmt *S = getCursorStmt(C);
3453 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003454 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003455
3456 return clang_getNullCursor();
3457 }
3458
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003459 if (C.kind == CXCursor_MacroInstantiation) {
3460 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003461 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003462 }
3463
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003464 if (!clang_isReference(C.kind))
3465 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003466
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003467 switch (C.kind) {
3468 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003469 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003470
3471 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003472 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003473
3474 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003475 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003476
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003477 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003478 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003479
3480 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003481 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003482
Douglas Gregor69319002010-08-31 23:48:11 +00003483 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003484 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003485
Douglas Gregora67e03f2010-09-09 21:42:20 +00003486 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003487 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003488
Ted Kremenek3064ef92010-08-27 21:34:58 +00003489 case CXCursor_CXXBaseSpecifier: {
3490 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3491 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003492 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003493 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003494
Douglas Gregor36897b02010-09-10 00:22:18 +00003495 case CXCursor_LabelRef:
3496 // FIXME: We end up faking the "parent" declaration here because we
3497 // don't want to make CXCursor larger.
3498 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003499 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3500 .getTranslationUnitDecl(),
3501 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003502
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003503 case CXCursor_OverloadedDeclRef:
3504 return C;
3505
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003506 default:
3507 // We would prefer to enumerate all non-reference cursor kinds here.
3508 llvm_unreachable("Unhandled reference cursor kind");
3509 break;
3510 }
3511 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003512
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003513 return clang_getNullCursor();
3514}
3515
Douglas Gregorb6998662010-01-19 19:34:47 +00003516CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003517 if (clang_isInvalid(C.kind))
3518 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003519
Ted Kremeneka60ed472010-11-16 08:15:36 +00003520 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003521
Douglas Gregorb6998662010-01-19 19:34:47 +00003522 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003523 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003524 C = clang_getCursorReferenced(C);
3525 WasReference = true;
3526 }
3527
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003528 if (C.kind == CXCursor_MacroInstantiation)
3529 return clang_getCursorReferenced(C);
3530
Douglas Gregorb6998662010-01-19 19:34:47 +00003531 if (!clang_isDeclaration(C.kind))
3532 return clang_getNullCursor();
3533
3534 Decl *D = getCursorDecl(C);
3535 if (!D)
3536 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003537
Douglas Gregorb6998662010-01-19 19:34:47 +00003538 switch (D->getKind()) {
3539 // Declaration kinds that don't really separate the notions of
3540 // declaration and definition.
3541 case Decl::Namespace:
3542 case Decl::Typedef:
3543 case Decl::TemplateTypeParm:
3544 case Decl::EnumConstant:
3545 case Decl::Field:
3546 case Decl::ObjCIvar:
3547 case Decl::ObjCAtDefsField:
3548 case Decl::ImplicitParam:
3549 case Decl::ParmVar:
3550 case Decl::NonTypeTemplateParm:
3551 case Decl::TemplateTemplateParm:
3552 case Decl::ObjCCategoryImpl:
3553 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003554 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003555 case Decl::LinkageSpec:
3556 case Decl::ObjCPropertyImpl:
3557 case Decl::FileScopeAsm:
3558 case Decl::StaticAssert:
3559 case Decl::Block:
3560 return C;
3561
3562 // Declaration kinds that don't make any sense here, but are
3563 // nonetheless harmless.
3564 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003565 break;
3566
3567 // Declaration kinds for which the definition is not resolvable.
3568 case Decl::UnresolvedUsingTypename:
3569 case Decl::UnresolvedUsingValue:
3570 break;
3571
3572 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003573 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003574 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003575
3576 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003577 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003578
3579 case Decl::Enum:
3580 case Decl::Record:
3581 case Decl::CXXRecord:
3582 case Decl::ClassTemplateSpecialization:
3583 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003584 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003585 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003586 return clang_getNullCursor();
3587
3588 case Decl::Function:
3589 case Decl::CXXMethod:
3590 case Decl::CXXConstructor:
3591 case Decl::CXXDestructor:
3592 case Decl::CXXConversion: {
3593 const FunctionDecl *Def = 0;
3594 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003595 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003596 return clang_getNullCursor();
3597 }
3598
3599 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003600 // Ask the variable if it has a definition.
3601 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003602 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003603 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003604 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003605
Douglas Gregorb6998662010-01-19 19:34:47 +00003606 case Decl::FunctionTemplate: {
3607 const FunctionDecl *Def = 0;
3608 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003609 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003610 return clang_getNullCursor();
3611 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003612
Douglas Gregorb6998662010-01-19 19:34:47 +00003613 case Decl::ClassTemplate: {
3614 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003615 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003616 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003617 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003618 return clang_getNullCursor();
3619 }
3620
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003621 case Decl::Using:
3622 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003623 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003624
3625 case Decl::UsingShadow:
3626 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003627 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003628 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003629
3630 case Decl::ObjCMethod: {
3631 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3632 if (Method->isThisDeclarationADefinition())
3633 return C;
3634
3635 // Dig out the method definition in the associated
3636 // @implementation, if we have it.
3637 // FIXME: The ASTs should make finding the definition easier.
3638 if (ObjCInterfaceDecl *Class
3639 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3640 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3641 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3642 Method->isInstanceMethod()))
3643 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003644 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003645
3646 return clang_getNullCursor();
3647 }
3648
3649 case Decl::ObjCCategory:
3650 if (ObjCCategoryImplDecl *Impl
3651 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003652 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003653 return clang_getNullCursor();
3654
3655 case Decl::ObjCProtocol:
3656 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3657 return C;
3658 return clang_getNullCursor();
3659
3660 case Decl::ObjCInterface:
3661 // There are two notions of a "definition" for an Objective-C
3662 // class: the interface and its implementation. When we resolved a
3663 // reference to an Objective-C class, produce the @interface as
3664 // the definition; when we were provided with the interface,
3665 // produce the @implementation as the definition.
3666 if (WasReference) {
3667 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3668 return C;
3669 } else if (ObjCImplementationDecl *Impl
3670 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003671 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003672 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003673
Douglas Gregorb6998662010-01-19 19:34:47 +00003674 case Decl::ObjCProperty:
3675 // FIXME: We don't really know where to find the
3676 // ObjCPropertyImplDecls that implement this property.
3677 return clang_getNullCursor();
3678
3679 case Decl::ObjCCompatibleAlias:
3680 if (ObjCInterfaceDecl *Class
3681 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3682 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003683 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003684
Douglas Gregorb6998662010-01-19 19:34:47 +00003685 return clang_getNullCursor();
3686
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003687 case Decl::ObjCForwardProtocol:
3688 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003689 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003690
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003691 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003692 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003693 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003694
3695 case Decl::Friend:
3696 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003697 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003698 return clang_getNullCursor();
3699
3700 case Decl::FriendTemplate:
3701 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003702 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003703 return clang_getNullCursor();
3704 }
3705
3706 return clang_getNullCursor();
3707}
3708
3709unsigned clang_isCursorDefinition(CXCursor C) {
3710 if (!clang_isDeclaration(C.kind))
3711 return 0;
3712
3713 return clang_getCursorDefinition(C) == C;
3714}
3715
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003716unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003717 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003718 return 0;
3719
3720 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3721 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3722 return E->getNumDecls();
3723
3724 if (OverloadedTemplateStorage *S
3725 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3726 return S->size();
3727
3728 Decl *D = Storage.get<Decl*>();
3729 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003730 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003731 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3732 return Classes->size();
3733 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3734 return Protocols->protocol_size();
3735
3736 return 0;
3737}
3738
3739CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003740 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003741 return clang_getNullCursor();
3742
3743 if (index >= clang_getNumOverloadedDecls(cursor))
3744 return clang_getNullCursor();
3745
Ted Kremeneka60ed472010-11-16 08:15:36 +00003746 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003747 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3748 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003749 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003750
3751 if (OverloadedTemplateStorage *S
3752 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003753 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003754
3755 Decl *D = Storage.get<Decl*>();
3756 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3757 // FIXME: This is, unfortunately, linear time.
3758 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3759 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003760 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003761 }
3762
3763 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003764 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003765
3766 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003767 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003768
3769 return clang_getNullCursor();
3770}
3771
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003772void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003773 const char **startBuf,
3774 const char **endBuf,
3775 unsigned *startLine,
3776 unsigned *startColumn,
3777 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003778 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003779 assert(getCursorDecl(C) && "CXCursor has null decl");
3780 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003781 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3782 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003783
Steve Naroff4ade6d62009-09-23 17:52:52 +00003784 SourceManager &SM = FD->getASTContext().getSourceManager();
3785 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3786 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3787 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3788 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3789 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3790 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3791}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003792
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003793void clang_enableStackTraces(void) {
3794 llvm::sys::PrintStackTraceOnErrorSignal();
3795}
3796
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003797void clang_executeOnThread(void (*fn)(void*), void *user_data,
3798 unsigned stack_size) {
3799 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3800}
3801
Ted Kremenekfb480492010-01-13 21:46:36 +00003802} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003803
Ted Kremenekfb480492010-01-13 21:46:36 +00003804//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003805// Token-based Operations.
3806//===----------------------------------------------------------------------===//
3807
3808/* CXToken layout:
3809 * int_data[0]: a CXTokenKind
3810 * int_data[1]: starting token location
3811 * int_data[2]: token length
3812 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003813 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003814 * otherwise unused.
3815 */
3816extern "C" {
3817
3818CXTokenKind clang_getTokenKind(CXToken CXTok) {
3819 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3820}
3821
3822CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3823 switch (clang_getTokenKind(CXTok)) {
3824 case CXToken_Identifier:
3825 case CXToken_Keyword:
3826 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003827 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3828 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003829
3830 case CXToken_Literal: {
3831 // We have stashed the starting pointer in the ptr_data field. Use it.
3832 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003833 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003836 case CXToken_Punctuation:
3837 case CXToken_Comment:
3838 break;
3839 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003840
3841 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003842 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003843 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003844 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003845 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003847 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3848 std::pair<FileID, unsigned> LocInfo
3849 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003850 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003851 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003852 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3853 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003854 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003856 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003857}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003860 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003861 if (!CXXUnit)
3862 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3865 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3866}
3867
3868CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003869 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003870 if (!CXXUnit)
3871 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003872
3873 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3875}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003876
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003877void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3878 CXToken **Tokens, unsigned *NumTokens) {
3879 if (Tokens)
3880 *Tokens = 0;
3881 if (NumTokens)
3882 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003883
Ted Kremeneka60ed472010-11-16 08:15:36 +00003884 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003885 if (!CXXUnit || !Tokens || !NumTokens)
3886 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887
Douglas Gregorbdf60622010-03-05 21:16:25 +00003888 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3889
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003890 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891 if (R.isInvalid())
3892 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003893
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3895 std::pair<FileID, unsigned> BeginLocInfo
3896 = SourceMgr.getDecomposedLoc(R.getBegin());
3897 std::pair<FileID, unsigned> EndLocInfo
3898 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003899
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003900 // Cannot tokenize across files.
3901 if (BeginLocInfo.first != EndLocInfo.first)
3902 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003903
3904 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003905 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003906 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003907 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003908 if (Invalid)
3909 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003910
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003911 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3912 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003913 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003914 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003915
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003916 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003917 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003918 llvm::SmallVector<CXToken, 32> CXTokens;
3919 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003920 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003921 do {
3922 // Lex the next token
3923 Lex.LexFromRawLexer(Tok);
3924 if (Tok.is(tok::eof))
3925 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003926
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003927 // Initialize the CXToken.
3928 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003929
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003930 // - Common fields
3931 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3932 CXTok.int_data[2] = Tok.getLength();
3933 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003934
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003935 // - Kind-specific fields
3936 if (Tok.isLiteral()) {
3937 CXTok.int_data[0] = CXToken_Literal;
3938 CXTok.ptr_data = (void *)Tok.getLiteralData();
3939 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003940 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003941 std::pair<FileID, unsigned> LocInfo
3942 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003943 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003944 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003945 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3946 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003947 return;
3948
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003949 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003950 IdentifierInfo *II
3951 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003952
David Chisnall096428b2010-10-13 21:44:48 +00003953 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003954 CXTok.int_data[0] = CXToken_Keyword;
3955 }
3956 else {
3957 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3958 CXToken_Identifier
3959 : CXToken_Keyword;
3960 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003961 CXTok.ptr_data = II;
3962 } else if (Tok.is(tok::comment)) {
3963 CXTok.int_data[0] = CXToken_Comment;
3964 CXTok.ptr_data = 0;
3965 } else {
3966 CXTok.int_data[0] = CXToken_Punctuation;
3967 CXTok.ptr_data = 0;
3968 }
3969 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003970 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003971 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003972
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003973 if (CXTokens.empty())
3974 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003975
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003976 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3977 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3978 *NumTokens = CXTokens.size();
3979}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003980
Ted Kremenek6db61092010-05-05 00:55:15 +00003981void clang_disposeTokens(CXTranslationUnit TU,
3982 CXToken *Tokens, unsigned NumTokens) {
3983 free(Tokens);
3984}
3985
3986} // end: extern "C"
3987
3988//===----------------------------------------------------------------------===//
3989// Token annotation APIs.
3990//===----------------------------------------------------------------------===//
3991
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003992typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003993static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3994 CXCursor parent,
3995 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003996namespace {
3997class AnnotateTokensWorker {
3998 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003999 CXToken *Tokens;
4000 CXCursor *Cursors;
4001 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004002 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004003 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004 CursorVisitor AnnotateVis;
4005 SourceManager &SrcMgr;
4006
4007 bool MoreTokens() const { return TokIdx < NumTokens; }
4008 unsigned NextToken() const { return TokIdx; }
4009 void AdvanceToken() { ++TokIdx; }
4010 SourceLocation GetTokenLoc(unsigned tokI) {
4011 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4012 }
4013
Ted Kremenek6db61092010-05-05 00:55:15 +00004014public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004015 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004016 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004017 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004018 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004019 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004020 AnnotateVis(tu,
4021 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004022 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004023 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004024
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004025 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004026 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004027 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004028 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004029 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004030 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004031};
4032}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004033
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004034void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4035 // Walk the AST within the region of interest, annotating tokens
4036 // along the way.
4037 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004038
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004039 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4040 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004041 if (Pos != Annotated.end() &&
4042 (clang_isInvalid(Cursors[I].kind) ||
4043 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004044 Cursors[I] = Pos->second;
4045 }
4046
4047 // Finish up annotating any tokens left.
4048 if (!MoreTokens())
4049 return;
4050
4051 const CXCursor &C = clang_getNullCursor();
4052 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4053 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4054 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004055 }
4056}
4057
Ted Kremenek6db61092010-05-05 00:55:15 +00004058enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004059AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004060 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004061 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004062 if (cursorRange.isInvalid())
4063 return CXChildVisit_Recurse;
4064
Douglas Gregor4419b672010-10-21 06:10:04 +00004065 if (clang_isPreprocessing(cursor.kind)) {
4066 // For macro instantiations, just note where the beginning of the macro
4067 // instantiation occurs.
4068 if (cursor.kind == CXCursor_MacroInstantiation) {
4069 Annotated[Loc.int_data] = cursor;
4070 return CXChildVisit_Recurse;
4071 }
4072
Douglas Gregor4419b672010-10-21 06:10:04 +00004073 // Items in the preprocessing record are kept separate from items in
4074 // declarations, so we keep a separate token index.
4075 unsigned SavedTokIdx = TokIdx;
4076 TokIdx = PreprocessingTokIdx;
4077
4078 // Skip tokens up until we catch up to the beginning of the preprocessing
4079 // entry.
4080 while (MoreTokens()) {
4081 const unsigned I = NextToken();
4082 SourceLocation TokLoc = GetTokenLoc(I);
4083 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4084 case RangeBefore:
4085 AdvanceToken();
4086 continue;
4087 case RangeAfter:
4088 case RangeOverlap:
4089 break;
4090 }
4091 break;
4092 }
4093
4094 // Look at all of the tokens within this range.
4095 while (MoreTokens()) {
4096 const unsigned I = NextToken();
4097 SourceLocation TokLoc = GetTokenLoc(I);
4098 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4099 case RangeBefore:
4100 assert(0 && "Infeasible");
4101 case RangeAfter:
4102 break;
4103 case RangeOverlap:
4104 Cursors[I] = cursor;
4105 AdvanceToken();
4106 continue;
4107 }
4108 break;
4109 }
4110
4111 // Save the preprocessing token index; restore the non-preprocessing
4112 // token index.
4113 PreprocessingTokIdx = TokIdx;
4114 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004115 return CXChildVisit_Recurse;
4116 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004117
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004118 if (cursorRange.isInvalid())
4119 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004120
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004121 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4122
Ted Kremeneka333c662010-05-12 05:29:33 +00004123 // Adjust the annotated range based specific declarations.
4124 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4125 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004126 Decl *D = cxcursor::getCursorDecl(cursor);
4127 // Don't visit synthesized ObjC methods, since they have no syntatic
4128 // representation in the source.
4129 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4130 if (MD->isSynthesized())
4131 return CXChildVisit_Continue;
4132 }
4133 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004134 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4135 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004136 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004137 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004138 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004139 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004140 }
4141 }
4142 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004143
Ted Kremenek3f404602010-08-14 01:14:06 +00004144 // If the location of the cursor occurs within a macro instantiation, record
4145 // the spelling location of the cursor in our annotation map. We can then
4146 // paper over the token labelings during a post-processing step to try and
4147 // get cursor mappings for tokens that are the *arguments* of a macro
4148 // instantiation.
4149 if (L.isMacroID()) {
4150 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4151 // Only invalidate the old annotation if it isn't part of a preprocessing
4152 // directive. Here we assume that the default construction of CXCursor
4153 // results in CXCursor.kind being an initialized value (i.e., 0). If
4154 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004155
Ted Kremenek3f404602010-08-14 01:14:06 +00004156 CXCursor &oldC = Annotated[rawEncoding];
4157 if (!clang_isPreprocessing(oldC.kind))
4158 oldC = cursor;
4159 }
4160
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004161 const enum CXCursorKind K = clang_getCursorKind(parent);
4162 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004163 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4164 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004165
4166 while (MoreTokens()) {
4167 const unsigned I = NextToken();
4168 SourceLocation TokLoc = GetTokenLoc(I);
4169 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4170 case RangeBefore:
4171 Cursors[I] = updateC;
4172 AdvanceToken();
4173 continue;
4174 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004175 case RangeOverlap:
4176 break;
4177 }
4178 break;
4179 }
4180
4181 // Visit children to get their cursor information.
4182 const unsigned BeforeChildren = NextToken();
4183 VisitChildren(cursor);
4184 const unsigned AfterChildren = NextToken();
4185
4186 // Adjust 'Last' to the last token within the extent of the cursor.
4187 while (MoreTokens()) {
4188 const unsigned I = NextToken();
4189 SourceLocation TokLoc = GetTokenLoc(I);
4190 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4191 case RangeBefore:
4192 assert(0 && "Infeasible");
4193 case RangeAfter:
4194 break;
4195 case RangeOverlap:
4196 Cursors[I] = updateC;
4197 AdvanceToken();
4198 continue;
4199 }
4200 break;
4201 }
4202 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004203
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004204 // Scan the tokens that are at the beginning of the cursor, but are not
4205 // capture by the child cursors.
4206
4207 // For AST elements within macros, rely on a post-annotate pass to
4208 // to correctly annotate the tokens with cursors. Otherwise we can
4209 // get confusing results of having tokens that map to cursors that really
4210 // are expanded by an instantiation.
4211 if (L.isMacroID())
4212 cursor = clang_getNullCursor();
4213
4214 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4215 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4216 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004217
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004218 Cursors[I] = cursor;
4219 }
4220 // Scan the tokens that are at the end of the cursor, but are not captured
4221 // but the child cursors.
4222 for (unsigned I = AfterChildren; I != Last; ++I)
4223 Cursors[I] = cursor;
4224
4225 TokIdx = Last;
4226 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004227}
4228
Ted Kremenek6db61092010-05-05 00:55:15 +00004229static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4230 CXCursor parent,
4231 CXClientData client_data) {
4232 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4233}
4234
Ted Kremenekab979612010-11-11 08:05:23 +00004235// This gets run a separate thread to avoid stack blowout.
4236static void runAnnotateTokensWorker(void *UserData) {
4237 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4238}
4239
Ted Kremenek6db61092010-05-05 00:55:15 +00004240extern "C" {
4241
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004242void clang_annotateTokens(CXTranslationUnit TU,
4243 CXToken *Tokens, unsigned NumTokens,
4244 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004245
4246 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004247 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004248
Douglas Gregor4419b672010-10-21 06:10:04 +00004249 // Any token we don't specifically annotate will have a NULL cursor.
4250 CXCursor C = clang_getNullCursor();
4251 for (unsigned I = 0; I != NumTokens; ++I)
4252 Cursors[I] = C;
4253
Ted Kremeneka60ed472010-11-16 08:15:36 +00004254 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004255 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004256 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004257
Douglas Gregorbdf60622010-03-05 21:16:25 +00004258 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004259
Douglas Gregor0396f462010-03-19 05:22:59 +00004260 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004261 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004262 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4263 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004264 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4265 clang_getTokenLocation(TU,
4266 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004267
Douglas Gregor0396f462010-03-19 05:22:59 +00004268 // A mapping from the source locations found when re-lexing or traversing the
4269 // region of interest to the corresponding cursors.
4270 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004271
4272 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004273 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004274 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4275 std::pair<FileID, unsigned> BeginLocInfo
4276 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4277 std::pair<FileID, unsigned> EndLocInfo
4278 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004280 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004281 bool Invalid = false;
4282 if (BeginLocInfo.first == EndLocInfo.first &&
4283 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4284 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004285 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4286 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004287 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004288 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004289 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004290
4291 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004292 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004293 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004294 Token Tok;
4295 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004296
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004297 reprocess:
4298 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4299 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004300 // don't see it while preprocessing these tokens later, but keep track
4301 // of all of the token locations inside this preprocessing directive so
4302 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004303 //
4304 // FIXME: Some simple tests here could identify macro definitions and
4305 // #undefs, to provide specific cursor kinds for those.
4306 std::vector<SourceLocation> Locations;
4307 do {
4308 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004309 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004310 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004311
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004312 using namespace cxcursor;
4313 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004314 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4315 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004316 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004317 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4318 Annotated[Locations[I].getRawEncoding()] = Cursor;
4319 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004320
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004321 if (Tok.isAtStartOfLine())
4322 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004323
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004324 continue;
4325 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004326
Douglas Gregor48072312010-03-18 15:23:44 +00004327 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004328 break;
4329 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004330 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004331
Douglas Gregor0396f462010-03-19 05:22:59 +00004332 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004333 // a specific cursor.
4334 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004335 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004336
4337 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004338 // FIXME: We use a ridiculous stack size here because the data-recursion
4339 // algorithm uses a large stack frame than the non-data recursive version,
4340 // and AnnotationTokensWorker currently transforms the data-recursion
4341 // algorithm back into a traditional recursion by explicitly calling
4342 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004343 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004344 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4345 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004346 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4347 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004348}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004349} // end: extern "C"
4350
4351//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004352// Operations for querying linkage of a cursor.
4353//===----------------------------------------------------------------------===//
4354
4355extern "C" {
4356CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004357 if (!clang_isDeclaration(cursor.kind))
4358 return CXLinkage_Invalid;
4359
Ted Kremenek16b42592010-03-03 06:36:57 +00004360 Decl *D = cxcursor::getCursorDecl(cursor);
4361 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4362 switch (ND->getLinkage()) {
4363 case NoLinkage: return CXLinkage_NoLinkage;
4364 case InternalLinkage: return CXLinkage_Internal;
4365 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4366 case ExternalLinkage: return CXLinkage_External;
4367 };
4368
4369 return CXLinkage_Invalid;
4370}
4371} // end: extern "C"
4372
4373//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004374// Operations for querying language of a cursor.
4375//===----------------------------------------------------------------------===//
4376
4377static CXLanguageKind getDeclLanguage(const Decl *D) {
4378 switch (D->getKind()) {
4379 default:
4380 break;
4381 case Decl::ImplicitParam:
4382 case Decl::ObjCAtDefsField:
4383 case Decl::ObjCCategory:
4384 case Decl::ObjCCategoryImpl:
4385 case Decl::ObjCClass:
4386 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004387 case Decl::ObjCForwardProtocol:
4388 case Decl::ObjCImplementation:
4389 case Decl::ObjCInterface:
4390 case Decl::ObjCIvar:
4391 case Decl::ObjCMethod:
4392 case Decl::ObjCProperty:
4393 case Decl::ObjCPropertyImpl:
4394 case Decl::ObjCProtocol:
4395 return CXLanguage_ObjC;
4396 case Decl::CXXConstructor:
4397 case Decl::CXXConversion:
4398 case Decl::CXXDestructor:
4399 case Decl::CXXMethod:
4400 case Decl::CXXRecord:
4401 case Decl::ClassTemplate:
4402 case Decl::ClassTemplatePartialSpecialization:
4403 case Decl::ClassTemplateSpecialization:
4404 case Decl::Friend:
4405 case Decl::FriendTemplate:
4406 case Decl::FunctionTemplate:
4407 case Decl::LinkageSpec:
4408 case Decl::Namespace:
4409 case Decl::NamespaceAlias:
4410 case Decl::NonTypeTemplateParm:
4411 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004412 case Decl::TemplateTemplateParm:
4413 case Decl::TemplateTypeParm:
4414 case Decl::UnresolvedUsingTypename:
4415 case Decl::UnresolvedUsingValue:
4416 case Decl::Using:
4417 case Decl::UsingDirective:
4418 case Decl::UsingShadow:
4419 return CXLanguage_CPlusPlus;
4420 }
4421
4422 return CXLanguage_C;
4423}
4424
4425extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004426
4427enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4428 if (clang_isDeclaration(cursor.kind))
4429 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4430 if (D->hasAttr<UnavailableAttr>() ||
4431 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4432 return CXAvailability_Available;
4433
4434 if (D->hasAttr<DeprecatedAttr>())
4435 return CXAvailability_Deprecated;
4436 }
4437
4438 return CXAvailability_Available;
4439}
4440
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004441CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4442 if (clang_isDeclaration(cursor.kind))
4443 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4444
4445 return CXLanguage_Invalid;
4446}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004447
4448CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4449 if (clang_isDeclaration(cursor.kind)) {
4450 if (Decl *D = getCursorDecl(cursor)) {
4451 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004452 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004453 }
4454 }
4455
4456 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4457 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004458 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004459 }
4460
4461 return clang_getNullCursor();
4462}
4463
4464CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4465 if (clang_isDeclaration(cursor.kind)) {
4466 if (Decl *D = getCursorDecl(cursor)) {
4467 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004468 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004469 }
4470 }
4471
4472 // FIXME: Note that we can't easily compute the lexical context of a
4473 // statement or expression, so we return nothing.
4474 return clang_getNullCursor();
4475}
4476
Douglas Gregor9f592342010-10-01 20:25:15 +00004477static void CollectOverriddenMethods(DeclContext *Ctx,
4478 ObjCMethodDecl *Method,
4479 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4480 if (!Ctx)
4481 return;
4482
4483 // If we have a class or category implementation, jump straight to the
4484 // interface.
4485 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4486 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4487
4488 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4489 if (!Container)
4490 return;
4491
4492 // Check whether we have a matching method at this level.
4493 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4494 Method->isInstanceMethod()))
4495 if (Method != Overridden) {
4496 // We found an override at this level; there is no need to look
4497 // into other protocols or categories.
4498 Methods.push_back(Overridden);
4499 return;
4500 }
4501
4502 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4503 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4504 PEnd = Protocol->protocol_end();
4505 P != PEnd; ++P)
4506 CollectOverriddenMethods(*P, Method, Methods);
4507 }
4508
4509 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4510 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4511 PEnd = Category->protocol_end();
4512 P != PEnd; ++P)
4513 CollectOverriddenMethods(*P, Method, Methods);
4514 }
4515
4516 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4517 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4518 PEnd = Interface->protocol_end();
4519 P != PEnd; ++P)
4520 CollectOverriddenMethods(*P, Method, Methods);
4521
4522 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4523 Category; Category = Category->getNextClassCategory())
4524 CollectOverriddenMethods(Category, Method, Methods);
4525
4526 // We only look into the superclass if we haven't found anything yet.
4527 if (Methods.empty())
4528 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4529 return CollectOverriddenMethods(Super, Method, Methods);
4530 }
4531}
4532
4533void clang_getOverriddenCursors(CXCursor cursor,
4534 CXCursor **overridden,
4535 unsigned *num_overridden) {
4536 if (overridden)
4537 *overridden = 0;
4538 if (num_overridden)
4539 *num_overridden = 0;
4540 if (!overridden || !num_overridden)
4541 return;
4542
4543 if (!clang_isDeclaration(cursor.kind))
4544 return;
4545
4546 Decl *D = getCursorDecl(cursor);
4547 if (!D)
4548 return;
4549
4550 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004551 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004552 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4553 *num_overridden = CXXMethod->size_overridden_methods();
4554 if (!*num_overridden)
4555 return;
4556
4557 *overridden = new CXCursor [*num_overridden];
4558 unsigned I = 0;
4559 for (CXXMethodDecl::method_iterator
4560 M = CXXMethod->begin_overridden_methods(),
4561 MEnd = CXXMethod->end_overridden_methods();
4562 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004563 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004564 return;
4565 }
4566
4567 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4568 if (!Method)
4569 return;
4570
4571 // Handle Objective-C methods.
4572 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4573 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4574
4575 if (Methods.empty())
4576 return;
4577
4578 *num_overridden = Methods.size();
4579 *overridden = new CXCursor [Methods.size()];
4580 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004581 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004582}
4583
4584void clang_disposeOverriddenCursors(CXCursor *overridden) {
4585 delete [] overridden;
4586}
4587
Douglas Gregorecdcb882010-10-20 22:00:55 +00004588CXFile clang_getIncludedFile(CXCursor cursor) {
4589 if (cursor.kind != CXCursor_InclusionDirective)
4590 return 0;
4591
4592 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4593 return (void *)ID->getFile();
4594}
4595
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004596} // end: extern "C"
4597
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004598
4599//===----------------------------------------------------------------------===//
4600// C++ AST instrospection.
4601//===----------------------------------------------------------------------===//
4602
4603extern "C" {
4604unsigned clang_CXXMethod_isStatic(CXCursor C) {
4605 if (!clang_isDeclaration(C.kind))
4606 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004607
4608 CXXMethodDecl *Method = 0;
4609 Decl *D = cxcursor::getCursorDecl(C);
4610 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4611 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4612 else
4613 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4614 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004615}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004616
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004617} // end: extern "C"
4618
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004619//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004620// Attribute introspection.
4621//===----------------------------------------------------------------------===//
4622
4623extern "C" {
4624CXType clang_getIBOutletCollectionType(CXCursor C) {
4625 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004626 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004627
4628 IBOutletCollectionAttr *A =
4629 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4630
Ted Kremeneka60ed472010-11-16 08:15:36 +00004631 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004632}
4633} // end: extern "C"
4634
4635//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004636// Misc. utility functions.
4637//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004638
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004639/// Default to using an 8 MB stack size on "safety" threads.
4640static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004641
4642namespace clang {
4643
4644bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004645 void (*Fn)(void*), void *UserData,
4646 unsigned Size) {
4647 if (!Size)
4648 Size = GetSafetyThreadStackSize();
4649 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004650 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4651 return CRC.RunSafely(Fn, UserData);
4652}
4653
4654unsigned GetSafetyThreadStackSize() {
4655 return SafetyStackThreadSize;
4656}
4657
4658void SetSafetyThreadStackSize(unsigned Value) {
4659 SafetyStackThreadSize = Value;
4660}
4661
4662}
4663
Ted Kremenek04bb7162010-01-22 22:44:15 +00004664extern "C" {
4665
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004666CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004667 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004668}
4669
4670} // end: extern "C"