blob: 585c9c8d7a307e6848392e0c50a937645e46decd [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);
357
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000358RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000359 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360}
361
Douglas Gregorb1373d02010-01-20 20:59:29 +0000362/// \brief Visit the given cursor and, if requested by the visitor,
363/// its children.
364///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365/// \param Cursor the cursor to visit.
366///
367/// \param CheckRegionOfInterest if true, then the caller already checked that
368/// this cursor is within the region of interest.
369///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370/// \returns true if the visitation should be aborted, false if it
371/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373 if (clang_isInvalid(Cursor.kind))
374 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000375
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 if (clang_isDeclaration(Cursor.kind)) {
377 Decl *D = getCursorDecl(Cursor);
378 assert(D && "Invalid declaration cursor");
379 if (D->getPCHLevel() > MaxPCHLevel)
380 return false;
381
382 if (D->isImplicit())
383 return false;
384 }
385
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000386 // If we have a range of interest, and this cursor doesn't intersect with it,
387 // we're done.
388 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000389 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000390 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391 return false;
392 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000393
Douglas Gregorb1373d02010-01-20 20:59:29 +0000394 switch (Visitor(Cursor, Parent, ClientData)) {
395 case CXChildVisit_Break:
396 return true;
397
398 case CXChildVisit_Continue:
399 return false;
400
401 case CXChildVisit_Recurse:
402 return VisitChildren(Cursor);
403 }
404
Douglas Gregorfd643772010-01-25 16:45:46 +0000405 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406}
407
Douglas Gregor788f5a12010-03-20 00:41:21 +0000408std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
409CursorVisitor::getPreprocessedEntities() {
410 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000411 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000412
413 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000414 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000415
416 // There is no region of interest; we have to walk everything.
417 if (RegionOfInterest.isInvalid())
418 return std::make_pair(PPRec.begin(OnlyLocalDecls),
419 PPRec.end(OnlyLocalDecls));
420
421 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000422 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000423 std::pair<FileID, unsigned> Begin
424 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
425 std::pair<FileID, unsigned> End
426 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
427
428 // The region of interest spans files; we have to walk everything.
429 if (Begin.first != End.first)
430 return std::make_pair(PPRec.begin(OnlyLocalDecls),
431 PPRec.end(OnlyLocalDecls));
432
433 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000434 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000435 if (ByFileMap.empty()) {
436 // Build the mapping from files to sets of preprocessed entities.
437 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
438 EEnd = PPRec.end(OnlyLocalDecls);
439 E != EEnd; ++E) {
440 std::pair<FileID, unsigned> P
441 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
442 ByFileMap[P.first].push_back(*E);
443 }
444 }
445
446 return std::make_pair(ByFileMap[Begin.first].begin(),
447 ByFileMap[Begin.first].end());
448}
449
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000451///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452/// \returns true if the visitation should be aborted, false if it
453/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000454bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000455 if (clang_isReference(Cursor.kind)) {
456 // By definition, references have no children.
457 return false;
458 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000459
460 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000461 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000462 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463
Douglas Gregorb1373d02010-01-20 20:59:29 +0000464 if (clang_isDeclaration(Cursor.kind)) {
465 Decl *D = getCursorDecl(Cursor);
466 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000467 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000469
Douglas Gregora59e3902010-01-21 23:27:09 +0000470 if (clang_isStatement(Cursor.kind))
471 return Visit(getCursorStmt(Cursor));
472 if (clang_isExpression(Cursor.kind))
473 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000474
Douglas Gregorb1373d02010-01-20 20:59:29 +0000475 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000476 CXTranslationUnit tu = getCursorTU(Cursor);
477 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000478 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
479 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000480 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
481 TLEnd = CXXUnit->top_level_end();
482 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000483 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000484 return true;
485 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000486 } else if (VisitDeclContext(
487 CXXUnit->getASTContext().getTranslationUnitDecl()))
488 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000489
Douglas Gregor0396f462010-03-19 05:22:59 +0000490 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000491 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 // FIXME: Once we have the ability to deserialize a preprocessing record,
493 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000494 PreprocessingRecord::iterator E, EEnd;
495 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000497 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000499
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 continue;
501 }
502
503 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000504 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000505 return true;
506
507 continue;
508 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000509
510 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000511 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000512 return true;
513
514 continue;
515 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000516 }
517 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000518 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000519 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000520
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522 return false;
523}
524
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000525bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000526 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
527 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528
Ted Kremenek664cffd2010-07-22 11:30:19 +0000529 if (Stmt *Body = B->getBody())
530 return Visit(MakeCXCursor(Body, StmtParent, TU));
531
532 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533}
534
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000535llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
536 if (RegionOfInterest.isValid()) {
537 SourceRange Range = getRawCursorExtent(Cursor);
538 if (Range.isInvalid())
539 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000540
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000541 switch (CompareRegionOfInterest(Range)) {
542 case RangeBefore:
543 // This declaration comes before the region of interest; skip it.
544 return llvm::Optional<bool>();
545
546 case RangeAfter:
547 // This declaration comes after the region of interest; we're done.
548 return false;
549
550 case RangeOverlap:
551 // This declaration overlaps the region of interest; visit it.
552 break;
553 }
554 }
555 return true;
556}
557
558bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
559 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
560
561 // FIXME: Eventually remove. This part of a hack to support proper
562 // iteration over all Decls contained lexically within an ObjC container.
563 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
564 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
565
566 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000567 Decl *D = *I;
568 if (D->getLexicalDeclContext() != DC)
569 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000570 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000571 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
572 if (!V.hasValue())
573 continue;
574 if (!V.getValue())
575 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000576 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000577 return true;
578 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000579 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000580}
581
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000582bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
583 llvm_unreachable("Translation units are visited directly by Visit()");
584 return false;
585}
586
587bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
588 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
589 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000590
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000591 return false;
592}
593
594bool CursorVisitor::VisitTagDecl(TagDecl *D) {
595 return VisitDeclContext(D);
596}
597
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000598bool CursorVisitor::VisitClassTemplateSpecializationDecl(
599 ClassTemplateSpecializationDecl *D) {
600 bool ShouldVisitBody = false;
601 switch (D->getSpecializationKind()) {
602 case TSK_Undeclared:
603 case TSK_ImplicitInstantiation:
604 // Nothing to visit
605 return false;
606
607 case TSK_ExplicitInstantiationDeclaration:
608 case TSK_ExplicitInstantiationDefinition:
609 break;
610
611 case TSK_ExplicitSpecialization:
612 ShouldVisitBody = true;
613 break;
614 }
615
616 // Visit the template arguments used in the specialization.
617 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
618 TypeLoc TL = SpecType->getTypeLoc();
619 if (TemplateSpecializationTypeLoc *TSTLoc
620 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
621 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
622 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
623 return true;
624 }
625 }
626
627 if (ShouldVisitBody && VisitCXXRecordDecl(D))
628 return true;
629
630 return false;
631}
632
Douglas Gregor74dbe642010-08-31 19:31:58 +0000633bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
634 ClassTemplatePartialSpecializationDecl *D) {
635 // FIXME: Visit the "outer" template parameter lists on the TagDecl
636 // before visiting these template parameters.
637 if (VisitTemplateParameters(D->getTemplateParameters()))
638 return true;
639
640 // Visit the partial specialization arguments.
641 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
642 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
643 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
644 return true;
645
646 return VisitCXXRecordDecl(D);
647}
648
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000649bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000650 // Visit the default argument.
651 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
652 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
653 if (Visit(DefArg->getTypeLoc()))
654 return true;
655
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000656 return false;
657}
658
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000659bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
660 if (Expr *Init = D->getInitExpr())
661 return Visit(MakeCXCursor(Init, StmtParent, TU));
662 return false;
663}
664
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000665bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
666 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
667 if (Visit(TSInfo->getTypeLoc()))
668 return true;
669
670 return false;
671}
672
Douglas Gregora67e03f2010-09-09 21:42:20 +0000673/// \brief Compare two base or member initializers based on their source order.
674static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
675 CXXBaseOrMemberInitializer const * const *X
676 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
677 CXXBaseOrMemberInitializer const * const *Y
678 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
679
680 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
681 return -1;
682 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
683 return 1;
684 else
685 return 0;
686}
687
Douglas Gregorb1373d02010-01-20 20:59:29 +0000688bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000689 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
690 // Visit the function declaration's syntactic components in the order
691 // written. This requires a bit of work.
692 TypeLoc TL = TSInfo->getTypeLoc();
693 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
694
695 // If we have a function declared directly (without the use of a typedef),
696 // visit just the return type. Otherwise, just visit the function's type
697 // now.
698 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
699 (!FTL && Visit(TL)))
700 return true;
701
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000702 // Visit the nested-name-specifier, if present.
703 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
704 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
705 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000706
707 // Visit the declaration name.
708 if (VisitDeclarationNameInfo(ND->getNameInfo()))
709 return true;
710
711 // FIXME: Visit explicitly-specified template arguments!
712
713 // Visit the function parameters, if we have a function type.
714 if (FTL && VisitFunctionTypeLoc(*FTL, true))
715 return true;
716
717 // FIXME: Attributes?
718 }
719
Douglas Gregora67e03f2010-09-09 21:42:20 +0000720 if (ND->isThisDeclarationADefinition()) {
721 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
722 // Find the initializers that were written in the source.
723 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
724 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
725 IEnd = Constructor->init_end();
726 I != IEnd; ++I) {
727 if (!(*I)->isWritten())
728 continue;
729
730 WrittenInits.push_back(*I);
731 }
732
733 // Sort the initializers in source order
734 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
735 &CompareCXXBaseOrMemberInitializers);
736
737 // Visit the initializers in source order
738 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
739 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
740 if (Init->isMemberInitializer()) {
741 if (Visit(MakeCursorMemberRef(Init->getMember(),
742 Init->getMemberLocation(), TU)))
743 return true;
744 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
745 if (Visit(BaseInfo->getTypeLoc()))
746 return true;
747 }
748
749 // Visit the initializer value.
750 if (Expr *Initializer = Init->getInit())
751 if (Visit(MakeCXCursor(Initializer, ND, TU)))
752 return true;
753 }
754 }
755
756 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
757 return true;
758 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000759
Douglas Gregorb1373d02010-01-20 20:59:29 +0000760 return false;
761}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000762
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000763bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
764 if (VisitDeclaratorDecl(D))
765 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000766
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000767 if (Expr *BitWidth = D->getBitWidth())
768 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770 return false;
771}
772
773bool CursorVisitor::VisitVarDecl(VarDecl *D) {
774 if (VisitDeclaratorDecl(D))
775 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000777 if (Expr *Init = D->getInit())
778 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780 return false;
781}
782
Douglas Gregor84b51d72010-09-01 20:16:53 +0000783bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
784 if (VisitDeclaratorDecl(D))
785 return true;
786
787 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
788 if (Expr *DefArg = D->getDefaultArgument())
789 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
790
791 return false;
792}
793
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000794bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
795 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
796 // before visiting these template parameters.
797 if (VisitTemplateParameters(D->getTemplateParameters()))
798 return true;
799
800 return VisitFunctionDecl(D->getTemplatedDecl());
801}
802
Douglas Gregor39d6f072010-08-31 19:02:00 +0000803bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
804 // FIXME: Visit the "outer" template parameter lists on the TagDecl
805 // before visiting these template parameters.
806 if (VisitTemplateParameters(D->getTemplateParameters()))
807 return true;
808
809 return VisitCXXRecordDecl(D->getTemplatedDecl());
810}
811
Douglas Gregor84b51d72010-09-01 20:16:53 +0000812bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
813 if (VisitTemplateParameters(D->getTemplateParameters()))
814 return true;
815
816 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
817 VisitTemplateArgumentLoc(D->getDefaultArgument()))
818 return true;
819
820 return false;
821}
822
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000823bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000824 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
825 if (Visit(TSInfo->getTypeLoc()))
826 return true;
827
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000828 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000829 PEnd = ND->param_end();
830 P != PEnd; ++P) {
831 if (Visit(MakeCXCursor(*P, TU)))
832 return true;
833 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000834
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000835 if (ND->isThisDeclarationADefinition() &&
836 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
837 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839 return false;
840}
841
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000842namespace {
843 struct ContainerDeclsSort {
844 SourceManager &SM;
845 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
846 bool operator()(Decl *A, Decl *B) {
847 SourceLocation L_A = A->getLocStart();
848 SourceLocation L_B = B->getLocStart();
849 assert(L_A.isValid() && L_B.isValid());
850 return SM.isBeforeInTranslationUnit(L_A, L_B);
851 }
852 };
853}
854
Douglas Gregora59e3902010-01-21 23:27:09 +0000855bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000856 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
857 // an @implementation can lexically contain Decls that are not properly
858 // nested in the AST. When we identify such cases, we need to retrofit
859 // this nesting here.
860 if (!DI_current)
861 return VisitDeclContext(D);
862
863 // Scan the Decls that immediately come after the container
864 // in the current DeclContext. If any fall within the
865 // container's lexical region, stash them into a vector
866 // for later processing.
867 llvm::SmallVector<Decl *, 24> DeclsInContainer;
868 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000869 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000870 if (EndLoc.isValid()) {
871 DeclContext::decl_iterator next = *DI_current;
872 while (++next != DE_current) {
873 Decl *D_next = *next;
874 if (!D_next)
875 break;
876 SourceLocation L = D_next->getLocStart();
877 if (!L.isValid())
878 break;
879 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
880 *DI_current = next;
881 DeclsInContainer.push_back(D_next);
882 continue;
883 }
884 break;
885 }
886 }
887
888 // The common case.
889 if (DeclsInContainer.empty())
890 return VisitDeclContext(D);
891
892 // Get all the Decls in the DeclContext, and sort them with the
893 // additional ones we've collected. Then visit them.
894 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
895 I!=E; ++I) {
896 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000897 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
898 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000899 continue;
900 DeclsInContainer.push_back(subDecl);
901 }
902
903 // Now sort the Decls so that they appear in lexical order.
904 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
905 ContainerDeclsSort(SM));
906
907 // Now visit the decls.
908 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
909 E = DeclsInContainer.end(); I != E; ++I) {
910 CXCursor Cursor = MakeCXCursor(*I, TU);
911 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
912 if (!V.hasValue())
913 continue;
914 if (!V.getValue())
915 return false;
916 if (Visit(Cursor, true))
917 return true;
918 }
919 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000920}
921
Douglas Gregorb1373d02010-01-20 20:59:29 +0000922bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000923 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
924 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000925 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000926
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000927 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
928 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
929 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000930 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000931 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000932
Douglas Gregora59e3902010-01-21 23:27:09 +0000933 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000934}
935
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000936bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
937 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
938 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
939 E = PID->protocol_end(); I != E; ++I, ++PL)
940 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000943 return VisitObjCContainerDecl(PID);
944}
945
Ted Kremenek23173d72010-05-18 21:09:07 +0000946bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000947 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000948 return true;
949
Ted Kremenek23173d72010-05-18 21:09:07 +0000950 // FIXME: This implements a workaround with @property declarations also being
951 // installed in the DeclContext for the @interface. Eventually this code
952 // should be removed.
953 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
954 if (!CDecl || !CDecl->IsClassExtension())
955 return false;
956
957 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
958 if (!ID)
959 return false;
960
961 IdentifierInfo *PropertyId = PD->getIdentifier();
962 ObjCPropertyDecl *prevDecl =
963 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
964
965 if (!prevDecl)
966 return false;
967
968 // Visit synthesized methods since they will be skipped when visiting
969 // the @interface.
970 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000971 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000972 if (Visit(MakeCXCursor(MD, TU)))
973 return true;
974
975 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000976 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000977 if (Visit(MakeCXCursor(MD, TU)))
978 return true;
979
980 return false;
981}
982
Douglas Gregorb1373d02010-01-20 20:59:29 +0000983bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000984 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000985 if (D->getSuperClass() &&
986 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000987 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000988 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000989 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000991 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
992 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
993 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000994 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000995 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000996
Douglas Gregora59e3902010-01-21 23:27:09 +0000997 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000998}
999
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001000bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1001 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001002}
1003
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001004bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001005 // 'ID' could be null when dealing with invalid code.
1006 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1007 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1008 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001009
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001010 return VisitObjCImplDecl(D);
1011}
1012
1013bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1014#if 0
1015 // Issue callbacks for super class.
1016 // FIXME: No source location information!
1017 if (D->getSuperClass() &&
1018 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001019 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001020 TU)))
1021 return true;
1022#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001023
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001024 return VisitObjCImplDecl(D);
1025}
1026
1027bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1028 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1029 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1030 E = D->protocol_end();
1031 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001032 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
1035 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001036}
1037
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001038bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1039 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1040 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1041 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001044}
1045
Douglas Gregora4ffd852010-11-17 01:03:52 +00001046bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1047 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1048 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1049
1050 return false;
1051}
1052
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001053bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1054 return VisitDeclContext(D);
1055}
1056
Douglas Gregor69319002010-08-31 23:48:11 +00001057bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001058 // Visit nested-name-specifier.
1059 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1060 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1061 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001062
1063 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1064 D->getTargetNameLoc(), TU));
1065}
1066
Douglas Gregor7e242562010-09-01 19:52:22 +00001067bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001068 // Visit nested-name-specifier.
1069 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1070 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1071 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001072
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001073 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1074 return true;
1075
Douglas Gregor7e242562010-09-01 19:52:22 +00001076 return VisitDeclarationNameInfo(D->getNameInfo());
1077}
1078
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001079bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080 // Visit nested-name-specifier.
1081 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1082 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1083 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001084
1085 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1086 D->getIdentLocation(), TU));
1087}
1088
Douglas Gregor7e242562010-09-01 19:52:22 +00001089bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 // Visit nested-name-specifier.
1091 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1092 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1093 return true;
1094
Douglas Gregor7e242562010-09-01 19:52:22 +00001095 return VisitDeclarationNameInfo(D->getNameInfo());
1096}
1097
1098bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1099 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 // Visit nested-name-specifier.
1101 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1102 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1103 return true;
1104
Douglas Gregor7e242562010-09-01 19:52:22 +00001105 return false;
1106}
1107
Douglas Gregor01829d32010-08-31 14:41:23 +00001108bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1109 switch (Name.getName().getNameKind()) {
1110 case clang::DeclarationName::Identifier:
1111 case clang::DeclarationName::CXXLiteralOperatorName:
1112 case clang::DeclarationName::CXXOperatorName:
1113 case clang::DeclarationName::CXXUsingDirective:
1114 return false;
1115
1116 case clang::DeclarationName::CXXConstructorName:
1117 case clang::DeclarationName::CXXDestructorName:
1118 case clang::DeclarationName::CXXConversionFunctionName:
1119 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1120 return Visit(TSInfo->getTypeLoc());
1121 return false;
1122
1123 case clang::DeclarationName::ObjCZeroArgSelector:
1124 case clang::DeclarationName::ObjCOneArgSelector:
1125 case clang::DeclarationName::ObjCMultiArgSelector:
1126 // FIXME: Per-identifier location info?
1127 return false;
1128 }
1129
1130 return false;
1131}
1132
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1134 SourceRange Range) {
1135 // FIXME: This whole routine is a hack to work around the lack of proper
1136 // source information in nested-name-specifiers (PR5791). Since we do have
1137 // a beginning source location, we can visit the first component of the
1138 // nested-name-specifier, if it's a single-token component.
1139 if (!NNS)
1140 return false;
1141
1142 // Get the first component in the nested-name-specifier.
1143 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1144 NNS = Prefix;
1145
1146 switch (NNS->getKind()) {
1147 case NestedNameSpecifier::Namespace:
1148 // FIXME: The token at this source location might actually have been a
1149 // namespace alias, but we don't model that. Lame!
1150 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1151 TU));
1152
1153 case NestedNameSpecifier::TypeSpec: {
1154 // If the type has a form where we know that the beginning of the source
1155 // range matches up with a reference cursor. Visit the appropriate reference
1156 // cursor.
1157 Type *T = NNS->getAsType();
1158 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1159 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1160 if (const TagType *Tag = dyn_cast<TagType>(T))
1161 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1162 if (const TemplateSpecializationType *TST
1163 = dyn_cast<TemplateSpecializationType>(T))
1164 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1165 break;
1166 }
1167
1168 case NestedNameSpecifier::TypeSpecWithTemplate:
1169 case NestedNameSpecifier::Global:
1170 case NestedNameSpecifier::Identifier:
1171 break;
1172 }
1173
1174 return false;
1175}
1176
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001177bool CursorVisitor::VisitTemplateParameters(
1178 const TemplateParameterList *Params) {
1179 if (!Params)
1180 return false;
1181
1182 for (TemplateParameterList::const_iterator P = Params->begin(),
1183 PEnd = Params->end();
1184 P != PEnd; ++P) {
1185 if (Visit(MakeCXCursor(*P, TU)))
1186 return true;
1187 }
1188
1189 return false;
1190}
1191
Douglas Gregor0b36e612010-08-31 20:37:03 +00001192bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1193 switch (Name.getKind()) {
1194 case TemplateName::Template:
1195 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1196
1197 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001198 // Visit the overloaded template set.
1199 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1200 return true;
1201
Douglas Gregor0b36e612010-08-31 20:37:03 +00001202 return false;
1203
1204 case TemplateName::DependentTemplate:
1205 // FIXME: Visit nested-name-specifier.
1206 return false;
1207
1208 case TemplateName::QualifiedTemplate:
1209 // FIXME: Visit nested-name-specifier.
1210 return Visit(MakeCursorTemplateRef(
1211 Name.getAsQualifiedTemplateName()->getDecl(),
1212 Loc, TU));
1213 }
1214
1215 return false;
1216}
1217
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001218bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1219 switch (TAL.getArgument().getKind()) {
1220 case TemplateArgument::Null:
1221 case TemplateArgument::Integral:
1222 return false;
1223
1224 case TemplateArgument::Pack:
1225 // FIXME: Implement when variadic templates come along.
1226 return false;
1227
1228 case TemplateArgument::Type:
1229 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1230 return Visit(TSInfo->getTypeLoc());
1231 return false;
1232
1233 case TemplateArgument::Declaration:
1234 if (Expr *E = TAL.getSourceDeclExpression())
1235 return Visit(MakeCXCursor(E, StmtParent, TU));
1236 return false;
1237
1238 case TemplateArgument::Expression:
1239 if (Expr *E = TAL.getSourceExpression())
1240 return Visit(MakeCXCursor(E, StmtParent, TU));
1241 return false;
1242
1243 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001244 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1245 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001246 }
1247
1248 return false;
1249}
1250
Ted Kremeneka0536d82010-05-07 01:04:29 +00001251bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1252 return VisitDeclContext(D);
1253}
1254
Douglas Gregor01829d32010-08-31 14:41:23 +00001255bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1256 return Visit(TL.getUnqualifiedLoc());
1257}
1258
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001259bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001260 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001261
1262 // Some builtin types (such as Objective-C's "id", "sel", and
1263 // "Class") have associated declarations. Create cursors for those.
1264 QualType VisitType;
1265 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001266 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001268 case BuiltinType::Char_U:
1269 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270 case BuiltinType::Char16:
1271 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001272 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273 case BuiltinType::UInt:
1274 case BuiltinType::ULong:
1275 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001276 case BuiltinType::UInt128:
1277 case BuiltinType::Char_S:
1278 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001279 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001280 case BuiltinType::Short:
1281 case BuiltinType::Int:
1282 case BuiltinType::Long:
1283 case BuiltinType::LongLong:
1284 case BuiltinType::Int128:
1285 case BuiltinType::Float:
1286 case BuiltinType::Double:
1287 case BuiltinType::LongDouble:
1288 case BuiltinType::NullPtr:
1289 case BuiltinType::Overload:
1290 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001292
1293 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001294 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001295
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001296 case BuiltinType::ObjCId:
1297 VisitType = Context.getObjCIdType();
1298 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001299
1300 case BuiltinType::ObjCClass:
1301 VisitType = Context.getObjCClassType();
1302 break;
1303
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001304 case BuiltinType::ObjCSel:
1305 VisitType = Context.getObjCSelType();
1306 break;
1307 }
1308
1309 if (!VisitType.isNull()) {
1310 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001311 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001312 TU));
1313 }
1314
1315 return false;
1316}
1317
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001318bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1319 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1320}
1321
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001322bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1323 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1324}
1325
1326bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1327 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1328}
1329
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001330bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001331 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001332 // no context information with which we can match up the depth/index in the
1333 // type to the appropriate
1334 return false;
1335}
1336
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1338 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1339 return true;
1340
John McCallc12c5bb2010-05-15 11:32:37 +00001341 return false;
1342}
1343
1344bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1345 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1346 return true;
1347
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1349 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1350 TU)))
1351 return true;
1352 }
1353
1354 return false;
1355}
1356
1357bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001358 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359}
1360
1361bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1362 return Visit(TL.getPointeeLoc());
1363}
1364
1365bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1366 return Visit(TL.getPointeeLoc());
1367}
1368
1369bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1370 return Visit(TL.getPointeeLoc());
1371}
1372
1373bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001374 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375}
1376
1377bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001378 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001379}
1380
Douglas Gregor01829d32010-08-31 14:41:23 +00001381bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1382 bool SkipResultType) {
1383 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384 return true;
1385
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001387 if (Decl *D = TL.getArg(I))
1388 if (Visit(MakeCXCursor(D, TU)))
1389 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390
1391 return false;
1392}
1393
1394bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1395 if (Visit(TL.getElementLoc()))
1396 return true;
1397
1398 if (Expr *Size = TL.getSizeExpr())
1399 return Visit(MakeCXCursor(Size, StmtParent, TU));
1400
1401 return false;
1402}
1403
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001404bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1405 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001406 // Visit the template name.
1407 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1408 TL.getTemplateNameLoc()))
1409 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001410
1411 // Visit the template arguments.
1412 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1413 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1414 return true;
1415
1416 return false;
1417}
1418
Douglas Gregor2332c112010-01-21 20:48:56 +00001419bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1420 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1421}
1422
1423bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1424 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1425 return Visit(TSInfo->getTypeLoc());
1426
1427 return false;
1428}
1429
Douglas Gregora59e3902010-01-21 23:27:09 +00001430bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001431 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001432}
1433
Ted Kremenek3064ef92010-08-27 21:34:58 +00001434bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1435 if (D->isDefinition()) {
1436 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1437 E = D->bases_end(); I != E; ++I) {
1438 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1439 return true;
1440 }
1441 }
1442
1443 return VisitTagDecl(D);
1444}
1445
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001446bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001447 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001448 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1449 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001450
1451 // Visit the components of the offsetof expression.
1452 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1453 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1454 const OffsetOfNode &Node = E->getComponent(I);
1455 switch (Node.getKind()) {
1456 case OffsetOfNode::Array:
1457 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1458 StmtParent, TU)))
1459 return true;
1460 break;
1461
1462 case OffsetOfNode::Field:
1463 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1464 TU)))
1465 return true;
1466 break;
1467
1468 case OffsetOfNode::Identifier:
1469 case OffsetOfNode::Base:
1470 continue;
1471 }
1472 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001473
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001474 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001475}
1476
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001477bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1478 // Visit the designators.
1479 typedef DesignatedInitExpr::Designator Designator;
1480 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1481 DEnd = E->designators_end();
1482 D != DEnd; ++D) {
1483 if (D->isFieldDesignator()) {
1484 if (FieldDecl *Field = D->getField())
1485 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1486 return true;
1487
1488 continue;
1489 }
1490
1491 if (D->isArrayDesignator()) {
1492 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1493 return true;
1494
1495 continue;
1496 }
1497
1498 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1499 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1500 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1501 return true;
1502 }
1503
1504 // Visit the initializer value itself.
1505 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1506}
1507
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001508bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1509 // Visit base expression.
1510 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1511 return true;
1512
1513 // Visit the nested-name-specifier.
1514 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1515 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1516 return true;
1517
1518 // Visit the scope type that looks disturbingly like the nested-name-specifier
1519 // but isn't.
1520 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1521 if (Visit(TSInfo->getTypeLoc()))
1522 return true;
1523
1524 // Visit the name of the type being destroyed.
1525 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1526 if (Visit(TSInfo->getTypeLoc()))
1527 return true;
1528
1529 return false;
1530}
1531
Douglas Gregorbfebed22010-09-03 17:24:10 +00001532bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1533 DependentScopeDeclRefExpr *E) {
1534 // Visit the nested-name-specifier.
1535 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1536 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1537 return true;
1538
1539 // Visit the declaration name.
1540 if (VisitDeclarationNameInfo(E->getNameInfo()))
1541 return true;
1542
1543 // Visit the explicitly-specified template arguments.
1544 if (const ExplicitTemplateArgumentList *ArgList
1545 = E->getOptionalExplicitTemplateArgs()) {
1546 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1547 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1548 Arg != ArgEnd; ++Arg) {
1549 if (VisitTemplateArgumentLoc(*Arg))
1550 return true;
1551 }
1552 }
1553
1554 return false;
1555}
1556
Douglas Gregor25d63622010-09-03 17:35:34 +00001557bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1558 CXXDependentScopeMemberExpr *E) {
1559 // Visit the base expression, if there is one.
1560 if (!E->isImplicitAccess() &&
1561 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1562 return true;
1563
1564 // Visit the nested-name-specifier.
1565 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1566 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1567 return true;
1568
1569 // Visit the declaration name.
1570 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1571 return true;
1572
1573 // Visit the explicitly-specified template arguments.
1574 if (const ExplicitTemplateArgumentList *ArgList
1575 = E->getOptionalExplicitTemplateArgs()) {
1576 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1577 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1578 Arg != ArgEnd; ++Arg) {
1579 if (VisitTemplateArgumentLoc(*Arg))
1580 return true;
1581 }
1582 }
1583
1584 return false;
1585}
1586
Ted Kremenek09dfa372010-02-18 05:46:33 +00001587bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001588 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1589 i != e; ++i)
1590 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001591 return true;
1592
1593 return false;
1594}
1595
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001596//===----------------------------------------------------------------------===//
1597// Data-recursive visitor methods.
1598//===----------------------------------------------------------------------===//
1599
Ted Kremenek28a71942010-11-13 00:36:47 +00001600namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001601#define DEF_JOB(NAME, DATA, KIND)\
1602class NAME : public VisitorJob {\
1603public:\
1604 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1605 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1606 DATA *get() const { return static_cast<DATA*>(dataA); }\
1607};
1608
1609DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1610DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001611DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001612DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001613DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1614 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001615#undef DEF_JOB
1616
1617class DeclVisit : public VisitorJob {
1618public:
1619 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1620 VisitorJob(parent, VisitorJob::DeclVisitKind,
1621 d, isFirst ? (void*) 1 : (void*) 0) {}
1622 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001623 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001624 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001625 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001626 bool isFirst() const { return dataB ? true : false; }
1627};
Ted Kremenek035dc412010-11-13 00:36:50 +00001628class TypeLocVisit : public VisitorJob {
1629public:
1630 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1631 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1632 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1633
1634 static bool classof(const VisitorJob *VJ) {
1635 return VJ->getKind() == TypeLocVisitKind;
1636 }
1637
Ted Kremenek82f3c502010-11-15 22:23:26 +00001638 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001639 QualType T = QualType::getFromOpaquePtr(dataA);
1640 return TypeLoc(T, dataB);
1641 }
1642};
1643
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001644class LabelRefVisit : public VisitorJob {
1645public:
1646 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1647 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1648 (void*) labelLoc.getRawEncoding()) {}
1649
1650 static bool classof(const VisitorJob *VJ) {
1651 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1652 }
1653 LabelStmt *get() const { return static_cast<LabelStmt*>(dataA); }
1654 SourceLocation getLoc() const {
1655 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) dataB); }
1656};
1657
Ted Kremenek28a71942010-11-13 00:36:47 +00001658class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1659 VisitorWorkList &WL;
1660 CXCursor Parent;
1661public:
1662 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1663 : WL(wl), Parent(parent) {}
1664
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001665 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001666 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001667 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001668 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001669 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1670 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001671 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001672 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001673 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001674 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001675 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001676 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001677 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001678 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001679 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1680 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001681 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001682 void VisitIfStmt(IfStmt *If);
1683 void VisitInitListExpr(InitListExpr *IE);
1684 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001685 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001686 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1687 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001688 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001689 void VisitStmt(Stmt *S);
1690 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001691 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001692 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001693 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001694 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001695 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696
1697private:
Ted Kremenek60608ec2010-11-17 00:50:47 +00001698 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenek28a71942010-11-13 00:36:47 +00001699 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001700 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001701 void AddTypeLoc(TypeSourceInfo *TI);
1702 void EnqueueChildren(Stmt *S);
1703};
1704} // end anonyous namespace
1705
1706void EnqueueVisitor::AddStmt(Stmt *S) {
1707 if (S)
1708 WL.push_back(StmtVisit(S, Parent));
1709}
Ted Kremenek035dc412010-11-13 00:36:50 +00001710void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001711 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001712 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001713}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001714void EnqueueVisitor::
1715 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1716 if (A)
1717 WL.push_back(ExplicitTemplateArgsVisit(
1718 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1719}
Ted Kremenek28a71942010-11-13 00:36:47 +00001720void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1721 if (TI)
1722 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1723 }
1724void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001725 unsigned size = WL.size();
1726 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1727 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001728 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001729 }
1730 if (size == WL.size())
1731 return;
1732 // Now reverse the entries we just added. This will match the DFS
1733 // ordering performed by the worklist.
1734 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1735 std::reverse(I, E);
1736}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001737void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1738 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1739}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001740void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1741 AddDecl(B->getBlockDecl());
1742}
Ted Kremenek28a71942010-11-13 00:36:47 +00001743void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1744 EnqueueChildren(E);
1745 AddTypeLoc(E->getTypeSourceInfo());
1746}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001747void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1748 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1749 E = S->body_rend(); I != E; ++I) {
1750 AddStmt(*I);
1751 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001752}
1753void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1754 // Enqueue the initializer or constructor arguments.
1755 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1756 AddStmt(E->getConstructorArg(I-1));
1757 // Enqueue the array size, if any.
1758 AddStmt(E->getArraySize());
1759 // Enqueue the allocated type.
1760 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1761 // Enqueue the placement arguments.
1762 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1763 AddStmt(E->getPlacementArg(I-1));
1764}
Ted Kremenek28a71942010-11-13 00:36:47 +00001765void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001766 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1767 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001768 AddStmt(CE->getCallee());
1769 AddStmt(CE->getArg(0));
1770}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001771void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1772 AddTypeLoc(E->getTypeSourceInfo());
1773}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001774void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1775 EnqueueChildren(E);
1776 AddTypeLoc(E->getTypeSourceInfo());
1777}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001778void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1779 EnqueueChildren(E);
1780 if (E->isTypeOperand())
1781 AddTypeLoc(E->getTypeOperandSourceInfo());
1782}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001783
1784void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1785 *E) {
1786 EnqueueChildren(E);
1787 AddTypeLoc(E->getTypeSourceInfo());
1788}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001789void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1790 EnqueueChildren(E);
1791 if (E->isTypeOperand())
1792 AddTypeLoc(E->getTypeOperandSourceInfo());
1793}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001794void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001795 if (DR->hasExplicitTemplateArgs()) {
1796 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1797 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001798 WL.push_back(DeclRefExprParts(DR, Parent));
1799}
Ted Kremenek035dc412010-11-13 00:36:50 +00001800void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1801 unsigned size = WL.size();
1802 bool isFirst = true;
1803 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1804 D != DEnd; ++D) {
1805 AddDecl(*D, isFirst);
1806 isFirst = false;
1807 }
1808 if (size == WL.size())
1809 return;
1810 // Now reverse the entries we just added. This will match the DFS
1811 // ordering performed by the worklist.
1812 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1813 std::reverse(I, E);
1814}
Ted Kremenek28a71942010-11-13 00:36:47 +00001815void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1816 EnqueueChildren(E);
1817 AddTypeLoc(E->getTypeInfoAsWritten());
1818}
1819void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1820 AddStmt(FS->getBody());
1821 AddStmt(FS->getInc());
1822 AddStmt(FS->getCond());
1823 AddDecl(FS->getConditionVariable());
1824 AddStmt(FS->getInit());
1825}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001826void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1827 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1828}
Ted Kremenek28a71942010-11-13 00:36:47 +00001829void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1830 AddStmt(If->getElse());
1831 AddStmt(If->getThen());
1832 AddStmt(If->getCond());
1833 AddDecl(If->getConditionVariable());
1834}
1835void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1836 // We care about the syntactic form of the initializer list, only.
1837 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1838 IE = Syntactic;
1839 EnqueueChildren(IE);
1840}
1841void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1842 WL.push_back(MemberExprParts(M, Parent));
1843 AddStmt(M->getBase());
1844}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001845void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1846 AddTypeLoc(E->getEncodedTypeSourceInfo());
1847}
Ted Kremenek28a71942010-11-13 00:36:47 +00001848void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1849 EnqueueChildren(M);
1850 AddTypeLoc(M->getClassReceiverTypeInfo());
1851}
1852void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001853 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001854 WL.push_back(OverloadExprParts(E, Parent));
1855}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001856void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1857 EnqueueChildren(E);
1858 if (E->isArgumentType())
1859 AddTypeLoc(E->getArgumentTypeInfo());
1860}
Ted Kremenek28a71942010-11-13 00:36:47 +00001861void EnqueueVisitor::VisitStmt(Stmt *S) {
1862 EnqueueChildren(S);
1863}
1864void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1865 AddStmt(S->getBody());
1866 AddStmt(S->getCond());
1867 AddDecl(S->getConditionVariable());
1868}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001869void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1870 AddTypeLoc(E->getArgTInfo2());
1871 AddTypeLoc(E->getArgTInfo1());
1872}
1873
Ted Kremenek28a71942010-11-13 00:36:47 +00001874void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1875 AddStmt(W->getBody());
1876 AddStmt(W->getCond());
1877 AddDecl(W->getConditionVariable());
1878}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001879void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1880 AddTypeLoc(E->getQueriedTypeSourceInfo());
1881}
Ted Kremenek28a71942010-11-13 00:36:47 +00001882void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1883 VisitOverloadExpr(U);
1884 if (!U->isImplicitAccess())
1885 AddStmt(U->getBase());
1886}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001887void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1888 AddStmt(E->getSubExpr());
1889 AddTypeLoc(E->getWrittenTypeInfo());
1890}
Ted Kremenek60458782010-11-12 21:34:16 +00001891
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001892void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001893 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001894}
1895
1896bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1897 if (RegionOfInterest.isValid()) {
1898 SourceRange Range = getRawCursorExtent(C);
1899 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1900 return false;
1901 }
1902 return true;
1903}
1904
1905bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1906 while (!WL.empty()) {
1907 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001908 VisitorJob LI = WL.back();
1909 WL.pop_back();
1910
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001911 // Set the Parent field, then back to its old value once we're done.
1912 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1913
1914 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001915 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001916 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001917 if (!D)
1918 continue;
1919
1920 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001921 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001922 return true;
1923
1924 continue;
1925 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001926 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1927 const ExplicitTemplateArgumentList *ArgList =
1928 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1929 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1930 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1931 Arg != ArgEnd; ++Arg) {
1932 if (VisitTemplateArgumentLoc(*Arg))
1933 return true;
1934 }
1935 continue;
1936 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001937 case VisitorJob::TypeLocVisitKind: {
1938 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001939 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001940 return true;
1941 continue;
1942 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001943 case VisitorJob::LabelRefVisitKind: {
1944 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1945 if (Visit(MakeCursorLabelRef(LS,
1946 cast<LabelRefVisit>(&LI)->getLoc(),
1947 TU)))
1948 return true;
1949 continue;
1950 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001951 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001952 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001953 if (!S)
1954 continue;
1955
Ted Kremenekf1107452010-11-12 18:26:56 +00001956 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001957 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1958
1959 switch (S->getStmtClass()) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001960 // Cases not yet handled by the data-recursion
1961 // algorithm.
1962 case Stmt::OffsetOfExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001963 case Stmt::DesignatedInitExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001964 case Stmt::CXXPseudoDestructorExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001965 case Stmt::DependentScopeDeclRefExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001966 case Stmt::CXXDependentScopeMemberExprClass:
1967 if (Visit(Cursor))
1968 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001969 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001970 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001971 if (!IsInRegionOfInterest(Cursor))
1972 continue;
1973 switch (Visitor(Cursor, Parent, ClientData)) {
1974 case CXChildVisit_Break:
1975 return true;
1976 case CXChildVisit_Continue:
1977 break;
1978 case CXChildVisit_Recurse:
1979 EnqueueWorkList(WL, S);
1980 break;
1981 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001982 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001983 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001984 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001985 }
1986 case VisitorJob::MemberExprPartsKind: {
1987 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001988 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001989
1990 // Visit the nested-name-specifier
1991 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1992 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1993 return true;
1994
1995 // Visit the declaration name.
1996 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1997 return true;
1998
1999 // Visit the explicitly-specified template arguments, if any.
2000 if (M->hasExplicitTemplateArgs()) {
2001 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2002 *ArgEnd = Arg + M->getNumTemplateArgs();
2003 Arg != ArgEnd; ++Arg) {
2004 if (VisitTemplateArgumentLoc(*Arg))
2005 return true;
2006 }
2007 }
2008 continue;
2009 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002010 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002011 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002012 // Visit nested-name-specifier, if present.
2013 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2014 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2015 return true;
2016 // Visit declaration name.
2017 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2018 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002019 continue;
2020 }
Ted Kremenek60458782010-11-12 21:34:16 +00002021 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002022 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002023 // Visit the nested-name-specifier.
2024 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2025 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2026 return true;
2027 // Visit the declaration name.
2028 if (VisitDeclarationNameInfo(O->getNameInfo()))
2029 return true;
2030 // Visit the overloaded declaration reference.
2031 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2032 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002033 continue;
2034 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002035 }
2036 }
2037 return false;
2038}
2039
2040bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002041 VisitorWorkList *WL = 0;
2042 if (!WorkListFreeList.empty()) {
2043 WL = WorkListFreeList.back();
2044 WL->clear();
2045 WorkListFreeList.pop_back();
2046 }
2047 else {
2048 WL = new VisitorWorkList();
2049 WorkListCache.push_back(WL);
2050 }
2051 EnqueueWorkList(*WL, S);
2052 bool result = RunVisitorWorkList(*WL);
2053 WorkListFreeList.push_back(WL);
2054 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002055}
2056
2057//===----------------------------------------------------------------------===//
2058// Misc. API hooks.
2059//===----------------------------------------------------------------------===//
2060
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002061static llvm::sys::Mutex EnableMultithreadingMutex;
2062static bool EnabledMultithreading;
2063
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002064extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002065CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2066 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002067 // Disable pretty stack trace functionality, which will otherwise be a very
2068 // poor citizen of the world and set up all sorts of signal handlers.
2069 llvm::DisablePrettyStackTrace = true;
2070
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002071 // We use crash recovery to make some of our APIs more reliable, implicitly
2072 // enable it.
2073 llvm::CrashRecoveryContext::Enable();
2074
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002075 // Enable support for multithreading in LLVM.
2076 {
2077 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2078 if (!EnabledMultithreading) {
2079 llvm::llvm_start_multithreaded();
2080 EnabledMultithreading = true;
2081 }
2082 }
2083
Douglas Gregora030b7c2010-01-22 20:35:53 +00002084 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002085 if (excludeDeclarationsFromPCH)
2086 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002087 if (displayDiagnostics)
2088 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002089 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002090}
2091
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002092void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002093 if (CIdx)
2094 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002095}
2096
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002097CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002098 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002099 if (!CIdx)
2100 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002101
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002102 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002103 FileSystemOptions FileSystemOpts;
2104 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002105
Douglas Gregor28019772010-04-05 23:52:57 +00002106 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002107 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002108 CXXIdx->getOnlyLocalDecls(),
2109 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002110 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002111}
2112
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002113unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002114 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002115 CXTranslationUnit_CacheCompletionResults |
2116 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002117}
2118
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002119CXTranslationUnit
2120clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2121 const char *source_filename,
2122 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002123 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002124 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002125 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002126 return clang_parseTranslationUnit(CIdx, source_filename,
2127 command_line_args, num_command_line_args,
2128 unsaved_files, num_unsaved_files,
2129 CXTranslationUnit_DetailedPreprocessingRecord);
2130}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002131
2132struct ParseTranslationUnitInfo {
2133 CXIndex CIdx;
2134 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002135 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002136 int num_command_line_args;
2137 struct CXUnsavedFile *unsaved_files;
2138 unsigned num_unsaved_files;
2139 unsigned options;
2140 CXTranslationUnit result;
2141};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002142static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002143 ParseTranslationUnitInfo *PTUI =
2144 static_cast<ParseTranslationUnitInfo*>(UserData);
2145 CXIndex CIdx = PTUI->CIdx;
2146 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002147 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002148 int num_command_line_args = PTUI->num_command_line_args;
2149 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2150 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2151 unsigned options = PTUI->options;
2152 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002153
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002154 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002155 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002156
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002157 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2158
Douglas Gregor44c181a2010-07-23 00:33:23 +00002159 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002160 bool CompleteTranslationUnit
2161 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002162 bool CacheCodeCompetionResults
2163 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002164 bool CXXPrecompilePreamble
2165 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2166 bool CXXChainedPCH
2167 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002168
Douglas Gregor5352ac02010-01-28 00:27:43 +00002169 // Configure the diagnostics.
2170 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002171 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2172 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173
Douglas Gregor4db64a42010-01-23 00:14:00 +00002174 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2175 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002176 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002177 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002178 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002179 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2180 Buffer));
2181 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002182
Douglas Gregorb10daed2010-10-11 16:52:23 +00002183 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002184
Ted Kremenek139ba862009-10-22 00:03:57 +00002185 // The 'source_filename' argument is optional. If the caller does not
2186 // specify it then it is assumed that the source file is specified
2187 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002188 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002189 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002190
2191 // Since the Clang C library is primarily used by batch tools dealing with
2192 // (often very broken) source code, where spell-checking can have a
2193 // significant negative impact on performance (particularly when
2194 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002195 // Only do this if we haven't found a spell-checking-related argument.
2196 bool FoundSpellCheckingArgument = false;
2197 for (int I = 0; I != num_command_line_args; ++I) {
2198 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2199 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2200 FoundSpellCheckingArgument = true;
2201 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002202 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002203 }
2204 if (!FoundSpellCheckingArgument)
2205 Args.push_back("-fno-spell-checking");
2206
2207 Args.insert(Args.end(), command_line_args,
2208 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002209
Douglas Gregor44c181a2010-07-23 00:33:23 +00002210 // Do we need the detailed preprocessing record?
2211 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002212 Args.push_back("-Xclang");
2213 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002214 }
2215
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002217 llvm::OwningPtr<ASTUnit> Unit(
2218 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2219 Diags,
2220 CXXIdx->getClangResourcesPath(),
2221 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002222 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002223 RemappedFiles.data(),
2224 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002225 PrecompilePreamble,
2226 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002227 CacheCodeCompetionResults,
2228 CXXPrecompilePreamble,
2229 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002230
Douglas Gregorb10daed2010-10-11 16:52:23 +00002231 if (NumErrors != Diags->getNumErrors()) {
2232 // Make sure to check that 'Unit' is non-NULL.
2233 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2234 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2235 DEnd = Unit->stored_diag_end();
2236 D != DEnd; ++D) {
2237 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2238 CXString Msg = clang_formatDiagnostic(&Diag,
2239 clang_defaultDiagnosticDisplayOptions());
2240 fprintf(stderr, "%s\n", clang_getCString(Msg));
2241 clang_disposeString(Msg);
2242 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002243#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002244 // On Windows, force a flush, since there may be multiple copies of
2245 // stderr and stdout in the file system, all with different buffers
2246 // but writing to the same device.
2247 fflush(stderr);
2248#endif
2249 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002250 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002251
Ted Kremeneka60ed472010-11-16 08:15:36 +00002252 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002253}
2254CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2255 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002256 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002257 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002258 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002259 unsigned num_unsaved_files,
2260 unsigned options) {
2261 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002262 num_command_line_args, unsaved_files,
2263 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002264 llvm::CrashRecoveryContext CRC;
2265
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002266 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002267 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2268 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2269 fprintf(stderr, " 'command_line_args' : [");
2270 for (int i = 0; i != num_command_line_args; ++i) {
2271 if (i)
2272 fprintf(stderr, ", ");
2273 fprintf(stderr, "'%s'", command_line_args[i]);
2274 }
2275 fprintf(stderr, "],\n");
2276 fprintf(stderr, " 'unsaved_files' : [");
2277 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2278 if (i)
2279 fprintf(stderr, ", ");
2280 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2281 unsaved_files[i].Length);
2282 }
2283 fprintf(stderr, "],\n");
2284 fprintf(stderr, " 'options' : %d,\n", options);
2285 fprintf(stderr, "}\n");
2286
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002287 return 0;
2288 }
2289
2290 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002291}
2292
Douglas Gregor19998442010-08-13 15:35:05 +00002293unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2294 return CXSaveTranslationUnit_None;
2295}
2296
2297int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2298 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002299 if (!TU)
2300 return 1;
2301
Ted Kremeneka60ed472010-11-16 08:15:36 +00002302 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002303}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002304
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002305void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002306 if (CTUnit) {
2307 // If the translation unit has been marked as unsafe to free, just discard
2308 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002309 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002310 return;
2311
Ted Kremeneka60ed472010-11-16 08:15:36 +00002312 delete static_cast<ASTUnit *>(CTUnit->TUData);
2313 disposeCXStringPool(CTUnit->StringPool);
2314 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002315 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002316}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002317
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002318unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2319 return CXReparse_None;
2320}
2321
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002322struct ReparseTranslationUnitInfo {
2323 CXTranslationUnit TU;
2324 unsigned num_unsaved_files;
2325 struct CXUnsavedFile *unsaved_files;
2326 unsigned options;
2327 int result;
2328};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002329
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002330static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002331 ReparseTranslationUnitInfo *RTUI =
2332 static_cast<ReparseTranslationUnitInfo*>(UserData);
2333 CXTranslationUnit TU = RTUI->TU;
2334 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2335 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2336 unsigned options = RTUI->options;
2337 (void) options;
2338 RTUI->result = 1;
2339
Douglas Gregorabc563f2010-07-19 21:46:24 +00002340 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002341 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002342
Ted Kremeneka60ed472010-11-16 08:15:36 +00002343 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002344 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002345
2346 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2347 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2348 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2349 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002350 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002351 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2352 Buffer));
2353 }
2354
Douglas Gregor593b0c12010-09-23 18:47:53 +00002355 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2356 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002357}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002358
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002359int clang_reparseTranslationUnit(CXTranslationUnit TU,
2360 unsigned num_unsaved_files,
2361 struct CXUnsavedFile *unsaved_files,
2362 unsigned options) {
2363 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2364 options, 0 };
2365 llvm::CrashRecoveryContext CRC;
2366
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002367 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002368 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002369 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002370 return 1;
2371 }
2372
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002373
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002374 return RTUI.result;
2375}
2376
Douglas Gregordf95a132010-08-09 20:45:32 +00002377
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002378CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002379 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002380 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002381
Ted Kremeneka60ed472010-11-16 08:15:36 +00002382 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002383 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002384}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002385
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002386CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002387 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002388 return Result;
2389}
2390
Ted Kremenekfb480492010-01-13 21:46:36 +00002391} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002392
Ted Kremenekfb480492010-01-13 21:46:36 +00002393//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002394// CXSourceLocation and CXSourceRange Operations.
2395//===----------------------------------------------------------------------===//
2396
Douglas Gregorb9790342010-01-22 21:44:22 +00002397extern "C" {
2398CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002399 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002400 return Result;
2401}
2402
2403unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002404 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2405 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2406 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002407}
2408
2409CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2410 CXFile file,
2411 unsigned line,
2412 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002413 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002414 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002415
Ted Kremeneka60ed472010-11-16 08:15:36 +00002416 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002417 SourceLocation SLoc
2418 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002420 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002421 if (SLoc.isInvalid()) return clang_getNullLocation();
2422
2423 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2424}
2425
2426CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2427 CXFile file,
2428 unsigned offset) {
2429 if (!tu || !file)
2430 return clang_getNullLocation();
2431
Ted Kremeneka60ed472010-11-16 08:15:36 +00002432 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002433 SourceLocation Start
2434 = CXXUnit->getSourceManager().getLocation(
2435 static_cast<const FileEntry *>(file),
2436 1, 1);
2437 if (Start.isInvalid()) return clang_getNullLocation();
2438
2439 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2440
2441 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002442
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002443 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002444}
2445
Douglas Gregor5352ac02010-01-28 00:27:43 +00002446CXSourceRange clang_getNullRange() {
2447 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2448 return Result;
2449}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002450
Douglas Gregor5352ac02010-01-28 00:27:43 +00002451CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2452 if (begin.ptr_data[0] != end.ptr_data[0] ||
2453 begin.ptr_data[1] != end.ptr_data[1])
2454 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002455
2456 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002457 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002458 return Result;
2459}
2460
Douglas Gregor46766dc2010-01-26 19:19:08 +00002461void clang_getInstantiationLocation(CXSourceLocation location,
2462 CXFile *file,
2463 unsigned *line,
2464 unsigned *column,
2465 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002466 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2467
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002468 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002469 if (file)
2470 *file = 0;
2471 if (line)
2472 *line = 0;
2473 if (column)
2474 *column = 0;
2475 if (offset)
2476 *offset = 0;
2477 return;
2478 }
2479
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002480 const SourceManager &SM =
2481 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002482 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002483
2484 if (file)
2485 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2486 if (line)
2487 *line = SM.getInstantiationLineNumber(InstLoc);
2488 if (column)
2489 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002490 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002491 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002492}
2493
Douglas Gregora9b06d42010-11-09 06:24:54 +00002494void clang_getSpellingLocation(CXSourceLocation location,
2495 CXFile *file,
2496 unsigned *line,
2497 unsigned *column,
2498 unsigned *offset) {
2499 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2500
2501 if (!location.ptr_data[0] || Loc.isInvalid()) {
2502 if (file)
2503 *file = 0;
2504 if (line)
2505 *line = 0;
2506 if (column)
2507 *column = 0;
2508 if (offset)
2509 *offset = 0;
2510 return;
2511 }
2512
2513 const SourceManager &SM =
2514 *static_cast<const SourceManager*>(location.ptr_data[0]);
2515 SourceLocation SpellLoc = Loc;
2516 if (SpellLoc.isMacroID()) {
2517 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2518 if (SimpleSpellingLoc.isFileID() &&
2519 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2520 SpellLoc = SimpleSpellingLoc;
2521 else
2522 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2523 }
2524
2525 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2526 FileID FID = LocInfo.first;
2527 unsigned FileOffset = LocInfo.second;
2528
2529 if (file)
2530 *file = (void *)SM.getFileEntryForID(FID);
2531 if (line)
2532 *line = SM.getLineNumber(FID, FileOffset);
2533 if (column)
2534 *column = SM.getColumnNumber(FID, FileOffset);
2535 if (offset)
2536 *offset = FileOffset;
2537}
2538
Douglas Gregor1db19de2010-01-19 21:36:55 +00002539CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002540 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002541 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002542 return Result;
2543}
2544
2545CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002546 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002547 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002548 return Result;
2549}
2550
Douglas Gregorb9790342010-01-22 21:44:22 +00002551} // end: extern "C"
2552
Douglas Gregor1db19de2010-01-19 21:36:55 +00002553//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002554// CXFile Operations.
2555//===----------------------------------------------------------------------===//
2556
2557extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002558CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002559 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002560 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002561
Steve Naroff88145032009-10-27 14:35:18 +00002562 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002563 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002564}
2565
2566time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002567 if (!SFile)
2568 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Steve Naroff88145032009-10-27 14:35:18 +00002570 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2571 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002572}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002573
Douglas Gregorb9790342010-01-22 21:44:22 +00002574CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2575 if (!tu)
2576 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002577
Ted Kremeneka60ed472010-11-16 08:15:36 +00002578 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002579
Douglas Gregorb9790342010-01-22 21:44:22 +00002580 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002581 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2582 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002583 return const_cast<FileEntry *>(File);
2584}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Ted Kremenekfb480492010-01-13 21:46:36 +00002586} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002587
Ted Kremenekfb480492010-01-13 21:46:36 +00002588//===----------------------------------------------------------------------===//
2589// CXCursor Operations.
2590//===----------------------------------------------------------------------===//
2591
Ted Kremenekfb480492010-01-13 21:46:36 +00002592static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002593 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2594 return getDeclFromExpr(CE->getSubExpr());
2595
Ted Kremenekfb480492010-01-13 21:46:36 +00002596 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2597 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002598 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2599 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002600 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2601 return ME->getMemberDecl();
2602 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2603 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002604 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2605 return PRE->getProperty();
2606
Ted Kremenekfb480492010-01-13 21:46:36 +00002607 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2608 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002609 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2610 if (!CE->isElidable())
2611 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002612 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2613 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002614
Douglas Gregordb1314e2010-10-01 21:11:22 +00002615 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2616 return PE->getProtocol();
2617
Ted Kremenekfb480492010-01-13 21:46:36 +00002618 return 0;
2619}
2620
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002621static SourceLocation getLocationFromExpr(Expr *E) {
2622 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2623 return /*FIXME:*/Msg->getLeftLoc();
2624 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2625 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002626 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2627 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002628 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2629 return Member->getMemberLoc();
2630 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2631 return Ivar->getLocation();
2632 return E->getLocStart();
2633}
2634
Ted Kremenekfb480492010-01-13 21:46:36 +00002635extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002636
2637unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002638 CXCursorVisitor visitor,
2639 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002640 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2641 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002642 return CursorVis.VisitChildren(parent);
2643}
2644
David Chisnall3387c652010-11-03 14:12:26 +00002645#ifndef __has_feature
2646#define __has_feature(x) 0
2647#endif
2648#if __has_feature(blocks)
2649typedef enum CXChildVisitResult
2650 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2651
2652static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2653 CXClientData client_data) {
2654 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2655 return block(cursor, parent);
2656}
2657#else
2658// If we are compiled with a compiler that doesn't have native blocks support,
2659// define and call the block manually, so the
2660typedef struct _CXChildVisitResult
2661{
2662 void *isa;
2663 int flags;
2664 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002665 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2666 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002667} *CXCursorVisitorBlock;
2668
2669static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2670 CXClientData client_data) {
2671 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2672 return block->invoke(block, cursor, parent);
2673}
2674#endif
2675
2676
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002677unsigned clang_visitChildrenWithBlock(CXCursor parent,
2678 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002679 return clang_visitChildren(parent, visitWithBlock, block);
2680}
2681
Douglas Gregor78205d42010-01-20 21:45:58 +00002682static CXString getDeclSpelling(Decl *D) {
2683 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002684 if (!ND) {
2685 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2686 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2687 return createCXString(Property->getIdentifier()->getName());
2688
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002689 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002690 }
2691
Douglas Gregor78205d42010-01-20 21:45:58 +00002692 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002693 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002694
Douglas Gregor78205d42010-01-20 21:45:58 +00002695 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2696 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2697 // and returns different names. NamedDecl returns the class name and
2698 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002699 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002700
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002701 if (isa<UsingDirectiveDecl>(D))
2702 return createCXString("");
2703
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002704 llvm::SmallString<1024> S;
2705 llvm::raw_svector_ostream os(S);
2706 ND->printName(os);
2707
2708 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002709}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002710
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002711CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002712 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002713 return clang_getTranslationUnitSpelling(
2714 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002715
Steve Narofff334b4e2009-09-02 18:26:48 +00002716 if (clang_isReference(C.kind)) {
2717 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002718 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002719 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002720 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002721 }
2722 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002723 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002724 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002725 }
2726 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002727 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002728 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002729 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002730 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002731 case CXCursor_CXXBaseSpecifier: {
2732 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2733 return createCXString(B->getType().getAsString());
2734 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002735 case CXCursor_TypeRef: {
2736 TypeDecl *Type = getCursorTypeRef(C).first;
2737 assert(Type && "Missing type decl");
2738
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002739 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2740 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002741 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002742 case CXCursor_TemplateRef: {
2743 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002744 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002745
2746 return createCXString(Template->getNameAsString());
2747 }
Douglas Gregor69319002010-08-31 23:48:11 +00002748
2749 case CXCursor_NamespaceRef: {
2750 NamedDecl *NS = getCursorNamespaceRef(C).first;
2751 assert(NS && "Missing namespace decl");
2752
2753 return createCXString(NS->getNameAsString());
2754 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002755
Douglas Gregora67e03f2010-09-09 21:42:20 +00002756 case CXCursor_MemberRef: {
2757 FieldDecl *Field = getCursorMemberRef(C).first;
2758 assert(Field && "Missing member decl");
2759
2760 return createCXString(Field->getNameAsString());
2761 }
2762
Douglas Gregor36897b02010-09-10 00:22:18 +00002763 case CXCursor_LabelRef: {
2764 LabelStmt *Label = getCursorLabelRef(C).first;
2765 assert(Label && "Missing label");
2766
2767 return createCXString(Label->getID()->getName());
2768 }
2769
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002770 case CXCursor_OverloadedDeclRef: {
2771 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2772 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2773 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2774 return createCXString(ND->getNameAsString());
2775 return createCXString("");
2776 }
2777 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2778 return createCXString(E->getName().getAsString());
2779 OverloadedTemplateStorage *Ovl
2780 = Storage.get<OverloadedTemplateStorage*>();
2781 if (Ovl->size() == 0)
2782 return createCXString("");
2783 return createCXString((*Ovl->begin())->getNameAsString());
2784 }
2785
Daniel Dunbaracca7252009-11-30 20:42:49 +00002786 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002787 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002788 }
2789 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002790
2791 if (clang_isExpression(C.kind)) {
2792 Decl *D = getDeclFromExpr(getCursorExpr(C));
2793 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002794 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002795 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002796 }
2797
Douglas Gregor36897b02010-09-10 00:22:18 +00002798 if (clang_isStatement(C.kind)) {
2799 Stmt *S = getCursorStmt(C);
2800 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2801 return createCXString(Label->getID()->getName());
2802
2803 return createCXString("");
2804 }
2805
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002806 if (C.kind == CXCursor_MacroInstantiation)
2807 return createCXString(getCursorMacroInstantiation(C)->getName()
2808 ->getNameStart());
2809
Douglas Gregor572feb22010-03-18 18:04:21 +00002810 if (C.kind == CXCursor_MacroDefinition)
2811 return createCXString(getCursorMacroDefinition(C)->getName()
2812 ->getNameStart());
2813
Douglas Gregorecdcb882010-10-20 22:00:55 +00002814 if (C.kind == CXCursor_InclusionDirective)
2815 return createCXString(getCursorInclusionDirective(C)->getFileName());
2816
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002817 if (clang_isDeclaration(C.kind))
2818 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002819
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002820 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002821}
2822
Douglas Gregor358559d2010-10-02 22:49:11 +00002823CXString clang_getCursorDisplayName(CXCursor C) {
2824 if (!clang_isDeclaration(C.kind))
2825 return clang_getCursorSpelling(C);
2826
2827 Decl *D = getCursorDecl(C);
2828 if (!D)
2829 return createCXString("");
2830
2831 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2832 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2833 D = FunTmpl->getTemplatedDecl();
2834
2835 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2836 llvm::SmallString<64> Str;
2837 llvm::raw_svector_ostream OS(Str);
2838 OS << Function->getNameAsString();
2839 if (Function->getPrimaryTemplate())
2840 OS << "<>";
2841 OS << "(";
2842 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2843 if (I)
2844 OS << ", ";
2845 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2846 }
2847
2848 if (Function->isVariadic()) {
2849 if (Function->getNumParams())
2850 OS << ", ";
2851 OS << "...";
2852 }
2853 OS << ")";
2854 return createCXString(OS.str());
2855 }
2856
2857 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2858 llvm::SmallString<64> Str;
2859 llvm::raw_svector_ostream OS(Str);
2860 OS << ClassTemplate->getNameAsString();
2861 OS << "<";
2862 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2863 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2864 if (I)
2865 OS << ", ";
2866
2867 NamedDecl *Param = Params->getParam(I);
2868 if (Param->getIdentifier()) {
2869 OS << Param->getIdentifier()->getName();
2870 continue;
2871 }
2872
2873 // There is no parameter name, which makes this tricky. Try to come up
2874 // with something useful that isn't too long.
2875 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2876 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2877 else if (NonTypeTemplateParmDecl *NTTP
2878 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2879 OS << NTTP->getType().getAsString(Policy);
2880 else
2881 OS << "template<...> class";
2882 }
2883
2884 OS << ">";
2885 return createCXString(OS.str());
2886 }
2887
2888 if (ClassTemplateSpecializationDecl *ClassSpec
2889 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2890 // If the type was explicitly written, use that.
2891 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2892 return createCXString(TSInfo->getType().getAsString(Policy));
2893
2894 llvm::SmallString<64> Str;
2895 llvm::raw_svector_ostream OS(Str);
2896 OS << ClassSpec->getNameAsString();
2897 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002898 ClassSpec->getTemplateArgs().data(),
2899 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002900 Policy);
2901 return createCXString(OS.str());
2902 }
2903
2904 return clang_getCursorSpelling(C);
2905}
2906
Ted Kremeneke68fff62010-02-17 00:41:32 +00002907CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002908 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002909 case CXCursor_FunctionDecl:
2910 return createCXString("FunctionDecl");
2911 case CXCursor_TypedefDecl:
2912 return createCXString("TypedefDecl");
2913 case CXCursor_EnumDecl:
2914 return createCXString("EnumDecl");
2915 case CXCursor_EnumConstantDecl:
2916 return createCXString("EnumConstantDecl");
2917 case CXCursor_StructDecl:
2918 return createCXString("StructDecl");
2919 case CXCursor_UnionDecl:
2920 return createCXString("UnionDecl");
2921 case CXCursor_ClassDecl:
2922 return createCXString("ClassDecl");
2923 case CXCursor_FieldDecl:
2924 return createCXString("FieldDecl");
2925 case CXCursor_VarDecl:
2926 return createCXString("VarDecl");
2927 case CXCursor_ParmDecl:
2928 return createCXString("ParmDecl");
2929 case CXCursor_ObjCInterfaceDecl:
2930 return createCXString("ObjCInterfaceDecl");
2931 case CXCursor_ObjCCategoryDecl:
2932 return createCXString("ObjCCategoryDecl");
2933 case CXCursor_ObjCProtocolDecl:
2934 return createCXString("ObjCProtocolDecl");
2935 case CXCursor_ObjCPropertyDecl:
2936 return createCXString("ObjCPropertyDecl");
2937 case CXCursor_ObjCIvarDecl:
2938 return createCXString("ObjCIvarDecl");
2939 case CXCursor_ObjCInstanceMethodDecl:
2940 return createCXString("ObjCInstanceMethodDecl");
2941 case CXCursor_ObjCClassMethodDecl:
2942 return createCXString("ObjCClassMethodDecl");
2943 case CXCursor_ObjCImplementationDecl:
2944 return createCXString("ObjCImplementationDecl");
2945 case CXCursor_ObjCCategoryImplDecl:
2946 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002947 case CXCursor_CXXMethod:
2948 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002949 case CXCursor_UnexposedDecl:
2950 return createCXString("UnexposedDecl");
2951 case CXCursor_ObjCSuperClassRef:
2952 return createCXString("ObjCSuperClassRef");
2953 case CXCursor_ObjCProtocolRef:
2954 return createCXString("ObjCProtocolRef");
2955 case CXCursor_ObjCClassRef:
2956 return createCXString("ObjCClassRef");
2957 case CXCursor_TypeRef:
2958 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002959 case CXCursor_TemplateRef:
2960 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002961 case CXCursor_NamespaceRef:
2962 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002963 case CXCursor_MemberRef:
2964 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002965 case CXCursor_LabelRef:
2966 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002967 case CXCursor_OverloadedDeclRef:
2968 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002969 case CXCursor_UnexposedExpr:
2970 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002971 case CXCursor_BlockExpr:
2972 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002973 case CXCursor_DeclRefExpr:
2974 return createCXString("DeclRefExpr");
2975 case CXCursor_MemberRefExpr:
2976 return createCXString("MemberRefExpr");
2977 case CXCursor_CallExpr:
2978 return createCXString("CallExpr");
2979 case CXCursor_ObjCMessageExpr:
2980 return createCXString("ObjCMessageExpr");
2981 case CXCursor_UnexposedStmt:
2982 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002983 case CXCursor_LabelStmt:
2984 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002985 case CXCursor_InvalidFile:
2986 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002987 case CXCursor_InvalidCode:
2988 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002989 case CXCursor_NoDeclFound:
2990 return createCXString("NoDeclFound");
2991 case CXCursor_NotImplemented:
2992 return createCXString("NotImplemented");
2993 case CXCursor_TranslationUnit:
2994 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002995 case CXCursor_UnexposedAttr:
2996 return createCXString("UnexposedAttr");
2997 case CXCursor_IBActionAttr:
2998 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002999 case CXCursor_IBOutletAttr:
3000 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003001 case CXCursor_IBOutletCollectionAttr:
3002 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003003 case CXCursor_PreprocessingDirective:
3004 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003005 case CXCursor_MacroDefinition:
3006 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003007 case CXCursor_MacroInstantiation:
3008 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003009 case CXCursor_InclusionDirective:
3010 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003011 case CXCursor_Namespace:
3012 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003013 case CXCursor_LinkageSpec:
3014 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003015 case CXCursor_CXXBaseSpecifier:
3016 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003017 case CXCursor_Constructor:
3018 return createCXString("CXXConstructor");
3019 case CXCursor_Destructor:
3020 return createCXString("CXXDestructor");
3021 case CXCursor_ConversionFunction:
3022 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003023 case CXCursor_TemplateTypeParameter:
3024 return createCXString("TemplateTypeParameter");
3025 case CXCursor_NonTypeTemplateParameter:
3026 return createCXString("NonTypeTemplateParameter");
3027 case CXCursor_TemplateTemplateParameter:
3028 return createCXString("TemplateTemplateParameter");
3029 case CXCursor_FunctionTemplate:
3030 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003031 case CXCursor_ClassTemplate:
3032 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003033 case CXCursor_ClassTemplatePartialSpecialization:
3034 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003035 case CXCursor_NamespaceAlias:
3036 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003037 case CXCursor_UsingDirective:
3038 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003039 case CXCursor_UsingDeclaration:
3040 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003041 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003042
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003043 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003044 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003045}
Steve Naroff89922f82009-08-31 00:59:03 +00003046
Ted Kremeneke68fff62010-02-17 00:41:32 +00003047enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3048 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003049 CXClientData client_data) {
3050 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003051
3052 // If our current best cursor is the construction of a temporary object,
3053 // don't replace that cursor with a type reference, because we want
3054 // clang_getCursor() to point at the constructor.
3055 if (clang_isExpression(BestCursor->kind) &&
3056 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3057 cursor.kind == CXCursor_TypeRef)
3058 return CXChildVisit_Recurse;
3059
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003060 *BestCursor = cursor;
3061 return CXChildVisit_Recurse;
3062}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003063
Douglas Gregorb9790342010-01-22 21:44:22 +00003064CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3065 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003066 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003067
Ted Kremeneka60ed472010-11-16 08:15:36 +00003068 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003069 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3070
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003071 // Translate the given source location to make it point at the beginning of
3072 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003073 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003074
3075 // Guard against an invalid SourceLocation, or we may assert in one
3076 // of the following calls.
3077 if (SLoc.isInvalid())
3078 return clang_getNullCursor();
3079
Douglas Gregor40749ee2010-11-03 00:35:38 +00003080 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003081 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3082 CXXUnit->getASTContext().getLangOptions());
3083
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003084 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3085 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003086 // FIXME: Would be great to have a "hint" cursor, then walk from that
3087 // hint cursor upward until we find a cursor whose source range encloses
3088 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003089 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3090 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003091 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003092 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003093 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003094
3095 if (Logging) {
3096 CXFile SearchFile;
3097 unsigned SearchLine, SearchColumn;
3098 CXFile ResultFile;
3099 unsigned ResultLine, ResultColumn;
3100 CXString SearchFileName, ResultFileName, KindSpelling;
3101 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3102
3103 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3104 0);
3105 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3106 &ResultColumn, 0);
3107 SearchFileName = clang_getFileName(SearchFile);
3108 ResultFileName = clang_getFileName(ResultFile);
3109 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3110 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3111 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3112 clang_getCString(KindSpelling),
3113 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3114 clang_disposeString(SearchFileName);
3115 clang_disposeString(ResultFileName);
3116 clang_disposeString(KindSpelling);
3117 }
3118
Ted Kremeneke68fff62010-02-17 00:41:32 +00003119 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003120}
3121
Ted Kremenek73885552009-11-17 19:28:59 +00003122CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003123 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003124}
3125
3126unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003127 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003128}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003129
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003130unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003131 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3132}
3133
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003134unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003135 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3136}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003137
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003138unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003139 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3140}
3141
Douglas Gregor97b98722010-01-19 23:20:36 +00003142unsigned clang_isExpression(enum CXCursorKind K) {
3143 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3144}
3145
3146unsigned clang_isStatement(enum CXCursorKind K) {
3147 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3148}
3149
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003150unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3151 return K == CXCursor_TranslationUnit;
3152}
3153
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003154unsigned clang_isPreprocessing(enum CXCursorKind K) {
3155 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3156}
3157
Ted Kremenekad6eff62010-03-08 21:17:29 +00003158unsigned clang_isUnexposed(enum CXCursorKind K) {
3159 switch (K) {
3160 case CXCursor_UnexposedDecl:
3161 case CXCursor_UnexposedExpr:
3162 case CXCursor_UnexposedStmt:
3163 case CXCursor_UnexposedAttr:
3164 return true;
3165 default:
3166 return false;
3167 }
3168}
3169
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003170CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003171 return C.kind;
3172}
3173
Douglas Gregor98258af2010-01-18 22:46:11 +00003174CXSourceLocation clang_getCursorLocation(CXCursor C) {
3175 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003176 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003177 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003178 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3179 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003180 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003181 }
3182
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003183 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003184 std::pair<ObjCProtocolDecl *, SourceLocation> P
3185 = getCursorObjCProtocolRef(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_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003190 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3191 = getCursorObjCClassRef(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 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003194
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003195 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003196 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003197 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003198 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003199
3200 case CXCursor_TemplateRef: {
3201 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3202 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3203 }
3204
Douglas Gregor69319002010-08-31 23:48:11 +00003205 case CXCursor_NamespaceRef: {
3206 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3207 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3208 }
3209
Douglas Gregora67e03f2010-09-09 21:42:20 +00003210 case CXCursor_MemberRef: {
3211 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3212 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3213 }
3214
Ted Kremenek3064ef92010-08-27 21:34:58 +00003215 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003216 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3217 if (!BaseSpec)
3218 return clang_getNullLocation();
3219
3220 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3221 return cxloc::translateSourceLocation(getCursorContext(C),
3222 TSInfo->getTypeLoc().getBeginLoc());
3223
3224 return cxloc::translateSourceLocation(getCursorContext(C),
3225 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003226 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003227
Douglas Gregor36897b02010-09-10 00:22:18 +00003228 case CXCursor_LabelRef: {
3229 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3230 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3231 }
3232
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003233 case CXCursor_OverloadedDeclRef:
3234 return cxloc::translateSourceLocation(getCursorContext(C),
3235 getCursorOverloadedDeclRef(C).second);
3236
Douglas Gregorf46034a2010-01-18 23:41:10 +00003237 default:
3238 // FIXME: Need a way to enumerate all non-reference cases.
3239 llvm_unreachable("Missed a reference kind");
3240 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003241 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003242
3243 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003244 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003245 getLocationFromExpr(getCursorExpr(C)));
3246
Douglas Gregor36897b02010-09-10 00:22:18 +00003247 if (clang_isStatement(C.kind))
3248 return cxloc::translateSourceLocation(getCursorContext(C),
3249 getCursorStmt(C)->getLocStart());
3250
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003251 if (C.kind == CXCursor_PreprocessingDirective) {
3252 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3253 return cxloc::translateSourceLocation(getCursorContext(C), L);
3254 }
Douglas Gregor48072312010-03-18 15:23:44 +00003255
3256 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003257 SourceLocation L
3258 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003259 return cxloc::translateSourceLocation(getCursorContext(C), L);
3260 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003261
3262 if (C.kind == CXCursor_MacroDefinition) {
3263 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3264 return cxloc::translateSourceLocation(getCursorContext(C), L);
3265 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003266
3267 if (C.kind == CXCursor_InclusionDirective) {
3268 SourceLocation L
3269 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3270 return cxloc::translateSourceLocation(getCursorContext(C), L);
3271 }
3272
Ted Kremenek9a700d22010-05-12 06:16:13 +00003273 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003274 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003275
Douglas Gregorf46034a2010-01-18 23:41:10 +00003276 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003277 SourceLocation Loc = D->getLocation();
3278 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3279 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003280 // FIXME: Multiple variables declared in a single declaration
3281 // currently lack the information needed to correctly determine their
3282 // ranges when accounting for the type-specifier. We use context
3283 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3284 // and if so, whether it is the first decl.
3285 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3286 if (!cxcursor::isFirstInDeclGroup(C))
3287 Loc = VD->getLocation();
3288 }
3289
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003290 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003291}
Douglas Gregora7bde202010-01-19 00:34:46 +00003292
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003293} // end extern "C"
3294
3295static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003296 if (clang_isReference(C.kind)) {
3297 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003298 case CXCursor_ObjCSuperClassRef:
3299 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003300
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003301 case CXCursor_ObjCProtocolRef:
3302 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003303
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003304 case CXCursor_ObjCClassRef:
3305 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003306
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003307 case CXCursor_TypeRef:
3308 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003309
3310 case CXCursor_TemplateRef:
3311 return getCursorTemplateRef(C).second;
3312
Douglas Gregor69319002010-08-31 23:48:11 +00003313 case CXCursor_NamespaceRef:
3314 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003315
3316 case CXCursor_MemberRef:
3317 return getCursorMemberRef(C).second;
3318
Ted Kremenek3064ef92010-08-27 21:34:58 +00003319 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003320 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003321
Douglas Gregor36897b02010-09-10 00:22:18 +00003322 case CXCursor_LabelRef:
3323 return getCursorLabelRef(C).second;
3324
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003325 case CXCursor_OverloadedDeclRef:
3326 return getCursorOverloadedDeclRef(C).second;
3327
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003328 default:
3329 // FIXME: Need a way to enumerate all non-reference cases.
3330 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003331 }
3332 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003333
3334 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003335 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003336
3337 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003338 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003339
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003340 if (C.kind == CXCursor_PreprocessingDirective)
3341 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003342
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003343 if (C.kind == CXCursor_MacroInstantiation)
3344 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003345
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003346 if (C.kind == CXCursor_MacroDefinition)
3347 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003348
3349 if (C.kind == CXCursor_InclusionDirective)
3350 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3351
Ted Kremenek007a7c92010-11-01 23:26:51 +00003352 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3353 Decl *D = cxcursor::getCursorDecl(C);
3354 SourceRange R = D->getSourceRange();
3355 // FIXME: Multiple variables declared in a single declaration
3356 // currently lack the information needed to correctly determine their
3357 // ranges when accounting for the type-specifier. We use context
3358 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3359 // and if so, whether it is the first decl.
3360 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3361 if (!cxcursor::isFirstInDeclGroup(C))
3362 R.setBegin(VD->getLocation());
3363 }
3364 return R;
3365 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003366 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003367
3368extern "C" {
3369
3370CXSourceRange clang_getCursorExtent(CXCursor C) {
3371 SourceRange R = getRawCursorExtent(C);
3372 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003373 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003374
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003375 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003376}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003377
3378CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003379 if (clang_isInvalid(C.kind))
3380 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003381
Ted Kremeneka60ed472010-11-16 08:15:36 +00003382 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003383 if (clang_isDeclaration(C.kind)) {
3384 Decl *D = getCursorDecl(C);
3385 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003386 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003387 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003388 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003389 if (ObjCForwardProtocolDecl *Protocols
3390 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003391 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003392 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3393 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3394 return MakeCXCursor(Property, tu);
3395
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003396 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003397 }
3398
Douglas Gregor97b98722010-01-19 23:20:36 +00003399 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003400 Expr *E = getCursorExpr(C);
3401 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003402 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003403 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003404
3405 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003406 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003407
Douglas Gregor97b98722010-01-19 23:20:36 +00003408 return clang_getNullCursor();
3409 }
3410
Douglas Gregor36897b02010-09-10 00:22:18 +00003411 if (clang_isStatement(C.kind)) {
3412 Stmt *S = getCursorStmt(C);
3413 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003414 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003415
3416 return clang_getNullCursor();
3417 }
3418
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003419 if (C.kind == CXCursor_MacroInstantiation) {
3420 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003421 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003422 }
3423
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003424 if (!clang_isReference(C.kind))
3425 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003426
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003427 switch (C.kind) {
3428 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003429 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003430
3431 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003432 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003433
3434 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003435 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003436
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003437 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003438 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003439
3440 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003441 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003442
Douglas Gregor69319002010-08-31 23:48:11 +00003443 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003444 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003445
Douglas Gregora67e03f2010-09-09 21:42:20 +00003446 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003447 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003448
Ted Kremenek3064ef92010-08-27 21:34:58 +00003449 case CXCursor_CXXBaseSpecifier: {
3450 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3451 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003452 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003453 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003454
Douglas Gregor36897b02010-09-10 00:22:18 +00003455 case CXCursor_LabelRef:
3456 // FIXME: We end up faking the "parent" declaration here because we
3457 // don't want to make CXCursor larger.
3458 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003459 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3460 .getTranslationUnitDecl(),
3461 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003462
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003463 case CXCursor_OverloadedDeclRef:
3464 return C;
3465
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003466 default:
3467 // We would prefer to enumerate all non-reference cursor kinds here.
3468 llvm_unreachable("Unhandled reference cursor kind");
3469 break;
3470 }
3471 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003472
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003473 return clang_getNullCursor();
3474}
3475
Douglas Gregorb6998662010-01-19 19:34:47 +00003476CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003477 if (clang_isInvalid(C.kind))
3478 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003479
Ted Kremeneka60ed472010-11-16 08:15:36 +00003480 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003481
Douglas Gregorb6998662010-01-19 19:34:47 +00003482 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003483 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003484 C = clang_getCursorReferenced(C);
3485 WasReference = true;
3486 }
3487
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003488 if (C.kind == CXCursor_MacroInstantiation)
3489 return clang_getCursorReferenced(C);
3490
Douglas Gregorb6998662010-01-19 19:34:47 +00003491 if (!clang_isDeclaration(C.kind))
3492 return clang_getNullCursor();
3493
3494 Decl *D = getCursorDecl(C);
3495 if (!D)
3496 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003497
Douglas Gregorb6998662010-01-19 19:34:47 +00003498 switch (D->getKind()) {
3499 // Declaration kinds that don't really separate the notions of
3500 // declaration and definition.
3501 case Decl::Namespace:
3502 case Decl::Typedef:
3503 case Decl::TemplateTypeParm:
3504 case Decl::EnumConstant:
3505 case Decl::Field:
3506 case Decl::ObjCIvar:
3507 case Decl::ObjCAtDefsField:
3508 case Decl::ImplicitParam:
3509 case Decl::ParmVar:
3510 case Decl::NonTypeTemplateParm:
3511 case Decl::TemplateTemplateParm:
3512 case Decl::ObjCCategoryImpl:
3513 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003514 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003515 case Decl::LinkageSpec:
3516 case Decl::ObjCPropertyImpl:
3517 case Decl::FileScopeAsm:
3518 case Decl::StaticAssert:
3519 case Decl::Block:
3520 return C;
3521
3522 // Declaration kinds that don't make any sense here, but are
3523 // nonetheless harmless.
3524 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003525 break;
3526
3527 // Declaration kinds for which the definition is not resolvable.
3528 case Decl::UnresolvedUsingTypename:
3529 case Decl::UnresolvedUsingValue:
3530 break;
3531
3532 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003533 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003534 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003535
3536 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003537 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003538
3539 case Decl::Enum:
3540 case Decl::Record:
3541 case Decl::CXXRecord:
3542 case Decl::ClassTemplateSpecialization:
3543 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003544 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003545 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003546 return clang_getNullCursor();
3547
3548 case Decl::Function:
3549 case Decl::CXXMethod:
3550 case Decl::CXXConstructor:
3551 case Decl::CXXDestructor:
3552 case Decl::CXXConversion: {
3553 const FunctionDecl *Def = 0;
3554 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003555 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003556 return clang_getNullCursor();
3557 }
3558
3559 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003560 // Ask the variable if it has a definition.
3561 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003562 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003563 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003564 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003565
Douglas Gregorb6998662010-01-19 19:34:47 +00003566 case Decl::FunctionTemplate: {
3567 const FunctionDecl *Def = 0;
3568 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003569 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003570 return clang_getNullCursor();
3571 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003572
Douglas Gregorb6998662010-01-19 19:34:47 +00003573 case Decl::ClassTemplate: {
3574 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003575 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003576 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003577 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 return clang_getNullCursor();
3579 }
3580
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003581 case Decl::Using:
3582 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003583 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003584
3585 case Decl::UsingShadow:
3586 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003587 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003588 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003589
3590 case Decl::ObjCMethod: {
3591 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3592 if (Method->isThisDeclarationADefinition())
3593 return C;
3594
3595 // Dig out the method definition in the associated
3596 // @implementation, if we have it.
3597 // FIXME: The ASTs should make finding the definition easier.
3598 if (ObjCInterfaceDecl *Class
3599 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3600 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3601 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3602 Method->isInstanceMethod()))
3603 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003604 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003605
3606 return clang_getNullCursor();
3607 }
3608
3609 case Decl::ObjCCategory:
3610 if (ObjCCategoryImplDecl *Impl
3611 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003612 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003613 return clang_getNullCursor();
3614
3615 case Decl::ObjCProtocol:
3616 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3617 return C;
3618 return clang_getNullCursor();
3619
3620 case Decl::ObjCInterface:
3621 // There are two notions of a "definition" for an Objective-C
3622 // class: the interface and its implementation. When we resolved a
3623 // reference to an Objective-C class, produce the @interface as
3624 // the definition; when we were provided with the interface,
3625 // produce the @implementation as the definition.
3626 if (WasReference) {
3627 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3628 return C;
3629 } else if (ObjCImplementationDecl *Impl
3630 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003631 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003632 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003633
Douglas Gregorb6998662010-01-19 19:34:47 +00003634 case Decl::ObjCProperty:
3635 // FIXME: We don't really know where to find the
3636 // ObjCPropertyImplDecls that implement this property.
3637 return clang_getNullCursor();
3638
3639 case Decl::ObjCCompatibleAlias:
3640 if (ObjCInterfaceDecl *Class
3641 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3642 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003643 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003644
Douglas Gregorb6998662010-01-19 19:34:47 +00003645 return clang_getNullCursor();
3646
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003647 case Decl::ObjCForwardProtocol:
3648 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003649 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003650
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003651 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003652 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003653 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003654
3655 case Decl::Friend:
3656 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003657 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003658 return clang_getNullCursor();
3659
3660 case Decl::FriendTemplate:
3661 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003662 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003663 return clang_getNullCursor();
3664 }
3665
3666 return clang_getNullCursor();
3667}
3668
3669unsigned clang_isCursorDefinition(CXCursor C) {
3670 if (!clang_isDeclaration(C.kind))
3671 return 0;
3672
3673 return clang_getCursorDefinition(C) == C;
3674}
3675
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003676unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003677 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003678 return 0;
3679
3680 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3681 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3682 return E->getNumDecls();
3683
3684 if (OverloadedTemplateStorage *S
3685 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3686 return S->size();
3687
3688 Decl *D = Storage.get<Decl*>();
3689 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003690 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003691 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3692 return Classes->size();
3693 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3694 return Protocols->protocol_size();
3695
3696 return 0;
3697}
3698
3699CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003700 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003701 return clang_getNullCursor();
3702
3703 if (index >= clang_getNumOverloadedDecls(cursor))
3704 return clang_getNullCursor();
3705
Ted Kremeneka60ed472010-11-16 08:15:36 +00003706 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003707 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3708 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003709 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003710
3711 if (OverloadedTemplateStorage *S
3712 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003713 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003714
3715 Decl *D = Storage.get<Decl*>();
3716 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3717 // FIXME: This is, unfortunately, linear time.
3718 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3719 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003720 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003721 }
3722
3723 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003724 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003725
3726 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003727 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003728
3729 return clang_getNullCursor();
3730}
3731
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003732void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003733 const char **startBuf,
3734 const char **endBuf,
3735 unsigned *startLine,
3736 unsigned *startColumn,
3737 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003738 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003739 assert(getCursorDecl(C) && "CXCursor has null decl");
3740 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003741 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3742 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003743
Steve Naroff4ade6d62009-09-23 17:52:52 +00003744 SourceManager &SM = FD->getASTContext().getSourceManager();
3745 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3746 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3747 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3748 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3749 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3750 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3751}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003752
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003753void clang_enableStackTraces(void) {
3754 llvm::sys::PrintStackTraceOnErrorSignal();
3755}
3756
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003757void clang_executeOnThread(void (*fn)(void*), void *user_data,
3758 unsigned stack_size) {
3759 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3760}
3761
Ted Kremenekfb480492010-01-13 21:46:36 +00003762} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003763
Ted Kremenekfb480492010-01-13 21:46:36 +00003764//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003765// Token-based Operations.
3766//===----------------------------------------------------------------------===//
3767
3768/* CXToken layout:
3769 * int_data[0]: a CXTokenKind
3770 * int_data[1]: starting token location
3771 * int_data[2]: token length
3772 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003773 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003774 * otherwise unused.
3775 */
3776extern "C" {
3777
3778CXTokenKind clang_getTokenKind(CXToken CXTok) {
3779 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3780}
3781
3782CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3783 switch (clang_getTokenKind(CXTok)) {
3784 case CXToken_Identifier:
3785 case CXToken_Keyword:
3786 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003787 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3788 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003789
3790 case CXToken_Literal: {
3791 // We have stashed the starting pointer in the ptr_data field. Use it.
3792 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003793 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003794 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003795
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003796 case CXToken_Punctuation:
3797 case CXToken_Comment:
3798 break;
3799 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003800
3801 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003803 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003804 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003805 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3808 std::pair<FileID, unsigned> LocInfo
3809 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003810 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003811 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003812 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3813 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003814 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003815
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003816 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003817}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003818
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003819CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003820 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003821 if (!CXXUnit)
3822 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003823
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003824 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3825 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3826}
3827
3828CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003829 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003830 if (!CXXUnit)
3831 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832
3833 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3835}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3838 CXToken **Tokens, unsigned *NumTokens) {
3839 if (Tokens)
3840 *Tokens = 0;
3841 if (NumTokens)
3842 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
Ted Kremeneka60ed472010-11-16 08:15:36 +00003844 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003845 if (!CXXUnit || !Tokens || !NumTokens)
3846 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
Douglas Gregorbdf60622010-03-05 21:16:25 +00003848 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3849
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003850 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003851 if (R.isInvalid())
3852 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003853
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003854 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3855 std::pair<FileID, unsigned> BeginLocInfo
3856 = SourceMgr.getDecomposedLoc(R.getBegin());
3857 std::pair<FileID, unsigned> EndLocInfo
3858 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003860 // Cannot tokenize across files.
3861 if (BeginLocInfo.first != EndLocInfo.first)
3862 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
3864 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003865 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003866 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003867 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003868 if (Invalid)
3869 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003870
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003871 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3872 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003873 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003875
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003876 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003877 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 llvm::SmallVector<CXToken, 32> CXTokens;
3879 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003880 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003881 do {
3882 // Lex the next token
3883 Lex.LexFromRawLexer(Tok);
3884 if (Tok.is(tok::eof))
3885 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003886
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003887 // Initialize the CXToken.
3888 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003889
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 // - Common fields
3891 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3892 CXTok.int_data[2] = Tok.getLength();
3893 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895 // - Kind-specific fields
3896 if (Tok.isLiteral()) {
3897 CXTok.int_data[0] = CXToken_Literal;
3898 CXTok.ptr_data = (void *)Tok.getLiteralData();
3899 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003900 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003901 std::pair<FileID, unsigned> LocInfo
3902 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003903 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003904 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003905 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3906 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003907 return;
3908
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003909 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003910 IdentifierInfo *II
3911 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003912
David Chisnall096428b2010-10-13 21:44:48 +00003913 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003914 CXTok.int_data[0] = CXToken_Keyword;
3915 }
3916 else {
3917 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3918 CXToken_Identifier
3919 : CXToken_Keyword;
3920 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003921 CXTok.ptr_data = II;
3922 } else if (Tok.is(tok::comment)) {
3923 CXTok.int_data[0] = CXToken_Comment;
3924 CXTok.ptr_data = 0;
3925 } else {
3926 CXTok.int_data[0] = CXToken_Punctuation;
3927 CXTok.ptr_data = 0;
3928 }
3929 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003930 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003931 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003932
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003933 if (CXTokens.empty())
3934 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003935
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003936 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3937 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3938 *NumTokens = CXTokens.size();
3939}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003940
Ted Kremenek6db61092010-05-05 00:55:15 +00003941void clang_disposeTokens(CXTranslationUnit TU,
3942 CXToken *Tokens, unsigned NumTokens) {
3943 free(Tokens);
3944}
3945
3946} // end: extern "C"
3947
3948//===----------------------------------------------------------------------===//
3949// Token annotation APIs.
3950//===----------------------------------------------------------------------===//
3951
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003952typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003953static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3954 CXCursor parent,
3955 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003956namespace {
3957class AnnotateTokensWorker {
3958 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003959 CXToken *Tokens;
3960 CXCursor *Cursors;
3961 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003962 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003963 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003964 CursorVisitor AnnotateVis;
3965 SourceManager &SrcMgr;
3966
3967 bool MoreTokens() const { return TokIdx < NumTokens; }
3968 unsigned NextToken() const { return TokIdx; }
3969 void AdvanceToken() { ++TokIdx; }
3970 SourceLocation GetTokenLoc(unsigned tokI) {
3971 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3972 }
3973
Ted Kremenek6db61092010-05-05 00:55:15 +00003974public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003975 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003976 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003977 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003978 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003979 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003980 AnnotateVis(tu,
3981 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003982 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003983 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003984
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003985 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003986 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003987 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003988 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003989 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00003990 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003991};
3992}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003993
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003994void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3995 // Walk the AST within the region of interest, annotating tokens
3996 // along the way.
3997 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003998
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003999 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4000 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004001 if (Pos != Annotated.end() &&
4002 (clang_isInvalid(Cursors[I].kind) ||
4003 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004 Cursors[I] = Pos->second;
4005 }
4006
4007 // Finish up annotating any tokens left.
4008 if (!MoreTokens())
4009 return;
4010
4011 const CXCursor &C = clang_getNullCursor();
4012 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4013 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4014 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004015 }
4016}
4017
Ted Kremenek6db61092010-05-05 00:55:15 +00004018enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004019AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004020 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004021 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004022 if (cursorRange.isInvalid())
4023 return CXChildVisit_Recurse;
4024
Douglas Gregor4419b672010-10-21 06:10:04 +00004025 if (clang_isPreprocessing(cursor.kind)) {
4026 // For macro instantiations, just note where the beginning of the macro
4027 // instantiation occurs.
4028 if (cursor.kind == CXCursor_MacroInstantiation) {
4029 Annotated[Loc.int_data] = cursor;
4030 return CXChildVisit_Recurse;
4031 }
4032
Douglas Gregor4419b672010-10-21 06:10:04 +00004033 // Items in the preprocessing record are kept separate from items in
4034 // declarations, so we keep a separate token index.
4035 unsigned SavedTokIdx = TokIdx;
4036 TokIdx = PreprocessingTokIdx;
4037
4038 // Skip tokens up until we catch up to the beginning of the preprocessing
4039 // entry.
4040 while (MoreTokens()) {
4041 const unsigned I = NextToken();
4042 SourceLocation TokLoc = GetTokenLoc(I);
4043 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4044 case RangeBefore:
4045 AdvanceToken();
4046 continue;
4047 case RangeAfter:
4048 case RangeOverlap:
4049 break;
4050 }
4051 break;
4052 }
4053
4054 // Look at all of the tokens within this range.
4055 while (MoreTokens()) {
4056 const unsigned I = NextToken();
4057 SourceLocation TokLoc = GetTokenLoc(I);
4058 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4059 case RangeBefore:
4060 assert(0 && "Infeasible");
4061 case RangeAfter:
4062 break;
4063 case RangeOverlap:
4064 Cursors[I] = cursor;
4065 AdvanceToken();
4066 continue;
4067 }
4068 break;
4069 }
4070
4071 // Save the preprocessing token index; restore the non-preprocessing
4072 // token index.
4073 PreprocessingTokIdx = TokIdx;
4074 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004075 return CXChildVisit_Recurse;
4076 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004077
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004078 if (cursorRange.isInvalid())
4079 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004080
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004081 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4082
Ted Kremeneka333c662010-05-12 05:29:33 +00004083 // Adjust the annotated range based specific declarations.
4084 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4085 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004086 Decl *D = cxcursor::getCursorDecl(cursor);
4087 // Don't visit synthesized ObjC methods, since they have no syntatic
4088 // representation in the source.
4089 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4090 if (MD->isSynthesized())
4091 return CXChildVisit_Continue;
4092 }
4093 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004094 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4095 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004096 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004097 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004098 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004099 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004100 }
4101 }
4102 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004103
Ted Kremenek3f404602010-08-14 01:14:06 +00004104 // If the location of the cursor occurs within a macro instantiation, record
4105 // the spelling location of the cursor in our annotation map. We can then
4106 // paper over the token labelings during a post-processing step to try and
4107 // get cursor mappings for tokens that are the *arguments* of a macro
4108 // instantiation.
4109 if (L.isMacroID()) {
4110 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4111 // Only invalidate the old annotation if it isn't part of a preprocessing
4112 // directive. Here we assume that the default construction of CXCursor
4113 // results in CXCursor.kind being an initialized value (i.e., 0). If
4114 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004115
Ted Kremenek3f404602010-08-14 01:14:06 +00004116 CXCursor &oldC = Annotated[rawEncoding];
4117 if (!clang_isPreprocessing(oldC.kind))
4118 oldC = cursor;
4119 }
4120
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004121 const enum CXCursorKind K = clang_getCursorKind(parent);
4122 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004123 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4124 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004125
4126 while (MoreTokens()) {
4127 const unsigned I = NextToken();
4128 SourceLocation TokLoc = GetTokenLoc(I);
4129 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4130 case RangeBefore:
4131 Cursors[I] = updateC;
4132 AdvanceToken();
4133 continue;
4134 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004135 case RangeOverlap:
4136 break;
4137 }
4138 break;
4139 }
4140
4141 // Visit children to get their cursor information.
4142 const unsigned BeforeChildren = NextToken();
4143 VisitChildren(cursor);
4144 const unsigned AfterChildren = NextToken();
4145
4146 // Adjust 'Last' to the last token within the extent of the cursor.
4147 while (MoreTokens()) {
4148 const unsigned I = NextToken();
4149 SourceLocation TokLoc = GetTokenLoc(I);
4150 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4151 case RangeBefore:
4152 assert(0 && "Infeasible");
4153 case RangeAfter:
4154 break;
4155 case RangeOverlap:
4156 Cursors[I] = updateC;
4157 AdvanceToken();
4158 continue;
4159 }
4160 break;
4161 }
4162 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004163
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004164 // Scan the tokens that are at the beginning of the cursor, but are not
4165 // capture by the child cursors.
4166
4167 // For AST elements within macros, rely on a post-annotate pass to
4168 // to correctly annotate the tokens with cursors. Otherwise we can
4169 // get confusing results of having tokens that map to cursors that really
4170 // are expanded by an instantiation.
4171 if (L.isMacroID())
4172 cursor = clang_getNullCursor();
4173
4174 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4175 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4176 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004177
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004178 Cursors[I] = cursor;
4179 }
4180 // Scan the tokens that are at the end of the cursor, but are not captured
4181 // but the child cursors.
4182 for (unsigned I = AfterChildren; I != Last; ++I)
4183 Cursors[I] = cursor;
4184
4185 TokIdx = Last;
4186 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004187}
4188
Ted Kremenek6db61092010-05-05 00:55:15 +00004189static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4190 CXCursor parent,
4191 CXClientData client_data) {
4192 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4193}
4194
Ted Kremenekab979612010-11-11 08:05:23 +00004195// This gets run a separate thread to avoid stack blowout.
4196static void runAnnotateTokensWorker(void *UserData) {
4197 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4198}
4199
Ted Kremenek6db61092010-05-05 00:55:15 +00004200extern "C" {
4201
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004202void clang_annotateTokens(CXTranslationUnit TU,
4203 CXToken *Tokens, unsigned NumTokens,
4204 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004205
4206 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004207 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004208
Douglas Gregor4419b672010-10-21 06:10:04 +00004209 // Any token we don't specifically annotate will have a NULL cursor.
4210 CXCursor C = clang_getNullCursor();
4211 for (unsigned I = 0; I != NumTokens; ++I)
4212 Cursors[I] = C;
4213
Ted Kremeneka60ed472010-11-16 08:15:36 +00004214 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004215 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004216 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004217
Douglas Gregorbdf60622010-03-05 21:16:25 +00004218 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004219
Douglas Gregor0396f462010-03-19 05:22:59 +00004220 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004221 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004222 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4223 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004224 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4225 clang_getTokenLocation(TU,
4226 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227
Douglas Gregor0396f462010-03-19 05:22:59 +00004228 // A mapping from the source locations found when re-lexing or traversing the
4229 // region of interest to the corresponding cursors.
4230 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004231
4232 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004233 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004234 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4235 std::pair<FileID, unsigned> BeginLocInfo
4236 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4237 std::pair<FileID, unsigned> EndLocInfo
4238 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004240 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004241 bool Invalid = false;
4242 if (BeginLocInfo.first == EndLocInfo.first &&
4243 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4244 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4246 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004247 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004248 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004249 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004250
4251 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004252 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004253 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004254 Token Tok;
4255 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004256
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004257 reprocess:
4258 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4259 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004260 // don't see it while preprocessing these tokens later, but keep track
4261 // of all of the token locations inside this preprocessing directive so
4262 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004263 //
4264 // FIXME: Some simple tests here could identify macro definitions and
4265 // #undefs, to provide specific cursor kinds for those.
4266 std::vector<SourceLocation> Locations;
4267 do {
4268 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004269 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004270 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004271
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004272 using namespace cxcursor;
4273 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004274 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4275 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004276 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004277 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4278 Annotated[Locations[I].getRawEncoding()] = Cursor;
4279 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004280
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004281 if (Tok.isAtStartOfLine())
4282 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004283
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004284 continue;
4285 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004286
Douglas Gregor48072312010-03-18 15:23:44 +00004287 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004288 break;
4289 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004290 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004291
Douglas Gregor0396f462010-03-19 05:22:59 +00004292 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004293 // a specific cursor.
4294 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004295 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004296
4297 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004298 // FIXME: We use a ridiculous stack size here because the data-recursion
4299 // algorithm uses a large stack frame than the non-data recursive version,
4300 // and AnnotationTokensWorker currently transforms the data-recursion
4301 // algorithm back into a traditional recursion by explicitly calling
4302 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004303 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004304 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4305 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004306 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4307 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004308}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004309} // end: extern "C"
4310
4311//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004312// Operations for querying linkage of a cursor.
4313//===----------------------------------------------------------------------===//
4314
4315extern "C" {
4316CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004317 if (!clang_isDeclaration(cursor.kind))
4318 return CXLinkage_Invalid;
4319
Ted Kremenek16b42592010-03-03 06:36:57 +00004320 Decl *D = cxcursor::getCursorDecl(cursor);
4321 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4322 switch (ND->getLinkage()) {
4323 case NoLinkage: return CXLinkage_NoLinkage;
4324 case InternalLinkage: return CXLinkage_Internal;
4325 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4326 case ExternalLinkage: return CXLinkage_External;
4327 };
4328
4329 return CXLinkage_Invalid;
4330}
4331} // end: extern "C"
4332
4333//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004334// Operations for querying language of a cursor.
4335//===----------------------------------------------------------------------===//
4336
4337static CXLanguageKind getDeclLanguage(const Decl *D) {
4338 switch (D->getKind()) {
4339 default:
4340 break;
4341 case Decl::ImplicitParam:
4342 case Decl::ObjCAtDefsField:
4343 case Decl::ObjCCategory:
4344 case Decl::ObjCCategoryImpl:
4345 case Decl::ObjCClass:
4346 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004347 case Decl::ObjCForwardProtocol:
4348 case Decl::ObjCImplementation:
4349 case Decl::ObjCInterface:
4350 case Decl::ObjCIvar:
4351 case Decl::ObjCMethod:
4352 case Decl::ObjCProperty:
4353 case Decl::ObjCPropertyImpl:
4354 case Decl::ObjCProtocol:
4355 return CXLanguage_ObjC;
4356 case Decl::CXXConstructor:
4357 case Decl::CXXConversion:
4358 case Decl::CXXDestructor:
4359 case Decl::CXXMethod:
4360 case Decl::CXXRecord:
4361 case Decl::ClassTemplate:
4362 case Decl::ClassTemplatePartialSpecialization:
4363 case Decl::ClassTemplateSpecialization:
4364 case Decl::Friend:
4365 case Decl::FriendTemplate:
4366 case Decl::FunctionTemplate:
4367 case Decl::LinkageSpec:
4368 case Decl::Namespace:
4369 case Decl::NamespaceAlias:
4370 case Decl::NonTypeTemplateParm:
4371 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004372 case Decl::TemplateTemplateParm:
4373 case Decl::TemplateTypeParm:
4374 case Decl::UnresolvedUsingTypename:
4375 case Decl::UnresolvedUsingValue:
4376 case Decl::Using:
4377 case Decl::UsingDirective:
4378 case Decl::UsingShadow:
4379 return CXLanguage_CPlusPlus;
4380 }
4381
4382 return CXLanguage_C;
4383}
4384
4385extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004386
4387enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4388 if (clang_isDeclaration(cursor.kind))
4389 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4390 if (D->hasAttr<UnavailableAttr>() ||
4391 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4392 return CXAvailability_Available;
4393
4394 if (D->hasAttr<DeprecatedAttr>())
4395 return CXAvailability_Deprecated;
4396 }
4397
4398 return CXAvailability_Available;
4399}
4400
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004401CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4402 if (clang_isDeclaration(cursor.kind))
4403 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4404
4405 return CXLanguage_Invalid;
4406}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004407
4408CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4409 if (clang_isDeclaration(cursor.kind)) {
4410 if (Decl *D = getCursorDecl(cursor)) {
4411 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004412 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004413 }
4414 }
4415
4416 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4417 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004418 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004419 }
4420
4421 return clang_getNullCursor();
4422}
4423
4424CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4425 if (clang_isDeclaration(cursor.kind)) {
4426 if (Decl *D = getCursorDecl(cursor)) {
4427 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004428 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004429 }
4430 }
4431
4432 // FIXME: Note that we can't easily compute the lexical context of a
4433 // statement or expression, so we return nothing.
4434 return clang_getNullCursor();
4435}
4436
Douglas Gregor9f592342010-10-01 20:25:15 +00004437static void CollectOverriddenMethods(DeclContext *Ctx,
4438 ObjCMethodDecl *Method,
4439 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4440 if (!Ctx)
4441 return;
4442
4443 // If we have a class or category implementation, jump straight to the
4444 // interface.
4445 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4446 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4447
4448 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4449 if (!Container)
4450 return;
4451
4452 // Check whether we have a matching method at this level.
4453 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4454 Method->isInstanceMethod()))
4455 if (Method != Overridden) {
4456 // We found an override at this level; there is no need to look
4457 // into other protocols or categories.
4458 Methods.push_back(Overridden);
4459 return;
4460 }
4461
4462 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4463 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4464 PEnd = Protocol->protocol_end();
4465 P != PEnd; ++P)
4466 CollectOverriddenMethods(*P, Method, Methods);
4467 }
4468
4469 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4470 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4471 PEnd = Category->protocol_end();
4472 P != PEnd; ++P)
4473 CollectOverriddenMethods(*P, Method, Methods);
4474 }
4475
4476 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4477 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4478 PEnd = Interface->protocol_end();
4479 P != PEnd; ++P)
4480 CollectOverriddenMethods(*P, Method, Methods);
4481
4482 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4483 Category; Category = Category->getNextClassCategory())
4484 CollectOverriddenMethods(Category, Method, Methods);
4485
4486 // We only look into the superclass if we haven't found anything yet.
4487 if (Methods.empty())
4488 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4489 return CollectOverriddenMethods(Super, Method, Methods);
4490 }
4491}
4492
4493void clang_getOverriddenCursors(CXCursor cursor,
4494 CXCursor **overridden,
4495 unsigned *num_overridden) {
4496 if (overridden)
4497 *overridden = 0;
4498 if (num_overridden)
4499 *num_overridden = 0;
4500 if (!overridden || !num_overridden)
4501 return;
4502
4503 if (!clang_isDeclaration(cursor.kind))
4504 return;
4505
4506 Decl *D = getCursorDecl(cursor);
4507 if (!D)
4508 return;
4509
4510 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004511 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004512 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4513 *num_overridden = CXXMethod->size_overridden_methods();
4514 if (!*num_overridden)
4515 return;
4516
4517 *overridden = new CXCursor [*num_overridden];
4518 unsigned I = 0;
4519 for (CXXMethodDecl::method_iterator
4520 M = CXXMethod->begin_overridden_methods(),
4521 MEnd = CXXMethod->end_overridden_methods();
4522 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004523 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004524 return;
4525 }
4526
4527 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4528 if (!Method)
4529 return;
4530
4531 // Handle Objective-C methods.
4532 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4533 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4534
4535 if (Methods.empty())
4536 return;
4537
4538 *num_overridden = Methods.size();
4539 *overridden = new CXCursor [Methods.size()];
4540 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004541 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004542}
4543
4544void clang_disposeOverriddenCursors(CXCursor *overridden) {
4545 delete [] overridden;
4546}
4547
Douglas Gregorecdcb882010-10-20 22:00:55 +00004548CXFile clang_getIncludedFile(CXCursor cursor) {
4549 if (cursor.kind != CXCursor_InclusionDirective)
4550 return 0;
4551
4552 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4553 return (void *)ID->getFile();
4554}
4555
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004556} // end: extern "C"
4557
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004558
4559//===----------------------------------------------------------------------===//
4560// C++ AST instrospection.
4561//===----------------------------------------------------------------------===//
4562
4563extern "C" {
4564unsigned clang_CXXMethod_isStatic(CXCursor C) {
4565 if (!clang_isDeclaration(C.kind))
4566 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004567
4568 CXXMethodDecl *Method = 0;
4569 Decl *D = cxcursor::getCursorDecl(C);
4570 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4571 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4572 else
4573 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4574 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004575}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004576
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004577} // end: extern "C"
4578
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004579//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004580// Attribute introspection.
4581//===----------------------------------------------------------------------===//
4582
4583extern "C" {
4584CXType clang_getIBOutletCollectionType(CXCursor C) {
4585 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004586 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004587
4588 IBOutletCollectionAttr *A =
4589 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4590
Ted Kremeneka60ed472010-11-16 08:15:36 +00004591 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004592}
4593} // end: extern "C"
4594
4595//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004596// Misc. utility functions.
4597//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004598
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004599/// Default to using an 8 MB stack size on "safety" threads.
4600static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004601
4602namespace clang {
4603
4604bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004605 void (*Fn)(void*), void *UserData,
4606 unsigned Size) {
4607 if (!Size)
4608 Size = GetSafetyThreadStackSize();
4609 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004610 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4611 return CRC.RunSafely(Fn, UserData);
4612}
4613
4614unsigned GetSafetyThreadStackSize() {
4615 return SafetyStackThreadSize;
4616}
4617
4618void SetSafetyThreadStackSize(unsigned Value) {
4619 SafetyStackThreadSize = Value;
4620}
4621
4622}
4623
Ted Kremenek04bb7162010-01-22 22:44:15 +00004624extern "C" {
4625
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004626CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004627 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004628}
4629
4630} // end: extern "C"