blob: 3b17414052f51953191db64160c6a83d30261b5b [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);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000296 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000297 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000298 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000299 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000300 bool VisitUsingDecl(UsingDecl *D);
301 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
302 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000303
Douglas Gregor01829d32010-08-31 14:41:23 +0000304 // Name visitor
305 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000306 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000307
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000308 // Template visitors
309 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000310 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000311 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
312
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000313 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000314 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000315 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000316 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000317 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
318 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000319 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000320 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000321 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
323 bool VisitPointerTypeLoc(PointerTypeLoc TL);
324 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
325 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
326 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
327 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000328 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000329 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000330 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000331 // FIXME: Implement visitors here when the unimplemented TypeLocs get
332 // implemented
333 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
334 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000335
Douglas Gregora59e3902010-01-21 23:27:09 +0000336 // Statement visitors
337 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000338
Douglas Gregor336fd812010-01-23 00:40:08 +0000339 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000340 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000341 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000342 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000343 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000344 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000345 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000346 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000347 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000348 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000349
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000350 // Data-recursive visitor functions.
351 bool IsInRegionOfInterest(CXCursor C);
352 bool RunVisitorWorkList(VisitorWorkList &WL);
353 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Benjamin Kramere645c722010-11-16 15:45:46 +0000354 LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000355};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000356
Ted Kremenekab188932010-01-05 19:32:54 +0000357} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000358
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000359static SourceRange getRawCursorExtent(CXCursor C);
360
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000362 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000363}
364
Douglas Gregorb1373d02010-01-20 20:59:29 +0000365/// \brief Visit the given cursor and, if requested by the visitor,
366/// its children.
367///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368/// \param Cursor the cursor to visit.
369///
370/// \param CheckRegionOfInterest if true, then the caller already checked that
371/// this cursor is within the region of interest.
372///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373/// \returns true if the visitation should be aborted, false if it
374/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000375bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 if (clang_isInvalid(Cursor.kind))
377 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000378
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379 if (clang_isDeclaration(Cursor.kind)) {
380 Decl *D = getCursorDecl(Cursor);
381 assert(D && "Invalid declaration cursor");
382 if (D->getPCHLevel() > MaxPCHLevel)
383 return false;
384
385 if (D->isImplicit())
386 return false;
387 }
388
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000389 // If we have a range of interest, and this cursor doesn't intersect with it,
390 // we're done.
391 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000392 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000393 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000394 return false;
395 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000396
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397 switch (Visitor(Cursor, Parent, ClientData)) {
398 case CXChildVisit_Break:
399 return true;
400
401 case CXChildVisit_Continue:
402 return false;
403
404 case CXChildVisit_Recurse:
405 return VisitChildren(Cursor);
406 }
407
Douglas Gregorfd643772010-01-25 16:45:46 +0000408 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000409}
410
Douglas Gregor788f5a12010-03-20 00:41:21 +0000411std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
412CursorVisitor::getPreprocessedEntities() {
413 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000414 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000415
416 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000417 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000418
419 // There is no region of interest; we have to walk everything.
420 if (RegionOfInterest.isInvalid())
421 return std::make_pair(PPRec.begin(OnlyLocalDecls),
422 PPRec.end(OnlyLocalDecls));
423
424 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000425 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000426 std::pair<FileID, unsigned> Begin
427 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
428 std::pair<FileID, unsigned> End
429 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
430
431 // The region of interest spans files; we have to walk everything.
432 if (Begin.first != End.first)
433 return std::make_pair(PPRec.begin(OnlyLocalDecls),
434 PPRec.end(OnlyLocalDecls));
435
436 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000437 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000438 if (ByFileMap.empty()) {
439 // Build the mapping from files to sets of preprocessed entities.
440 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
441 EEnd = PPRec.end(OnlyLocalDecls);
442 E != EEnd; ++E) {
443 std::pair<FileID, unsigned> P
444 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
445 ByFileMap[P.first].push_back(*E);
446 }
447 }
448
449 return std::make_pair(ByFileMap[Begin.first].begin(),
450 ByFileMap[Begin.first].end());
451}
452
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000454///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455/// \returns true if the visitation should be aborted, false if it
456/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000458 if (clang_isReference(Cursor.kind)) {
459 // By definition, references have no children.
460 return false;
461 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000462
463 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000464 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000465 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467 if (clang_isDeclaration(Cursor.kind)) {
468 Decl *D = getCursorDecl(Cursor);
469 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000470 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472
Douglas Gregora59e3902010-01-21 23:27:09 +0000473 if (clang_isStatement(Cursor.kind))
474 return Visit(getCursorStmt(Cursor));
475 if (clang_isExpression(Cursor.kind))
476 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000477
Douglas Gregorb1373d02010-01-20 20:59:29 +0000478 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000479 CXTranslationUnit tu = getCursorTU(Cursor);
480 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000481 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
482 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000483 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
484 TLEnd = CXXUnit->top_level_end();
485 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000486 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000487 return true;
488 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000489 } else if (VisitDeclContext(
490 CXXUnit->getASTContext().getTranslationUnitDecl()))
491 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000492
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000494 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 // FIXME: Once we have the ability to deserialize a preprocessing record,
496 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000497 PreprocessingRecord::iterator E, EEnd;
498 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000499 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000500 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000502
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 continue;
504 }
505
506 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000507 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 return true;
509
510 continue;
511 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000512
513 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000514 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000515 return true;
516
517 continue;
518 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000519 }
520 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000521 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000523
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 return false;
526}
527
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000529 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
530 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000531
Ted Kremenek664cffd2010-07-22 11:30:19 +0000532 if (Stmt *Body = B->getBody())
533 return Visit(MakeCXCursor(Body, StmtParent, TU));
534
535 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000536}
537
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000538llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
539 if (RegionOfInterest.isValid()) {
540 SourceRange Range = getRawCursorExtent(Cursor);
541 if (Range.isInvalid())
542 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000543
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000544 switch (CompareRegionOfInterest(Range)) {
545 case RangeBefore:
546 // This declaration comes before the region of interest; skip it.
547 return llvm::Optional<bool>();
548
549 case RangeAfter:
550 // This declaration comes after the region of interest; we're done.
551 return false;
552
553 case RangeOverlap:
554 // This declaration overlaps the region of interest; visit it.
555 break;
556 }
557 }
558 return true;
559}
560
561bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
562 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
563
564 // FIXME: Eventually remove. This part of a hack to support proper
565 // iteration over all Decls contained lexically within an ObjC container.
566 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
567 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
568
569 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000570 Decl *D = *I;
571 if (D->getLexicalDeclContext() != DC)
572 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000573 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000574 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
575 if (!V.hasValue())
576 continue;
577 if (!V.getValue())
578 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000579 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000580 return true;
581 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000583}
584
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000585bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
586 llvm_unreachable("Translation units are visited directly by Visit()");
587 return false;
588}
589
590bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
591 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
592 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000594 return false;
595}
596
597bool CursorVisitor::VisitTagDecl(TagDecl *D) {
598 return VisitDeclContext(D);
599}
600
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000601bool CursorVisitor::VisitClassTemplateSpecializationDecl(
602 ClassTemplateSpecializationDecl *D) {
603 bool ShouldVisitBody = false;
604 switch (D->getSpecializationKind()) {
605 case TSK_Undeclared:
606 case TSK_ImplicitInstantiation:
607 // Nothing to visit
608 return false;
609
610 case TSK_ExplicitInstantiationDeclaration:
611 case TSK_ExplicitInstantiationDefinition:
612 break;
613
614 case TSK_ExplicitSpecialization:
615 ShouldVisitBody = true;
616 break;
617 }
618
619 // Visit the template arguments used in the specialization.
620 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
621 TypeLoc TL = SpecType->getTypeLoc();
622 if (TemplateSpecializationTypeLoc *TSTLoc
623 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
624 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
625 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
626 return true;
627 }
628 }
629
630 if (ShouldVisitBody && VisitCXXRecordDecl(D))
631 return true;
632
633 return false;
634}
635
Douglas Gregor74dbe642010-08-31 19:31:58 +0000636bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
637 ClassTemplatePartialSpecializationDecl *D) {
638 // FIXME: Visit the "outer" template parameter lists on the TagDecl
639 // before visiting these template parameters.
640 if (VisitTemplateParameters(D->getTemplateParameters()))
641 return true;
642
643 // Visit the partial specialization arguments.
644 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
645 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
646 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
647 return true;
648
649 return VisitCXXRecordDecl(D);
650}
651
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000652bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000653 // Visit the default argument.
654 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
655 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
656 if (Visit(DefArg->getTypeLoc()))
657 return true;
658
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000659 return false;
660}
661
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000662bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
663 if (Expr *Init = D->getInitExpr())
664 return Visit(MakeCXCursor(Init, StmtParent, TU));
665 return false;
666}
667
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000668bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
669 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
670 if (Visit(TSInfo->getTypeLoc()))
671 return true;
672
673 return false;
674}
675
Douglas Gregora67e03f2010-09-09 21:42:20 +0000676/// \brief Compare two base or member initializers based on their source order.
677static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
678 CXXBaseOrMemberInitializer const * const *X
679 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
680 CXXBaseOrMemberInitializer const * const *Y
681 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
682
683 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
684 return -1;
685 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
686 return 1;
687 else
688 return 0;
689}
690
Douglas Gregorb1373d02010-01-20 20:59:29 +0000691bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000692 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
693 // Visit the function declaration's syntactic components in the order
694 // written. This requires a bit of work.
695 TypeLoc TL = TSInfo->getTypeLoc();
696 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
697
698 // If we have a function declared directly (without the use of a typedef),
699 // visit just the return type. Otherwise, just visit the function's type
700 // now.
701 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
702 (!FTL && Visit(TL)))
703 return true;
704
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000705 // Visit the nested-name-specifier, if present.
706 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
707 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
708 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000709
710 // Visit the declaration name.
711 if (VisitDeclarationNameInfo(ND->getNameInfo()))
712 return true;
713
714 // FIXME: Visit explicitly-specified template arguments!
715
716 // Visit the function parameters, if we have a function type.
717 if (FTL && VisitFunctionTypeLoc(*FTL, true))
718 return true;
719
720 // FIXME: Attributes?
721 }
722
Douglas Gregora67e03f2010-09-09 21:42:20 +0000723 if (ND->isThisDeclarationADefinition()) {
724 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
725 // Find the initializers that were written in the source.
726 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
727 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
728 IEnd = Constructor->init_end();
729 I != IEnd; ++I) {
730 if (!(*I)->isWritten())
731 continue;
732
733 WrittenInits.push_back(*I);
734 }
735
736 // Sort the initializers in source order
737 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
738 &CompareCXXBaseOrMemberInitializers);
739
740 // Visit the initializers in source order
741 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
742 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
743 if (Init->isMemberInitializer()) {
744 if (Visit(MakeCursorMemberRef(Init->getMember(),
745 Init->getMemberLocation(), TU)))
746 return true;
747 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
748 if (Visit(BaseInfo->getTypeLoc()))
749 return true;
750 }
751
752 // Visit the initializer value.
753 if (Expr *Initializer = Init->getInit())
754 if (Visit(MakeCXCursor(Initializer, ND, TU)))
755 return true;
756 }
757 }
758
759 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
760 return true;
761 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000762
Douglas Gregorb1373d02010-01-20 20:59:29 +0000763 return false;
764}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000765
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000766bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
767 if (VisitDeclaratorDecl(D))
768 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770 if (Expr *BitWidth = D->getBitWidth())
771 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000772
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000773 return false;
774}
775
776bool CursorVisitor::VisitVarDecl(VarDecl *D) {
777 if (VisitDeclaratorDecl(D))
778 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780 if (Expr *Init = D->getInit())
781 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000783 return false;
784}
785
Douglas Gregor84b51d72010-09-01 20:16:53 +0000786bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
787 if (VisitDeclaratorDecl(D))
788 return true;
789
790 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
791 if (Expr *DefArg = D->getDefaultArgument())
792 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
793
794 return false;
795}
796
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000797bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
798 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
799 // before visiting these template parameters.
800 if (VisitTemplateParameters(D->getTemplateParameters()))
801 return true;
802
803 return VisitFunctionDecl(D->getTemplatedDecl());
804}
805
Douglas Gregor39d6f072010-08-31 19:02:00 +0000806bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
807 // FIXME: Visit the "outer" template parameter lists on the TagDecl
808 // before visiting these template parameters.
809 if (VisitTemplateParameters(D->getTemplateParameters()))
810 return true;
811
812 return VisitCXXRecordDecl(D->getTemplatedDecl());
813}
814
Douglas Gregor84b51d72010-09-01 20:16:53 +0000815bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
816 if (VisitTemplateParameters(D->getTemplateParameters()))
817 return true;
818
819 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
820 VisitTemplateArgumentLoc(D->getDefaultArgument()))
821 return true;
822
823 return false;
824}
825
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000826bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000827 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
828 if (Visit(TSInfo->getTypeLoc()))
829 return true;
830
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832 PEnd = ND->param_end();
833 P != PEnd; ++P) {
834 if (Visit(MakeCXCursor(*P, TU)))
835 return true;
836 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000837
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000838 if (ND->isThisDeclarationADefinition() &&
839 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
840 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 return false;
843}
844
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000845namespace {
846 struct ContainerDeclsSort {
847 SourceManager &SM;
848 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
849 bool operator()(Decl *A, Decl *B) {
850 SourceLocation L_A = A->getLocStart();
851 SourceLocation L_B = B->getLocStart();
852 assert(L_A.isValid() && L_B.isValid());
853 return SM.isBeforeInTranslationUnit(L_A, L_B);
854 }
855 };
856}
857
Douglas Gregora59e3902010-01-21 23:27:09 +0000858bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000859 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
860 // an @implementation can lexically contain Decls that are not properly
861 // nested in the AST. When we identify such cases, we need to retrofit
862 // this nesting here.
863 if (!DI_current)
864 return VisitDeclContext(D);
865
866 // Scan the Decls that immediately come after the container
867 // in the current DeclContext. If any fall within the
868 // container's lexical region, stash them into a vector
869 // for later processing.
870 llvm::SmallVector<Decl *, 24> DeclsInContainer;
871 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000872 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000873 if (EndLoc.isValid()) {
874 DeclContext::decl_iterator next = *DI_current;
875 while (++next != DE_current) {
876 Decl *D_next = *next;
877 if (!D_next)
878 break;
879 SourceLocation L = D_next->getLocStart();
880 if (!L.isValid())
881 break;
882 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
883 *DI_current = next;
884 DeclsInContainer.push_back(D_next);
885 continue;
886 }
887 break;
888 }
889 }
890
891 // The common case.
892 if (DeclsInContainer.empty())
893 return VisitDeclContext(D);
894
895 // Get all the Decls in the DeclContext, and sort them with the
896 // additional ones we've collected. Then visit them.
897 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
898 I!=E; ++I) {
899 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000900 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
901 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000902 continue;
903 DeclsInContainer.push_back(subDecl);
904 }
905
906 // Now sort the Decls so that they appear in lexical order.
907 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
908 ContainerDeclsSort(SM));
909
910 // Now visit the decls.
911 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
912 E = DeclsInContainer.end(); I != E; ++I) {
913 CXCursor Cursor = MakeCXCursor(*I, TU);
914 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
915 if (!V.hasValue())
916 continue;
917 if (!V.getValue())
918 return false;
919 if (Visit(Cursor, true))
920 return true;
921 }
922 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000923}
924
Douglas Gregorb1373d02010-01-20 20:59:29 +0000925bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000926 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
927 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000928 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000929
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000930 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
931 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
932 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000933 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000934 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000935
Douglas Gregora59e3902010-01-21 23:27:09 +0000936 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000937}
938
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000939bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
940 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
941 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
942 E = PID->protocol_end(); I != E; ++I, ++PL)
943 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
944 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000945
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000946 return VisitObjCContainerDecl(PID);
947}
948
Ted Kremenek23173d72010-05-18 21:09:07 +0000949bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000950 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000951 return true;
952
Ted Kremenek23173d72010-05-18 21:09:07 +0000953 // FIXME: This implements a workaround with @property declarations also being
954 // installed in the DeclContext for the @interface. Eventually this code
955 // should be removed.
956 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
957 if (!CDecl || !CDecl->IsClassExtension())
958 return false;
959
960 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
961 if (!ID)
962 return false;
963
964 IdentifierInfo *PropertyId = PD->getIdentifier();
965 ObjCPropertyDecl *prevDecl =
966 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
967
968 if (!prevDecl)
969 return false;
970
971 // Visit synthesized methods since they will be skipped when visiting
972 // the @interface.
973 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000974 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000975 if (Visit(MakeCXCursor(MD, TU)))
976 return true;
977
978 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000979 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000980 if (Visit(MakeCXCursor(MD, TU)))
981 return true;
982
983 return false;
984}
985
Douglas Gregorb1373d02010-01-20 20:59:29 +0000986bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000987 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988 if (D->getSuperClass() &&
989 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000991 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000992 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000994 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
995 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
996 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000997 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000998 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999
Douglas Gregora59e3902010-01-21 23:27:09 +00001000 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001001}
1002
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001003bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1004 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001005}
1006
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001007bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001008 // 'ID' could be null when dealing with invalid code.
1009 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1010 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001013 return VisitObjCImplDecl(D);
1014}
1015
1016bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1017#if 0
1018 // Issue callbacks for super class.
1019 // FIXME: No source location information!
1020 if (D->getSuperClass() &&
1021 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001023 TU)))
1024 return true;
1025#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001027 return VisitObjCImplDecl(D);
1028}
1029
1030bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1031 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1032 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1033 E = D->protocol_end();
1034 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001035 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001036 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037
1038 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001039}
1040
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001041bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1042 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1043 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1044 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001047}
1048
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001049bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1050 return VisitDeclContext(D);
1051}
1052
Douglas Gregor69319002010-08-31 23:48:11 +00001053bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001054 // Visit nested-name-specifier.
1055 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1056 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1057 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001058
1059 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1060 D->getTargetNameLoc(), TU));
1061}
1062
Douglas Gregor7e242562010-09-01 19:52:22 +00001063bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001064 // Visit nested-name-specifier.
1065 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1066 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1067 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001068
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001069 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1070 return true;
1071
Douglas Gregor7e242562010-09-01 19:52:22 +00001072 return VisitDeclarationNameInfo(D->getNameInfo());
1073}
1074
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001075bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001076 // Visit nested-name-specifier.
1077 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1078 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1079 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001080
1081 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1082 D->getIdentLocation(), TU));
1083}
1084
Douglas Gregor7e242562010-09-01 19:52:22 +00001085bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 // Visit nested-name-specifier.
1087 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1088 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1089 return true;
1090
Douglas Gregor7e242562010-09-01 19:52:22 +00001091 return VisitDeclarationNameInfo(D->getNameInfo());
1092}
1093
1094bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1095 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 // Visit nested-name-specifier.
1097 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1098 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1099 return true;
1100
Douglas Gregor7e242562010-09-01 19:52:22 +00001101 return false;
1102}
1103
Douglas Gregor01829d32010-08-31 14:41:23 +00001104bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1105 switch (Name.getName().getNameKind()) {
1106 case clang::DeclarationName::Identifier:
1107 case clang::DeclarationName::CXXLiteralOperatorName:
1108 case clang::DeclarationName::CXXOperatorName:
1109 case clang::DeclarationName::CXXUsingDirective:
1110 return false;
1111
1112 case clang::DeclarationName::CXXConstructorName:
1113 case clang::DeclarationName::CXXDestructorName:
1114 case clang::DeclarationName::CXXConversionFunctionName:
1115 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1116 return Visit(TSInfo->getTypeLoc());
1117 return false;
1118
1119 case clang::DeclarationName::ObjCZeroArgSelector:
1120 case clang::DeclarationName::ObjCOneArgSelector:
1121 case clang::DeclarationName::ObjCMultiArgSelector:
1122 // FIXME: Per-identifier location info?
1123 return false;
1124 }
1125
1126 return false;
1127}
1128
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001129bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1130 SourceRange Range) {
1131 // FIXME: This whole routine is a hack to work around the lack of proper
1132 // source information in nested-name-specifiers (PR5791). Since we do have
1133 // a beginning source location, we can visit the first component of the
1134 // nested-name-specifier, if it's a single-token component.
1135 if (!NNS)
1136 return false;
1137
1138 // Get the first component in the nested-name-specifier.
1139 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1140 NNS = Prefix;
1141
1142 switch (NNS->getKind()) {
1143 case NestedNameSpecifier::Namespace:
1144 // FIXME: The token at this source location might actually have been a
1145 // namespace alias, but we don't model that. Lame!
1146 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1147 TU));
1148
1149 case NestedNameSpecifier::TypeSpec: {
1150 // If the type has a form where we know that the beginning of the source
1151 // range matches up with a reference cursor. Visit the appropriate reference
1152 // cursor.
1153 Type *T = NNS->getAsType();
1154 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1155 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1156 if (const TagType *Tag = dyn_cast<TagType>(T))
1157 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1158 if (const TemplateSpecializationType *TST
1159 = dyn_cast<TemplateSpecializationType>(T))
1160 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1161 break;
1162 }
1163
1164 case NestedNameSpecifier::TypeSpecWithTemplate:
1165 case NestedNameSpecifier::Global:
1166 case NestedNameSpecifier::Identifier:
1167 break;
1168 }
1169
1170 return false;
1171}
1172
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001173bool CursorVisitor::VisitTemplateParameters(
1174 const TemplateParameterList *Params) {
1175 if (!Params)
1176 return false;
1177
1178 for (TemplateParameterList::const_iterator P = Params->begin(),
1179 PEnd = Params->end();
1180 P != PEnd; ++P) {
1181 if (Visit(MakeCXCursor(*P, TU)))
1182 return true;
1183 }
1184
1185 return false;
1186}
1187
Douglas Gregor0b36e612010-08-31 20:37:03 +00001188bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1189 switch (Name.getKind()) {
1190 case TemplateName::Template:
1191 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1192
1193 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001194 // Visit the overloaded template set.
1195 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1196 return true;
1197
Douglas Gregor0b36e612010-08-31 20:37:03 +00001198 return false;
1199
1200 case TemplateName::DependentTemplate:
1201 // FIXME: Visit nested-name-specifier.
1202 return false;
1203
1204 case TemplateName::QualifiedTemplate:
1205 // FIXME: Visit nested-name-specifier.
1206 return Visit(MakeCursorTemplateRef(
1207 Name.getAsQualifiedTemplateName()->getDecl(),
1208 Loc, TU));
1209 }
1210
1211 return false;
1212}
1213
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001214bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1215 switch (TAL.getArgument().getKind()) {
1216 case TemplateArgument::Null:
1217 case TemplateArgument::Integral:
1218 return false;
1219
1220 case TemplateArgument::Pack:
1221 // FIXME: Implement when variadic templates come along.
1222 return false;
1223
1224 case TemplateArgument::Type:
1225 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1226 return Visit(TSInfo->getTypeLoc());
1227 return false;
1228
1229 case TemplateArgument::Declaration:
1230 if (Expr *E = TAL.getSourceDeclExpression())
1231 return Visit(MakeCXCursor(E, StmtParent, TU));
1232 return false;
1233
1234 case TemplateArgument::Expression:
1235 if (Expr *E = TAL.getSourceExpression())
1236 return Visit(MakeCXCursor(E, StmtParent, TU));
1237 return false;
1238
1239 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001240 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1241 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001242 }
1243
1244 return false;
1245}
1246
Ted Kremeneka0536d82010-05-07 01:04:29 +00001247bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1248 return VisitDeclContext(D);
1249}
1250
Douglas Gregor01829d32010-08-31 14:41:23 +00001251bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1252 return Visit(TL.getUnqualifiedLoc());
1253}
1254
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001255bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001256 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001257
1258 // Some builtin types (such as Objective-C's "id", "sel", and
1259 // "Class") have associated declarations. Create cursors for those.
1260 QualType VisitType;
1261 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001262 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001263 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001264 case BuiltinType::Char_U:
1265 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001266 case BuiltinType::Char16:
1267 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001268 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001269 case BuiltinType::UInt:
1270 case BuiltinType::ULong:
1271 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001272 case BuiltinType::UInt128:
1273 case BuiltinType::Char_S:
1274 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001275 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001276 case BuiltinType::Short:
1277 case BuiltinType::Int:
1278 case BuiltinType::Long:
1279 case BuiltinType::LongLong:
1280 case BuiltinType::Int128:
1281 case BuiltinType::Float:
1282 case BuiltinType::Double:
1283 case BuiltinType::LongDouble:
1284 case BuiltinType::NullPtr:
1285 case BuiltinType::Overload:
1286 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001287 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001288
1289 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001290 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001291
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001292 case BuiltinType::ObjCId:
1293 VisitType = Context.getObjCIdType();
1294 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001295
1296 case BuiltinType::ObjCClass:
1297 VisitType = Context.getObjCClassType();
1298 break;
1299
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001300 case BuiltinType::ObjCSel:
1301 VisitType = Context.getObjCSelType();
1302 break;
1303 }
1304
1305 if (!VisitType.isNull()) {
1306 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001307 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001308 TU));
1309 }
1310
1311 return false;
1312}
1313
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001314bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1315 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1316}
1317
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001318bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1319 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1320}
1321
1322bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1323 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1324}
1325
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001326bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001327 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001328 // no context information with which we can match up the depth/index in the
1329 // type to the appropriate
1330 return false;
1331}
1332
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1334 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1335 return true;
1336
John McCallc12c5bb2010-05-15 11:32:37 +00001337 return false;
1338}
1339
1340bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1341 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1342 return true;
1343
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001344 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1345 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1346 TU)))
1347 return true;
1348 }
1349
1350 return false;
1351}
1352
1353bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001354 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001355}
1356
1357bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1358 return Visit(TL.getPointeeLoc());
1359}
1360
1361bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1362 return Visit(TL.getPointeeLoc());
1363}
1364
1365bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1366 return Visit(TL.getPointeeLoc());
1367}
1368
1369bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001370 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001371}
1372
1373bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001374 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375}
1376
Douglas Gregor01829d32010-08-31 14:41:23 +00001377bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1378 bool SkipResultType) {
1379 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380 return true;
1381
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001382 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001383 if (Decl *D = TL.getArg(I))
1384 if (Visit(MakeCXCursor(D, TU)))
1385 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386
1387 return false;
1388}
1389
1390bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1391 if (Visit(TL.getElementLoc()))
1392 return true;
1393
1394 if (Expr *Size = TL.getSizeExpr())
1395 return Visit(MakeCXCursor(Size, StmtParent, TU));
1396
1397 return false;
1398}
1399
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001400bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1401 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001402 // Visit the template name.
1403 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1404 TL.getTemplateNameLoc()))
1405 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001406
1407 // Visit the template arguments.
1408 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1409 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1410 return true;
1411
1412 return false;
1413}
1414
Douglas Gregor2332c112010-01-21 20:48:56 +00001415bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1416 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1417}
1418
1419bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1420 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1421 return Visit(TSInfo->getTypeLoc());
1422
1423 return false;
1424}
1425
Douglas Gregora59e3902010-01-21 23:27:09 +00001426bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001427 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001428}
1429
Ted Kremenek3064ef92010-08-27 21:34:58 +00001430bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1431 if (D->isDefinition()) {
1432 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1433 E = D->bases_end(); I != E; ++I) {
1434 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1435 return true;
1436 }
1437 }
1438
1439 return VisitTagDecl(D);
1440}
1441
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001442bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001443 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001444 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1445 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001446
1447 // Visit the components of the offsetof expression.
1448 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1449 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1450 const OffsetOfNode &Node = E->getComponent(I);
1451 switch (Node.getKind()) {
1452 case OffsetOfNode::Array:
1453 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1454 StmtParent, TU)))
1455 return true;
1456 break;
1457
1458 case OffsetOfNode::Field:
1459 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1460 TU)))
1461 return true;
1462 break;
1463
1464 case OffsetOfNode::Identifier:
1465 case OffsetOfNode::Base:
1466 continue;
1467 }
1468 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001469
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001470 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001471}
1472
Douglas Gregor336fd812010-01-23 00:40:08 +00001473bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1474 if (E->isArgumentType()) {
1475 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1476 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001477
Douglas Gregor336fd812010-01-23 00:40:08 +00001478 return false;
1479 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001480
Douglas Gregor336fd812010-01-23 00:40:08 +00001481 return VisitExpr(E);
1482}
1483
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001484bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1485 // Visit the designators.
1486 typedef DesignatedInitExpr::Designator Designator;
1487 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1488 DEnd = E->designators_end();
1489 D != DEnd; ++D) {
1490 if (D->isFieldDesignator()) {
1491 if (FieldDecl *Field = D->getField())
1492 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1493 return true;
1494
1495 continue;
1496 }
1497
1498 if (D->isArrayDesignator()) {
1499 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1500 return true;
1501
1502 continue;
1503 }
1504
1505 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1506 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1507 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1508 return true;
1509 }
1510
1511 // Visit the initializer value itself.
1512 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1513}
1514
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001515bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1516 if (E->isTypeOperand()) {
1517 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1518 return Visit(TSInfo->getTypeLoc());
1519
1520 return false;
1521 }
1522
1523 return VisitExpr(E);
1524}
1525
Douglas Gregorab6677e2010-09-08 00:15:04 +00001526bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1527 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1528 return Visit(TSInfo->getTypeLoc());
1529
1530 return false;
1531}
1532
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001533bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1534 // Visit base expression.
1535 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1536 return true;
1537
1538 // Visit the nested-name-specifier.
1539 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1540 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1541 return true;
1542
1543 // Visit the scope type that looks disturbingly like the nested-name-specifier
1544 // but isn't.
1545 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1546 if (Visit(TSInfo->getTypeLoc()))
1547 return true;
1548
1549 // Visit the name of the type being destroyed.
1550 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1551 if (Visit(TSInfo->getTypeLoc()))
1552 return true;
1553
1554 return false;
1555}
1556
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001557bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1558 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1559}
1560
Douglas Gregorbfebed22010-09-03 17:24:10 +00001561bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1562 DependentScopeDeclRefExpr *E) {
1563 // Visit the nested-name-specifier.
1564 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1565 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1566 return true;
1567
1568 // Visit the declaration name.
1569 if (VisitDeclarationNameInfo(E->getNameInfo()))
1570 return true;
1571
1572 // Visit the explicitly-specified template arguments.
1573 if (const ExplicitTemplateArgumentList *ArgList
1574 = E->getOptionalExplicitTemplateArgs()) {
1575 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1576 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1577 Arg != ArgEnd; ++Arg) {
1578 if (VisitTemplateArgumentLoc(*Arg))
1579 return true;
1580 }
1581 }
1582
1583 return false;
1584}
1585
Douglas Gregor25d63622010-09-03 17:35:34 +00001586bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1587 CXXDependentScopeMemberExpr *E) {
1588 // Visit the base expression, if there is one.
1589 if (!E->isImplicitAccess() &&
1590 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1591 return true;
1592
1593 // Visit the nested-name-specifier.
1594 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1595 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1596 return true;
1597
1598 // Visit the declaration name.
1599 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1600 return true;
1601
1602 // Visit the explicitly-specified template arguments.
1603 if (const ExplicitTemplateArgumentList *ArgList
1604 = E->getOptionalExplicitTemplateArgs()) {
1605 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1606 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1607 Arg != ArgEnd; ++Arg) {
1608 if (VisitTemplateArgumentLoc(*Arg))
1609 return true;
1610 }
1611 }
1612
1613 return false;
1614}
1615
Ted Kremenek09dfa372010-02-18 05:46:33 +00001616bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001617 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1618 i != e; ++i)
1619 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001620 return true;
1621
1622 return false;
1623}
1624
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001625//===----------------------------------------------------------------------===//
1626// Data-recursive visitor methods.
1627//===----------------------------------------------------------------------===//
1628
Ted Kremenek28a71942010-11-13 00:36:47 +00001629namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001630#define DEF_JOB(NAME, DATA, KIND)\
1631class NAME : public VisitorJob {\
1632public:\
1633 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1634 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1635 DATA *get() const { return static_cast<DATA*>(dataA); }\
1636};
1637
1638DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1639DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001640DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001641DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001642DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1643 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001644#undef DEF_JOB
1645
1646class DeclVisit : public VisitorJob {
1647public:
1648 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1649 VisitorJob(parent, VisitorJob::DeclVisitKind,
1650 d, isFirst ? (void*) 1 : (void*) 0) {}
1651 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001652 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001653 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001654 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001655 bool isFirst() const { return dataB ? true : false; }
1656};
Ted Kremenek035dc412010-11-13 00:36:50 +00001657class TypeLocVisit : public VisitorJob {
1658public:
1659 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1660 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1661 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1662
1663 static bool classof(const VisitorJob *VJ) {
1664 return VJ->getKind() == TypeLocVisitKind;
1665 }
1666
Ted Kremenek82f3c502010-11-15 22:23:26 +00001667 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001668 QualType T = QualType::getFromOpaquePtr(dataA);
1669 return TypeLoc(T, dataB);
1670 }
1671};
1672
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001673class LabelRefVisit : public VisitorJob {
1674public:
1675 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1676 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1677 (void*) labelLoc.getRawEncoding()) {}
1678
1679 static bool classof(const VisitorJob *VJ) {
1680 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1681 }
1682 LabelStmt *get() const { return static_cast<LabelStmt*>(dataA); }
1683 SourceLocation getLoc() const {
1684 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) dataB); }
1685};
1686
Ted Kremenek28a71942010-11-13 00:36:47 +00001687class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1688 VisitorWorkList &WL;
1689 CXCursor Parent;
1690public:
1691 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1692 : WL(wl), Parent(parent) {}
1693
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001694 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001695 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001697 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001698 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1699 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001700 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001701 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001702 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001703 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001704 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001705 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001706 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1707 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001708 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001709 void VisitIfStmt(IfStmt *If);
1710 void VisitInitListExpr(InitListExpr *IE);
1711 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001712 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001713 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1714 void VisitOverloadExpr(OverloadExpr *E);
1715 void VisitStmt(Stmt *S);
1716 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001717 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001718 void VisitWhileStmt(WhileStmt *W);
1719 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001720 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001721
1722private:
Ted Kremenek60608ec2010-11-17 00:50:47 +00001723 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenek28a71942010-11-13 00:36:47 +00001724 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001725 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001726 void AddTypeLoc(TypeSourceInfo *TI);
1727 void EnqueueChildren(Stmt *S);
1728};
1729} // end anonyous namespace
1730
1731void EnqueueVisitor::AddStmt(Stmt *S) {
1732 if (S)
1733 WL.push_back(StmtVisit(S, Parent));
1734}
Ted Kremenek035dc412010-11-13 00:36:50 +00001735void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001736 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001737 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001738}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001739void EnqueueVisitor::
1740 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1741 if (A)
1742 WL.push_back(ExplicitTemplateArgsVisit(
1743 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1744}
Ted Kremenek28a71942010-11-13 00:36:47 +00001745void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1746 if (TI)
1747 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1748 }
1749void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001750 unsigned size = WL.size();
1751 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1752 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001753 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001754 }
1755 if (size == WL.size())
1756 return;
1757 // Now reverse the entries we just added. This will match the DFS
1758 // ordering performed by the worklist.
1759 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1760 std::reverse(I, E);
1761}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001762void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1763 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1764}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001765void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1766 AddDecl(B->getBlockDecl());
1767}
Ted Kremenek28a71942010-11-13 00:36:47 +00001768void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1769 EnqueueChildren(E);
1770 AddTypeLoc(E->getTypeSourceInfo());
1771}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001772void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1773 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1774 E = S->body_rend(); I != E; ++I) {
1775 AddStmt(*I);
1776 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001777}
1778void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1779 // Enqueue the initializer or constructor arguments.
1780 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1781 AddStmt(E->getConstructorArg(I-1));
1782 // Enqueue the array size, if any.
1783 AddStmt(E->getArraySize());
1784 // Enqueue the allocated type.
1785 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1786 // Enqueue the placement arguments.
1787 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1788 AddStmt(E->getPlacementArg(I-1));
1789}
Ted Kremenek28a71942010-11-13 00:36:47 +00001790void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001791 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1792 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001793 AddStmt(CE->getCallee());
1794 AddStmt(CE->getArg(0));
1795}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001796void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1797 EnqueueChildren(E);
1798 AddTypeLoc(E->getTypeSourceInfo());
1799}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001800void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1801 EnqueueChildren(E);
1802 if (E->isTypeOperand())
1803 AddTypeLoc(E->getTypeOperandSourceInfo());
1804}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001805
1806void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1807 *E) {
1808 EnqueueChildren(E);
1809 AddTypeLoc(E->getTypeSourceInfo());
1810}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001811void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001812 if (DR->hasExplicitTemplateArgs()) {
1813 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1814 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001815 WL.push_back(DeclRefExprParts(DR, Parent));
1816}
Ted Kremenek035dc412010-11-13 00:36:50 +00001817void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1818 unsigned size = WL.size();
1819 bool isFirst = true;
1820 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1821 D != DEnd; ++D) {
1822 AddDecl(*D, isFirst);
1823 isFirst = false;
1824 }
1825 if (size == WL.size())
1826 return;
1827 // Now reverse the entries we just added. This will match the DFS
1828 // ordering performed by the worklist.
1829 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1830 std::reverse(I, E);
1831}
Ted Kremenek28a71942010-11-13 00:36:47 +00001832void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1833 EnqueueChildren(E);
1834 AddTypeLoc(E->getTypeInfoAsWritten());
1835}
1836void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1837 AddStmt(FS->getBody());
1838 AddStmt(FS->getInc());
1839 AddStmt(FS->getCond());
1840 AddDecl(FS->getConditionVariable());
1841 AddStmt(FS->getInit());
1842}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001843void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1844 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1845}
Ted Kremenek28a71942010-11-13 00:36:47 +00001846void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1847 AddStmt(If->getElse());
1848 AddStmt(If->getThen());
1849 AddStmt(If->getCond());
1850 AddDecl(If->getConditionVariable());
1851}
1852void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1853 // We care about the syntactic form of the initializer list, only.
1854 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1855 IE = Syntactic;
1856 EnqueueChildren(IE);
1857}
1858void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1859 WL.push_back(MemberExprParts(M, Parent));
1860 AddStmt(M->getBase());
1861}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001862void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1863 AddTypeLoc(E->getEncodedTypeSourceInfo());
1864}
Ted Kremenek28a71942010-11-13 00:36:47 +00001865void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1866 EnqueueChildren(M);
1867 AddTypeLoc(M->getClassReceiverTypeInfo());
1868}
1869void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001870 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001871 WL.push_back(OverloadExprParts(E, Parent));
1872}
Ted Kremenek28a71942010-11-13 00:36:47 +00001873void EnqueueVisitor::VisitStmt(Stmt *S) {
1874 EnqueueChildren(S);
1875}
1876void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1877 AddStmt(S->getBody());
1878 AddStmt(S->getCond());
1879 AddDecl(S->getConditionVariable());
1880}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001881void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1882 AddTypeLoc(E->getArgTInfo2());
1883 AddTypeLoc(E->getArgTInfo1());
1884}
1885
Ted Kremenek28a71942010-11-13 00:36:47 +00001886void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1887 AddStmt(W->getBody());
1888 AddStmt(W->getCond());
1889 AddDecl(W->getConditionVariable());
1890}
1891void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1892 VisitOverloadExpr(U);
1893 if (!U->isImplicitAccess())
1894 AddStmt(U->getBase());
1895}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001896void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1897 AddStmt(E->getSubExpr());
1898 AddTypeLoc(E->getWrittenTypeInfo());
1899}
Ted Kremenek60458782010-11-12 21:34:16 +00001900
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001901void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001902 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001903}
1904
1905bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1906 if (RegionOfInterest.isValid()) {
1907 SourceRange Range = getRawCursorExtent(C);
1908 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1909 return false;
1910 }
1911 return true;
1912}
1913
1914bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1915 while (!WL.empty()) {
1916 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001917 VisitorJob LI = WL.back();
1918 WL.pop_back();
1919
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001920 // Set the Parent field, then back to its old value once we're done.
1921 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1922
1923 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001924 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001925 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001926 if (!D)
1927 continue;
1928
1929 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001930 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001931 return true;
1932
1933 continue;
1934 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001935 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1936 const ExplicitTemplateArgumentList *ArgList =
1937 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1938 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1939 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1940 Arg != ArgEnd; ++Arg) {
1941 if (VisitTemplateArgumentLoc(*Arg))
1942 return true;
1943 }
1944 continue;
1945 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001946 case VisitorJob::TypeLocVisitKind: {
1947 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001948 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001949 return true;
1950 continue;
1951 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001952 case VisitorJob::LabelRefVisitKind: {
1953 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1954 if (Visit(MakeCursorLabelRef(LS,
1955 cast<LabelRefVisit>(&LI)->getLoc(),
1956 TU)))
1957 return true;
1958 continue;
1959 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001960 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001961 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001962 if (!S)
1963 continue;
1964
Ted Kremenekf1107452010-11-12 18:26:56 +00001965 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001966 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1967
1968 switch (S->getStmtClass()) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001969 // Cases not yet handled by the data-recursion
1970 // algorithm.
1971 case Stmt::OffsetOfExprClass:
1972 case Stmt::SizeOfAlignOfExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001973 case Stmt::DesignatedInitExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001974 case Stmt::CXXUuidofExprClass:
1975 case Stmt::CXXScalarValueInitExprClass:
1976 case Stmt::CXXPseudoDestructorExprClass:
1977 case Stmt::UnaryTypeTraitExprClass:
1978 case Stmt::DependentScopeDeclRefExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001979 case Stmt::CXXDependentScopeMemberExprClass:
1980 if (Visit(Cursor))
1981 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001982 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001983 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001984 if (!IsInRegionOfInterest(Cursor))
1985 continue;
1986 switch (Visitor(Cursor, Parent, ClientData)) {
1987 case CXChildVisit_Break:
1988 return true;
1989 case CXChildVisit_Continue:
1990 break;
1991 case CXChildVisit_Recurse:
1992 EnqueueWorkList(WL, S);
1993 break;
1994 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001995 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001996 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001997 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001998 }
1999 case VisitorJob::MemberExprPartsKind: {
2000 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002001 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002002
2003 // Visit the nested-name-specifier
2004 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2005 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2006 return true;
2007
2008 // Visit the declaration name.
2009 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2010 return true;
2011
2012 // Visit the explicitly-specified template arguments, if any.
2013 if (M->hasExplicitTemplateArgs()) {
2014 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2015 *ArgEnd = Arg + M->getNumTemplateArgs();
2016 Arg != ArgEnd; ++Arg) {
2017 if (VisitTemplateArgumentLoc(*Arg))
2018 return true;
2019 }
2020 }
2021 continue;
2022 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002023 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002024 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002025 // Visit nested-name-specifier, if present.
2026 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2027 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2028 return true;
2029 // Visit declaration name.
2030 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2031 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002032 continue;
2033 }
Ted Kremenek60458782010-11-12 21:34:16 +00002034 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002035 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002036 // Visit the nested-name-specifier.
2037 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2038 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2039 return true;
2040 // Visit the declaration name.
2041 if (VisitDeclarationNameInfo(O->getNameInfo()))
2042 return true;
2043 // Visit the overloaded declaration reference.
2044 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2045 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002046 continue;
2047 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002048 }
2049 }
2050 return false;
2051}
2052
2053bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002054 VisitorWorkList *WL = 0;
2055 if (!WorkListFreeList.empty()) {
2056 WL = WorkListFreeList.back();
2057 WL->clear();
2058 WorkListFreeList.pop_back();
2059 }
2060 else {
2061 WL = new VisitorWorkList();
2062 WorkListCache.push_back(WL);
2063 }
2064 EnqueueWorkList(*WL, S);
2065 bool result = RunVisitorWorkList(*WL);
2066 WorkListFreeList.push_back(WL);
2067 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002068}
2069
2070//===----------------------------------------------------------------------===//
2071// Misc. API hooks.
2072//===----------------------------------------------------------------------===//
2073
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002074static llvm::sys::Mutex EnableMultithreadingMutex;
2075static bool EnabledMultithreading;
2076
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002077extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002078CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2079 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002080 // Disable pretty stack trace functionality, which will otherwise be a very
2081 // poor citizen of the world and set up all sorts of signal handlers.
2082 llvm::DisablePrettyStackTrace = true;
2083
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002084 // We use crash recovery to make some of our APIs more reliable, implicitly
2085 // enable it.
2086 llvm::CrashRecoveryContext::Enable();
2087
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002088 // Enable support for multithreading in LLVM.
2089 {
2090 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2091 if (!EnabledMultithreading) {
2092 llvm::llvm_start_multithreaded();
2093 EnabledMultithreading = true;
2094 }
2095 }
2096
Douglas Gregora030b7c2010-01-22 20:35:53 +00002097 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002098 if (excludeDeclarationsFromPCH)
2099 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002100 if (displayDiagnostics)
2101 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002102 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002103}
2104
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002105void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002106 if (CIdx)
2107 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002108}
2109
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002110CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002111 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002112 if (!CIdx)
2113 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002114
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002115 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002116 FileSystemOptions FileSystemOpts;
2117 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002118
Douglas Gregor28019772010-04-05 23:52:57 +00002119 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002120 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002121 CXXIdx->getOnlyLocalDecls(),
2122 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002123 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002124}
2125
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002126unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002127 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002128 CXTranslationUnit_CacheCompletionResults |
2129 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002130}
2131
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002132CXTranslationUnit
2133clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2134 const char *source_filename,
2135 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002136 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002137 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002138 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002139 return clang_parseTranslationUnit(CIdx, source_filename,
2140 command_line_args, num_command_line_args,
2141 unsaved_files, num_unsaved_files,
2142 CXTranslationUnit_DetailedPreprocessingRecord);
2143}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002144
2145struct ParseTranslationUnitInfo {
2146 CXIndex CIdx;
2147 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002148 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002149 int num_command_line_args;
2150 struct CXUnsavedFile *unsaved_files;
2151 unsigned num_unsaved_files;
2152 unsigned options;
2153 CXTranslationUnit result;
2154};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002155static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002156 ParseTranslationUnitInfo *PTUI =
2157 static_cast<ParseTranslationUnitInfo*>(UserData);
2158 CXIndex CIdx = PTUI->CIdx;
2159 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002160 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002161 int num_command_line_args = PTUI->num_command_line_args;
2162 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2163 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2164 unsigned options = PTUI->options;
2165 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002166
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002167 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002168 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002169
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002170 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2171
Douglas Gregor44c181a2010-07-23 00:33:23 +00002172 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002173 bool CompleteTranslationUnit
2174 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002175 bool CacheCodeCompetionResults
2176 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002177 bool CXXPrecompilePreamble
2178 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2179 bool CXXChainedPCH
2180 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002181
Douglas Gregor5352ac02010-01-28 00:27:43 +00002182 // Configure the diagnostics.
2183 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002184 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2185 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002186
Douglas Gregor4db64a42010-01-23 00:14:00 +00002187 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2188 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002189 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002190 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002191 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002192 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2193 Buffer));
2194 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
Douglas Gregorb10daed2010-10-11 16:52:23 +00002196 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002197
Ted Kremenek139ba862009-10-22 00:03:57 +00002198 // The 'source_filename' argument is optional. If the caller does not
2199 // specify it then it is assumed that the source file is specified
2200 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002201 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002202 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002203
2204 // Since the Clang C library is primarily used by batch tools dealing with
2205 // (often very broken) source code, where spell-checking can have a
2206 // significant negative impact on performance (particularly when
2207 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002208 // Only do this if we haven't found a spell-checking-related argument.
2209 bool FoundSpellCheckingArgument = false;
2210 for (int I = 0; I != num_command_line_args; ++I) {
2211 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2212 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2213 FoundSpellCheckingArgument = true;
2214 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002215 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 }
2217 if (!FoundSpellCheckingArgument)
2218 Args.push_back("-fno-spell-checking");
2219
2220 Args.insert(Args.end(), command_line_args,
2221 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002222
Douglas Gregor44c181a2010-07-23 00:33:23 +00002223 // Do we need the detailed preprocessing record?
2224 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002225 Args.push_back("-Xclang");
2226 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002227 }
2228
Douglas Gregorb10daed2010-10-11 16:52:23 +00002229 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002230 llvm::OwningPtr<ASTUnit> Unit(
2231 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2232 Diags,
2233 CXXIdx->getClangResourcesPath(),
2234 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002235 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002236 RemappedFiles.data(),
2237 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002238 PrecompilePreamble,
2239 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002240 CacheCodeCompetionResults,
2241 CXXPrecompilePreamble,
2242 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002243
Douglas Gregorb10daed2010-10-11 16:52:23 +00002244 if (NumErrors != Diags->getNumErrors()) {
2245 // Make sure to check that 'Unit' is non-NULL.
2246 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2247 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2248 DEnd = Unit->stored_diag_end();
2249 D != DEnd; ++D) {
2250 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2251 CXString Msg = clang_formatDiagnostic(&Diag,
2252 clang_defaultDiagnosticDisplayOptions());
2253 fprintf(stderr, "%s\n", clang_getCString(Msg));
2254 clang_disposeString(Msg);
2255 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002256#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002257 // On Windows, force a flush, since there may be multiple copies of
2258 // stderr and stdout in the file system, all with different buffers
2259 // but writing to the same device.
2260 fflush(stderr);
2261#endif
2262 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002263 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002264
Ted Kremeneka60ed472010-11-16 08:15:36 +00002265 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002266}
2267CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2268 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002269 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002270 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002271 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002272 unsigned num_unsaved_files,
2273 unsigned options) {
2274 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002275 num_command_line_args, unsaved_files,
2276 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002277 llvm::CrashRecoveryContext CRC;
2278
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002279 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002280 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2281 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2282 fprintf(stderr, " 'command_line_args' : [");
2283 for (int i = 0; i != num_command_line_args; ++i) {
2284 if (i)
2285 fprintf(stderr, ", ");
2286 fprintf(stderr, "'%s'", command_line_args[i]);
2287 }
2288 fprintf(stderr, "],\n");
2289 fprintf(stderr, " 'unsaved_files' : [");
2290 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2291 if (i)
2292 fprintf(stderr, ", ");
2293 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2294 unsaved_files[i].Length);
2295 }
2296 fprintf(stderr, "],\n");
2297 fprintf(stderr, " 'options' : %d,\n", options);
2298 fprintf(stderr, "}\n");
2299
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002300 return 0;
2301 }
2302
2303 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002304}
2305
Douglas Gregor19998442010-08-13 15:35:05 +00002306unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2307 return CXSaveTranslationUnit_None;
2308}
2309
2310int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2311 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002312 if (!TU)
2313 return 1;
2314
Ted Kremeneka60ed472010-11-16 08:15:36 +00002315 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002316}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002317
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002318void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002319 if (CTUnit) {
2320 // If the translation unit has been marked as unsafe to free, just discard
2321 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002322 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002323 return;
2324
Ted Kremeneka60ed472010-11-16 08:15:36 +00002325 delete static_cast<ASTUnit *>(CTUnit->TUData);
2326 disposeCXStringPool(CTUnit->StringPool);
2327 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002328 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002329}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002330
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002331unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2332 return CXReparse_None;
2333}
2334
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002335struct ReparseTranslationUnitInfo {
2336 CXTranslationUnit TU;
2337 unsigned num_unsaved_files;
2338 struct CXUnsavedFile *unsaved_files;
2339 unsigned options;
2340 int result;
2341};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002342
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002343static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002344 ReparseTranslationUnitInfo *RTUI =
2345 static_cast<ReparseTranslationUnitInfo*>(UserData);
2346 CXTranslationUnit TU = RTUI->TU;
2347 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2348 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2349 unsigned options = RTUI->options;
2350 (void) options;
2351 RTUI->result = 1;
2352
Douglas Gregorabc563f2010-07-19 21:46:24 +00002353 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002354 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002355
Ted Kremeneka60ed472010-11-16 08:15:36 +00002356 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002357 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002358
2359 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2360 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2361 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2362 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002363 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002364 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2365 Buffer));
2366 }
2367
Douglas Gregor593b0c12010-09-23 18:47:53 +00002368 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2369 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002370}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002371
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002372int clang_reparseTranslationUnit(CXTranslationUnit TU,
2373 unsigned num_unsaved_files,
2374 struct CXUnsavedFile *unsaved_files,
2375 unsigned options) {
2376 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2377 options, 0 };
2378 llvm::CrashRecoveryContext CRC;
2379
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002380 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002381 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002382 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002383 return 1;
2384 }
2385
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002386
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002387 return RTUI.result;
2388}
2389
Douglas Gregordf95a132010-08-09 20:45:32 +00002390
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002391CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002392 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002393 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002394
Ted Kremeneka60ed472010-11-16 08:15:36 +00002395 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002396 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002397}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002398
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002399CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002400 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002401 return Result;
2402}
2403
Ted Kremenekfb480492010-01-13 21:46:36 +00002404} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002405
Ted Kremenekfb480492010-01-13 21:46:36 +00002406//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002407// CXSourceLocation and CXSourceRange Operations.
2408//===----------------------------------------------------------------------===//
2409
Douglas Gregorb9790342010-01-22 21:44:22 +00002410extern "C" {
2411CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002412 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002413 return Result;
2414}
2415
2416unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002417 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2418 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2419 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002420}
2421
2422CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2423 CXFile file,
2424 unsigned line,
2425 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002426 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002427 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002428
Ted Kremeneka60ed472010-11-16 08:15:36 +00002429 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002430 SourceLocation SLoc
2431 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002432 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002433 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002434 if (SLoc.isInvalid()) return clang_getNullLocation();
2435
2436 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2437}
2438
2439CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2440 CXFile file,
2441 unsigned offset) {
2442 if (!tu || !file)
2443 return clang_getNullLocation();
2444
Ted Kremeneka60ed472010-11-16 08:15:36 +00002445 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002446 SourceLocation Start
2447 = CXXUnit->getSourceManager().getLocation(
2448 static_cast<const FileEntry *>(file),
2449 1, 1);
2450 if (Start.isInvalid()) return clang_getNullLocation();
2451
2452 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2453
2454 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002455
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002456 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002457}
2458
Douglas Gregor5352ac02010-01-28 00:27:43 +00002459CXSourceRange clang_getNullRange() {
2460 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2461 return Result;
2462}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002463
Douglas Gregor5352ac02010-01-28 00:27:43 +00002464CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2465 if (begin.ptr_data[0] != end.ptr_data[0] ||
2466 begin.ptr_data[1] != end.ptr_data[1])
2467 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002468
2469 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002470 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002471 return Result;
2472}
2473
Douglas Gregor46766dc2010-01-26 19:19:08 +00002474void clang_getInstantiationLocation(CXSourceLocation location,
2475 CXFile *file,
2476 unsigned *line,
2477 unsigned *column,
2478 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002479 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2480
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002481 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002482 if (file)
2483 *file = 0;
2484 if (line)
2485 *line = 0;
2486 if (column)
2487 *column = 0;
2488 if (offset)
2489 *offset = 0;
2490 return;
2491 }
2492
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002493 const SourceManager &SM =
2494 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002495 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002496
2497 if (file)
2498 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2499 if (line)
2500 *line = SM.getInstantiationLineNumber(InstLoc);
2501 if (column)
2502 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002503 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002504 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002505}
2506
Douglas Gregora9b06d42010-11-09 06:24:54 +00002507void clang_getSpellingLocation(CXSourceLocation location,
2508 CXFile *file,
2509 unsigned *line,
2510 unsigned *column,
2511 unsigned *offset) {
2512 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2513
2514 if (!location.ptr_data[0] || Loc.isInvalid()) {
2515 if (file)
2516 *file = 0;
2517 if (line)
2518 *line = 0;
2519 if (column)
2520 *column = 0;
2521 if (offset)
2522 *offset = 0;
2523 return;
2524 }
2525
2526 const SourceManager &SM =
2527 *static_cast<const SourceManager*>(location.ptr_data[0]);
2528 SourceLocation SpellLoc = Loc;
2529 if (SpellLoc.isMacroID()) {
2530 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2531 if (SimpleSpellingLoc.isFileID() &&
2532 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2533 SpellLoc = SimpleSpellingLoc;
2534 else
2535 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2536 }
2537
2538 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2539 FileID FID = LocInfo.first;
2540 unsigned FileOffset = LocInfo.second;
2541
2542 if (file)
2543 *file = (void *)SM.getFileEntryForID(FID);
2544 if (line)
2545 *line = SM.getLineNumber(FID, FileOffset);
2546 if (column)
2547 *column = SM.getColumnNumber(FID, FileOffset);
2548 if (offset)
2549 *offset = FileOffset;
2550}
2551
Douglas Gregor1db19de2010-01-19 21:36:55 +00002552CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002553 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002554 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002555 return Result;
2556}
2557
2558CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002559 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002560 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002561 return Result;
2562}
2563
Douglas Gregorb9790342010-01-22 21:44:22 +00002564} // end: extern "C"
2565
Douglas Gregor1db19de2010-01-19 21:36:55 +00002566//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002567// CXFile Operations.
2568//===----------------------------------------------------------------------===//
2569
2570extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002571CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002572 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002573 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002574
Steve Naroff88145032009-10-27 14:35:18 +00002575 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002576 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002577}
2578
2579time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002580 if (!SFile)
2581 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582
Steve Naroff88145032009-10-27 14:35:18 +00002583 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2584 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002585}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002586
Douglas Gregorb9790342010-01-22 21:44:22 +00002587CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2588 if (!tu)
2589 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590
Ted Kremeneka60ed472010-11-16 08:15:36 +00002591 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
Douglas Gregorb9790342010-01-22 21:44:22 +00002593 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002594 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2595 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002596 return const_cast<FileEntry *>(File);
2597}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Ted Kremenekfb480492010-01-13 21:46:36 +00002599} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002600
Ted Kremenekfb480492010-01-13 21:46:36 +00002601//===----------------------------------------------------------------------===//
2602// CXCursor Operations.
2603//===----------------------------------------------------------------------===//
2604
Ted Kremenekfb480492010-01-13 21:46:36 +00002605static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002606 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2607 return getDeclFromExpr(CE->getSubExpr());
2608
Ted Kremenekfb480492010-01-13 21:46:36 +00002609 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2610 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002611 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2612 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002613 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2614 return ME->getMemberDecl();
2615 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2616 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002617 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2618 return PRE->getProperty();
2619
Ted Kremenekfb480492010-01-13 21:46:36 +00002620 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2621 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002622 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2623 if (!CE->isElidable())
2624 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002625 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2626 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002627
Douglas Gregordb1314e2010-10-01 21:11:22 +00002628 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2629 return PE->getProtocol();
2630
Ted Kremenekfb480492010-01-13 21:46:36 +00002631 return 0;
2632}
2633
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002634static SourceLocation getLocationFromExpr(Expr *E) {
2635 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2636 return /*FIXME:*/Msg->getLeftLoc();
2637 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2638 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002639 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2640 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002641 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2642 return Member->getMemberLoc();
2643 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2644 return Ivar->getLocation();
2645 return E->getLocStart();
2646}
2647
Ted Kremenekfb480492010-01-13 21:46:36 +00002648extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002649
2650unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002651 CXCursorVisitor visitor,
2652 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002653 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2654 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002655 return CursorVis.VisitChildren(parent);
2656}
2657
David Chisnall3387c652010-11-03 14:12:26 +00002658#ifndef __has_feature
2659#define __has_feature(x) 0
2660#endif
2661#if __has_feature(blocks)
2662typedef enum CXChildVisitResult
2663 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2664
2665static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2666 CXClientData client_data) {
2667 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2668 return block(cursor, parent);
2669}
2670#else
2671// If we are compiled with a compiler that doesn't have native blocks support,
2672// define and call the block manually, so the
2673typedef struct _CXChildVisitResult
2674{
2675 void *isa;
2676 int flags;
2677 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002678 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2679 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002680} *CXCursorVisitorBlock;
2681
2682static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2683 CXClientData client_data) {
2684 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2685 return block->invoke(block, cursor, parent);
2686}
2687#endif
2688
2689
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002690unsigned clang_visitChildrenWithBlock(CXCursor parent,
2691 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002692 return clang_visitChildren(parent, visitWithBlock, block);
2693}
2694
Douglas Gregor78205d42010-01-20 21:45:58 +00002695static CXString getDeclSpelling(Decl *D) {
2696 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002697 if (!ND) {
2698 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2699 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2700 return createCXString(Property->getIdentifier()->getName());
2701
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002702 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002703 }
2704
Douglas Gregor78205d42010-01-20 21:45:58 +00002705 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002706 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002707
Douglas Gregor78205d42010-01-20 21:45:58 +00002708 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2709 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2710 // and returns different names. NamedDecl returns the class name and
2711 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002712 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002713
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002714 if (isa<UsingDirectiveDecl>(D))
2715 return createCXString("");
2716
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002717 llvm::SmallString<1024> S;
2718 llvm::raw_svector_ostream os(S);
2719 ND->printName(os);
2720
2721 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002722}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002723
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002724CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002725 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002726 return clang_getTranslationUnitSpelling(
2727 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002728
Steve Narofff334b4e2009-09-02 18:26:48 +00002729 if (clang_isReference(C.kind)) {
2730 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002731 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002732 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002733 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002734 }
2735 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002736 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002737 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002738 }
2739 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002740 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002741 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002742 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002743 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002744 case CXCursor_CXXBaseSpecifier: {
2745 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2746 return createCXString(B->getType().getAsString());
2747 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002748 case CXCursor_TypeRef: {
2749 TypeDecl *Type = getCursorTypeRef(C).first;
2750 assert(Type && "Missing type decl");
2751
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002752 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2753 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002754 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002755 case CXCursor_TemplateRef: {
2756 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002757 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002758
2759 return createCXString(Template->getNameAsString());
2760 }
Douglas Gregor69319002010-08-31 23:48:11 +00002761
2762 case CXCursor_NamespaceRef: {
2763 NamedDecl *NS = getCursorNamespaceRef(C).first;
2764 assert(NS && "Missing namespace decl");
2765
2766 return createCXString(NS->getNameAsString());
2767 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002768
Douglas Gregora67e03f2010-09-09 21:42:20 +00002769 case CXCursor_MemberRef: {
2770 FieldDecl *Field = getCursorMemberRef(C).first;
2771 assert(Field && "Missing member decl");
2772
2773 return createCXString(Field->getNameAsString());
2774 }
2775
Douglas Gregor36897b02010-09-10 00:22:18 +00002776 case CXCursor_LabelRef: {
2777 LabelStmt *Label = getCursorLabelRef(C).first;
2778 assert(Label && "Missing label");
2779
2780 return createCXString(Label->getID()->getName());
2781 }
2782
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002783 case CXCursor_OverloadedDeclRef: {
2784 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2785 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2786 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2787 return createCXString(ND->getNameAsString());
2788 return createCXString("");
2789 }
2790 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2791 return createCXString(E->getName().getAsString());
2792 OverloadedTemplateStorage *Ovl
2793 = Storage.get<OverloadedTemplateStorage*>();
2794 if (Ovl->size() == 0)
2795 return createCXString("");
2796 return createCXString((*Ovl->begin())->getNameAsString());
2797 }
2798
Daniel Dunbaracca7252009-11-30 20:42:49 +00002799 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002800 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002801 }
2802 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002803
2804 if (clang_isExpression(C.kind)) {
2805 Decl *D = getDeclFromExpr(getCursorExpr(C));
2806 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002807 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002808 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002809 }
2810
Douglas Gregor36897b02010-09-10 00:22:18 +00002811 if (clang_isStatement(C.kind)) {
2812 Stmt *S = getCursorStmt(C);
2813 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2814 return createCXString(Label->getID()->getName());
2815
2816 return createCXString("");
2817 }
2818
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002819 if (C.kind == CXCursor_MacroInstantiation)
2820 return createCXString(getCursorMacroInstantiation(C)->getName()
2821 ->getNameStart());
2822
Douglas Gregor572feb22010-03-18 18:04:21 +00002823 if (C.kind == CXCursor_MacroDefinition)
2824 return createCXString(getCursorMacroDefinition(C)->getName()
2825 ->getNameStart());
2826
Douglas Gregorecdcb882010-10-20 22:00:55 +00002827 if (C.kind == CXCursor_InclusionDirective)
2828 return createCXString(getCursorInclusionDirective(C)->getFileName());
2829
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002830 if (clang_isDeclaration(C.kind))
2831 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002832
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002833 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002834}
2835
Douglas Gregor358559d2010-10-02 22:49:11 +00002836CXString clang_getCursorDisplayName(CXCursor C) {
2837 if (!clang_isDeclaration(C.kind))
2838 return clang_getCursorSpelling(C);
2839
2840 Decl *D = getCursorDecl(C);
2841 if (!D)
2842 return createCXString("");
2843
2844 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2845 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2846 D = FunTmpl->getTemplatedDecl();
2847
2848 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2849 llvm::SmallString<64> Str;
2850 llvm::raw_svector_ostream OS(Str);
2851 OS << Function->getNameAsString();
2852 if (Function->getPrimaryTemplate())
2853 OS << "<>";
2854 OS << "(";
2855 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2856 if (I)
2857 OS << ", ";
2858 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2859 }
2860
2861 if (Function->isVariadic()) {
2862 if (Function->getNumParams())
2863 OS << ", ";
2864 OS << "...";
2865 }
2866 OS << ")";
2867 return createCXString(OS.str());
2868 }
2869
2870 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2871 llvm::SmallString<64> Str;
2872 llvm::raw_svector_ostream OS(Str);
2873 OS << ClassTemplate->getNameAsString();
2874 OS << "<";
2875 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2876 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2877 if (I)
2878 OS << ", ";
2879
2880 NamedDecl *Param = Params->getParam(I);
2881 if (Param->getIdentifier()) {
2882 OS << Param->getIdentifier()->getName();
2883 continue;
2884 }
2885
2886 // There is no parameter name, which makes this tricky. Try to come up
2887 // with something useful that isn't too long.
2888 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2889 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2890 else if (NonTypeTemplateParmDecl *NTTP
2891 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2892 OS << NTTP->getType().getAsString(Policy);
2893 else
2894 OS << "template<...> class";
2895 }
2896
2897 OS << ">";
2898 return createCXString(OS.str());
2899 }
2900
2901 if (ClassTemplateSpecializationDecl *ClassSpec
2902 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2903 // If the type was explicitly written, use that.
2904 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2905 return createCXString(TSInfo->getType().getAsString(Policy));
2906
2907 llvm::SmallString<64> Str;
2908 llvm::raw_svector_ostream OS(Str);
2909 OS << ClassSpec->getNameAsString();
2910 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002911 ClassSpec->getTemplateArgs().data(),
2912 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002913 Policy);
2914 return createCXString(OS.str());
2915 }
2916
2917 return clang_getCursorSpelling(C);
2918}
2919
Ted Kremeneke68fff62010-02-17 00:41:32 +00002920CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002921 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002922 case CXCursor_FunctionDecl:
2923 return createCXString("FunctionDecl");
2924 case CXCursor_TypedefDecl:
2925 return createCXString("TypedefDecl");
2926 case CXCursor_EnumDecl:
2927 return createCXString("EnumDecl");
2928 case CXCursor_EnumConstantDecl:
2929 return createCXString("EnumConstantDecl");
2930 case CXCursor_StructDecl:
2931 return createCXString("StructDecl");
2932 case CXCursor_UnionDecl:
2933 return createCXString("UnionDecl");
2934 case CXCursor_ClassDecl:
2935 return createCXString("ClassDecl");
2936 case CXCursor_FieldDecl:
2937 return createCXString("FieldDecl");
2938 case CXCursor_VarDecl:
2939 return createCXString("VarDecl");
2940 case CXCursor_ParmDecl:
2941 return createCXString("ParmDecl");
2942 case CXCursor_ObjCInterfaceDecl:
2943 return createCXString("ObjCInterfaceDecl");
2944 case CXCursor_ObjCCategoryDecl:
2945 return createCXString("ObjCCategoryDecl");
2946 case CXCursor_ObjCProtocolDecl:
2947 return createCXString("ObjCProtocolDecl");
2948 case CXCursor_ObjCPropertyDecl:
2949 return createCXString("ObjCPropertyDecl");
2950 case CXCursor_ObjCIvarDecl:
2951 return createCXString("ObjCIvarDecl");
2952 case CXCursor_ObjCInstanceMethodDecl:
2953 return createCXString("ObjCInstanceMethodDecl");
2954 case CXCursor_ObjCClassMethodDecl:
2955 return createCXString("ObjCClassMethodDecl");
2956 case CXCursor_ObjCImplementationDecl:
2957 return createCXString("ObjCImplementationDecl");
2958 case CXCursor_ObjCCategoryImplDecl:
2959 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002960 case CXCursor_CXXMethod:
2961 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002962 case CXCursor_UnexposedDecl:
2963 return createCXString("UnexposedDecl");
2964 case CXCursor_ObjCSuperClassRef:
2965 return createCXString("ObjCSuperClassRef");
2966 case CXCursor_ObjCProtocolRef:
2967 return createCXString("ObjCProtocolRef");
2968 case CXCursor_ObjCClassRef:
2969 return createCXString("ObjCClassRef");
2970 case CXCursor_TypeRef:
2971 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002972 case CXCursor_TemplateRef:
2973 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002974 case CXCursor_NamespaceRef:
2975 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002976 case CXCursor_MemberRef:
2977 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002978 case CXCursor_LabelRef:
2979 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002980 case CXCursor_OverloadedDeclRef:
2981 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002982 case CXCursor_UnexposedExpr:
2983 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002984 case CXCursor_BlockExpr:
2985 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002986 case CXCursor_DeclRefExpr:
2987 return createCXString("DeclRefExpr");
2988 case CXCursor_MemberRefExpr:
2989 return createCXString("MemberRefExpr");
2990 case CXCursor_CallExpr:
2991 return createCXString("CallExpr");
2992 case CXCursor_ObjCMessageExpr:
2993 return createCXString("ObjCMessageExpr");
2994 case CXCursor_UnexposedStmt:
2995 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002996 case CXCursor_LabelStmt:
2997 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002998 case CXCursor_InvalidFile:
2999 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003000 case CXCursor_InvalidCode:
3001 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003002 case CXCursor_NoDeclFound:
3003 return createCXString("NoDeclFound");
3004 case CXCursor_NotImplemented:
3005 return createCXString("NotImplemented");
3006 case CXCursor_TranslationUnit:
3007 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003008 case CXCursor_UnexposedAttr:
3009 return createCXString("UnexposedAttr");
3010 case CXCursor_IBActionAttr:
3011 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003012 case CXCursor_IBOutletAttr:
3013 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003014 case CXCursor_IBOutletCollectionAttr:
3015 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003016 case CXCursor_PreprocessingDirective:
3017 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003018 case CXCursor_MacroDefinition:
3019 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003020 case CXCursor_MacroInstantiation:
3021 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003022 case CXCursor_InclusionDirective:
3023 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003024 case CXCursor_Namespace:
3025 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003026 case CXCursor_LinkageSpec:
3027 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003028 case CXCursor_CXXBaseSpecifier:
3029 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003030 case CXCursor_Constructor:
3031 return createCXString("CXXConstructor");
3032 case CXCursor_Destructor:
3033 return createCXString("CXXDestructor");
3034 case CXCursor_ConversionFunction:
3035 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003036 case CXCursor_TemplateTypeParameter:
3037 return createCXString("TemplateTypeParameter");
3038 case CXCursor_NonTypeTemplateParameter:
3039 return createCXString("NonTypeTemplateParameter");
3040 case CXCursor_TemplateTemplateParameter:
3041 return createCXString("TemplateTemplateParameter");
3042 case CXCursor_FunctionTemplate:
3043 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003044 case CXCursor_ClassTemplate:
3045 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003046 case CXCursor_ClassTemplatePartialSpecialization:
3047 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003048 case CXCursor_NamespaceAlias:
3049 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003050 case CXCursor_UsingDirective:
3051 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003052 case CXCursor_UsingDeclaration:
3053 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003054 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003055
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003056 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003057 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003058}
Steve Naroff89922f82009-08-31 00:59:03 +00003059
Ted Kremeneke68fff62010-02-17 00:41:32 +00003060enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3061 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003062 CXClientData client_data) {
3063 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003064
3065 // If our current best cursor is the construction of a temporary object,
3066 // don't replace that cursor with a type reference, because we want
3067 // clang_getCursor() to point at the constructor.
3068 if (clang_isExpression(BestCursor->kind) &&
3069 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3070 cursor.kind == CXCursor_TypeRef)
3071 return CXChildVisit_Recurse;
3072
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003073 *BestCursor = cursor;
3074 return CXChildVisit_Recurse;
3075}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003076
Douglas Gregorb9790342010-01-22 21:44:22 +00003077CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3078 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003079 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003080
Ted Kremeneka60ed472010-11-16 08:15:36 +00003081 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003082 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3083
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003084 // Translate the given source location to make it point at the beginning of
3085 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003086 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003087
3088 // Guard against an invalid SourceLocation, or we may assert in one
3089 // of the following calls.
3090 if (SLoc.isInvalid())
3091 return clang_getNullCursor();
3092
Douglas Gregor40749ee2010-11-03 00:35:38 +00003093 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003094 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3095 CXXUnit->getASTContext().getLangOptions());
3096
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003097 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3098 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003099 // FIXME: Would be great to have a "hint" cursor, then walk from that
3100 // hint cursor upward until we find a cursor whose source range encloses
3101 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003102 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3103 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003104 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003105 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003106 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003107
3108 if (Logging) {
3109 CXFile SearchFile;
3110 unsigned SearchLine, SearchColumn;
3111 CXFile ResultFile;
3112 unsigned ResultLine, ResultColumn;
3113 CXString SearchFileName, ResultFileName, KindSpelling;
3114 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3115
3116 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3117 0);
3118 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3119 &ResultColumn, 0);
3120 SearchFileName = clang_getFileName(SearchFile);
3121 ResultFileName = clang_getFileName(ResultFile);
3122 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3123 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3124 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3125 clang_getCString(KindSpelling),
3126 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3127 clang_disposeString(SearchFileName);
3128 clang_disposeString(ResultFileName);
3129 clang_disposeString(KindSpelling);
3130 }
3131
Ted Kremeneke68fff62010-02-17 00:41:32 +00003132 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003133}
3134
Ted Kremenek73885552009-11-17 19:28:59 +00003135CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003136 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003137}
3138
3139unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003140 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003141}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003142
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003143unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003144 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3145}
3146
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003147unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003148 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3149}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003150
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003151unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003152 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3153}
3154
Douglas Gregor97b98722010-01-19 23:20:36 +00003155unsigned clang_isExpression(enum CXCursorKind K) {
3156 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3157}
3158
3159unsigned clang_isStatement(enum CXCursorKind K) {
3160 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3161}
3162
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003163unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3164 return K == CXCursor_TranslationUnit;
3165}
3166
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003167unsigned clang_isPreprocessing(enum CXCursorKind K) {
3168 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3169}
3170
Ted Kremenekad6eff62010-03-08 21:17:29 +00003171unsigned clang_isUnexposed(enum CXCursorKind K) {
3172 switch (K) {
3173 case CXCursor_UnexposedDecl:
3174 case CXCursor_UnexposedExpr:
3175 case CXCursor_UnexposedStmt:
3176 case CXCursor_UnexposedAttr:
3177 return true;
3178 default:
3179 return false;
3180 }
3181}
3182
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003183CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003184 return C.kind;
3185}
3186
Douglas Gregor98258af2010-01-18 22:46:11 +00003187CXSourceLocation clang_getCursorLocation(CXCursor C) {
3188 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003189 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003190 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003191 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3192 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003193 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003194 }
3195
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003196 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003197 std::pair<ObjCProtocolDecl *, SourceLocation> P
3198 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003199 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003200 }
3201
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003202 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003203 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3204 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003205 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003206 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003207
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003208 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003209 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003210 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003211 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003212
3213 case CXCursor_TemplateRef: {
3214 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3215 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3216 }
3217
Douglas Gregor69319002010-08-31 23:48:11 +00003218 case CXCursor_NamespaceRef: {
3219 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3220 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3221 }
3222
Douglas Gregora67e03f2010-09-09 21:42:20 +00003223 case CXCursor_MemberRef: {
3224 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3225 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3226 }
3227
Ted Kremenek3064ef92010-08-27 21:34:58 +00003228 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003229 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3230 if (!BaseSpec)
3231 return clang_getNullLocation();
3232
3233 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3234 return cxloc::translateSourceLocation(getCursorContext(C),
3235 TSInfo->getTypeLoc().getBeginLoc());
3236
3237 return cxloc::translateSourceLocation(getCursorContext(C),
3238 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003239 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003240
Douglas Gregor36897b02010-09-10 00:22:18 +00003241 case CXCursor_LabelRef: {
3242 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3243 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3244 }
3245
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003246 case CXCursor_OverloadedDeclRef:
3247 return cxloc::translateSourceLocation(getCursorContext(C),
3248 getCursorOverloadedDeclRef(C).second);
3249
Douglas Gregorf46034a2010-01-18 23:41:10 +00003250 default:
3251 // FIXME: Need a way to enumerate all non-reference cases.
3252 llvm_unreachable("Missed a reference kind");
3253 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003254 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003255
3256 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003257 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003258 getLocationFromExpr(getCursorExpr(C)));
3259
Douglas Gregor36897b02010-09-10 00:22:18 +00003260 if (clang_isStatement(C.kind))
3261 return cxloc::translateSourceLocation(getCursorContext(C),
3262 getCursorStmt(C)->getLocStart());
3263
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003264 if (C.kind == CXCursor_PreprocessingDirective) {
3265 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3266 return cxloc::translateSourceLocation(getCursorContext(C), L);
3267 }
Douglas Gregor48072312010-03-18 15:23:44 +00003268
3269 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003270 SourceLocation L
3271 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003272 return cxloc::translateSourceLocation(getCursorContext(C), L);
3273 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003274
3275 if (C.kind == CXCursor_MacroDefinition) {
3276 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3277 return cxloc::translateSourceLocation(getCursorContext(C), L);
3278 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003279
3280 if (C.kind == CXCursor_InclusionDirective) {
3281 SourceLocation L
3282 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3283 return cxloc::translateSourceLocation(getCursorContext(C), L);
3284 }
3285
Ted Kremenek9a700d22010-05-12 06:16:13 +00003286 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003287 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003288
Douglas Gregorf46034a2010-01-18 23:41:10 +00003289 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003290 SourceLocation Loc = D->getLocation();
3291 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3292 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003293 // FIXME: Multiple variables declared in a single declaration
3294 // currently lack the information needed to correctly determine their
3295 // ranges when accounting for the type-specifier. We use context
3296 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3297 // and if so, whether it is the first decl.
3298 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3299 if (!cxcursor::isFirstInDeclGroup(C))
3300 Loc = VD->getLocation();
3301 }
3302
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003303 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003304}
Douglas Gregora7bde202010-01-19 00:34:46 +00003305
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003306} // end extern "C"
3307
3308static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003309 if (clang_isReference(C.kind)) {
3310 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003311 case CXCursor_ObjCSuperClassRef:
3312 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003313
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003314 case CXCursor_ObjCProtocolRef:
3315 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003316
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003317 case CXCursor_ObjCClassRef:
3318 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003319
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003320 case CXCursor_TypeRef:
3321 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003322
3323 case CXCursor_TemplateRef:
3324 return getCursorTemplateRef(C).second;
3325
Douglas Gregor69319002010-08-31 23:48:11 +00003326 case CXCursor_NamespaceRef:
3327 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003328
3329 case CXCursor_MemberRef:
3330 return getCursorMemberRef(C).second;
3331
Ted Kremenek3064ef92010-08-27 21:34:58 +00003332 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003333 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003334
Douglas Gregor36897b02010-09-10 00:22:18 +00003335 case CXCursor_LabelRef:
3336 return getCursorLabelRef(C).second;
3337
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003338 case CXCursor_OverloadedDeclRef:
3339 return getCursorOverloadedDeclRef(C).second;
3340
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003341 default:
3342 // FIXME: Need a way to enumerate all non-reference cases.
3343 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003344 }
3345 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003346
3347 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003348 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003349
3350 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003351 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003352
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003353 if (C.kind == CXCursor_PreprocessingDirective)
3354 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003355
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003356 if (C.kind == CXCursor_MacroInstantiation)
3357 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003358
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003359 if (C.kind == CXCursor_MacroDefinition)
3360 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003361
3362 if (C.kind == CXCursor_InclusionDirective)
3363 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3364
Ted Kremenek007a7c92010-11-01 23:26:51 +00003365 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3366 Decl *D = cxcursor::getCursorDecl(C);
3367 SourceRange R = D->getSourceRange();
3368 // FIXME: Multiple variables declared in a single declaration
3369 // currently lack the information needed to correctly determine their
3370 // ranges when accounting for the type-specifier. We use context
3371 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3372 // and if so, whether it is the first decl.
3373 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3374 if (!cxcursor::isFirstInDeclGroup(C))
3375 R.setBegin(VD->getLocation());
3376 }
3377 return R;
3378 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003379 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003380
3381extern "C" {
3382
3383CXSourceRange clang_getCursorExtent(CXCursor C) {
3384 SourceRange R = getRawCursorExtent(C);
3385 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003386 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003387
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003388 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003389}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003390
3391CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003392 if (clang_isInvalid(C.kind))
3393 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003394
Ted Kremeneka60ed472010-11-16 08:15:36 +00003395 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003396 if (clang_isDeclaration(C.kind)) {
3397 Decl *D = getCursorDecl(C);
3398 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003399 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003400 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003401 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003402 if (ObjCForwardProtocolDecl *Protocols
3403 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003404 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003405 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3406 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3407 return MakeCXCursor(Property, tu);
3408
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003409 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003410 }
3411
Douglas Gregor97b98722010-01-19 23:20:36 +00003412 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003413 Expr *E = getCursorExpr(C);
3414 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003415 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003416 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003417
3418 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003419 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003420
Douglas Gregor97b98722010-01-19 23:20:36 +00003421 return clang_getNullCursor();
3422 }
3423
Douglas Gregor36897b02010-09-10 00:22:18 +00003424 if (clang_isStatement(C.kind)) {
3425 Stmt *S = getCursorStmt(C);
3426 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003427 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003428
3429 return clang_getNullCursor();
3430 }
3431
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003432 if (C.kind == CXCursor_MacroInstantiation) {
3433 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003434 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003435 }
3436
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003437 if (!clang_isReference(C.kind))
3438 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003439
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003440 switch (C.kind) {
3441 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003442 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003443
3444 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003445 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003446
3447 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003448 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003449
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003450 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003451 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003452
3453 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003454 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003455
Douglas Gregor69319002010-08-31 23:48:11 +00003456 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003457 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003458
Douglas Gregora67e03f2010-09-09 21:42:20 +00003459 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003460 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003461
Ted Kremenek3064ef92010-08-27 21:34:58 +00003462 case CXCursor_CXXBaseSpecifier: {
3463 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3464 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003465 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003466 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003467
Douglas Gregor36897b02010-09-10 00:22:18 +00003468 case CXCursor_LabelRef:
3469 // FIXME: We end up faking the "parent" declaration here because we
3470 // don't want to make CXCursor larger.
3471 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003472 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3473 .getTranslationUnitDecl(),
3474 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003475
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003476 case CXCursor_OverloadedDeclRef:
3477 return C;
3478
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003479 default:
3480 // We would prefer to enumerate all non-reference cursor kinds here.
3481 llvm_unreachable("Unhandled reference cursor kind");
3482 break;
3483 }
3484 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003485
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003486 return clang_getNullCursor();
3487}
3488
Douglas Gregorb6998662010-01-19 19:34:47 +00003489CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003490 if (clang_isInvalid(C.kind))
3491 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003492
Ted Kremeneka60ed472010-11-16 08:15:36 +00003493 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003494
Douglas Gregorb6998662010-01-19 19:34:47 +00003495 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003496 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003497 C = clang_getCursorReferenced(C);
3498 WasReference = true;
3499 }
3500
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003501 if (C.kind == CXCursor_MacroInstantiation)
3502 return clang_getCursorReferenced(C);
3503
Douglas Gregorb6998662010-01-19 19:34:47 +00003504 if (!clang_isDeclaration(C.kind))
3505 return clang_getNullCursor();
3506
3507 Decl *D = getCursorDecl(C);
3508 if (!D)
3509 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003510
Douglas Gregorb6998662010-01-19 19:34:47 +00003511 switch (D->getKind()) {
3512 // Declaration kinds that don't really separate the notions of
3513 // declaration and definition.
3514 case Decl::Namespace:
3515 case Decl::Typedef:
3516 case Decl::TemplateTypeParm:
3517 case Decl::EnumConstant:
3518 case Decl::Field:
3519 case Decl::ObjCIvar:
3520 case Decl::ObjCAtDefsField:
3521 case Decl::ImplicitParam:
3522 case Decl::ParmVar:
3523 case Decl::NonTypeTemplateParm:
3524 case Decl::TemplateTemplateParm:
3525 case Decl::ObjCCategoryImpl:
3526 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003527 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003528 case Decl::LinkageSpec:
3529 case Decl::ObjCPropertyImpl:
3530 case Decl::FileScopeAsm:
3531 case Decl::StaticAssert:
3532 case Decl::Block:
3533 return C;
3534
3535 // Declaration kinds that don't make any sense here, but are
3536 // nonetheless harmless.
3537 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003538 break;
3539
3540 // Declaration kinds for which the definition is not resolvable.
3541 case Decl::UnresolvedUsingTypename:
3542 case Decl::UnresolvedUsingValue:
3543 break;
3544
3545 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003546 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003547 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003548
3549 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003550 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003551
3552 case Decl::Enum:
3553 case Decl::Record:
3554 case Decl::CXXRecord:
3555 case Decl::ClassTemplateSpecialization:
3556 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003557 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003558 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003559 return clang_getNullCursor();
3560
3561 case Decl::Function:
3562 case Decl::CXXMethod:
3563 case Decl::CXXConstructor:
3564 case Decl::CXXDestructor:
3565 case Decl::CXXConversion: {
3566 const FunctionDecl *Def = 0;
3567 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003568 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003569 return clang_getNullCursor();
3570 }
3571
3572 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003573 // Ask the variable if it has a definition.
3574 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003575 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003576 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003577 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003578
Douglas Gregorb6998662010-01-19 19:34:47 +00003579 case Decl::FunctionTemplate: {
3580 const FunctionDecl *Def = 0;
3581 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003582 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003583 return clang_getNullCursor();
3584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585
Douglas Gregorb6998662010-01-19 19:34:47 +00003586 case Decl::ClassTemplate: {
3587 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003588 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003589 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003590 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003591 return clang_getNullCursor();
3592 }
3593
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003594 case Decl::Using:
3595 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003596 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003597
3598 case Decl::UsingShadow:
3599 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003600 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003601 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003602
3603 case Decl::ObjCMethod: {
3604 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3605 if (Method->isThisDeclarationADefinition())
3606 return C;
3607
3608 // Dig out the method definition in the associated
3609 // @implementation, if we have it.
3610 // FIXME: The ASTs should make finding the definition easier.
3611 if (ObjCInterfaceDecl *Class
3612 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3613 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3614 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3615 Method->isInstanceMethod()))
3616 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003617 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003618
3619 return clang_getNullCursor();
3620 }
3621
3622 case Decl::ObjCCategory:
3623 if (ObjCCategoryImplDecl *Impl
3624 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003625 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003626 return clang_getNullCursor();
3627
3628 case Decl::ObjCProtocol:
3629 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3630 return C;
3631 return clang_getNullCursor();
3632
3633 case Decl::ObjCInterface:
3634 // There are two notions of a "definition" for an Objective-C
3635 // class: the interface and its implementation. When we resolved a
3636 // reference to an Objective-C class, produce the @interface as
3637 // the definition; when we were provided with the interface,
3638 // produce the @implementation as the definition.
3639 if (WasReference) {
3640 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3641 return C;
3642 } else if (ObjCImplementationDecl *Impl
3643 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003644 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003645 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003646
Douglas Gregorb6998662010-01-19 19:34:47 +00003647 case Decl::ObjCProperty:
3648 // FIXME: We don't really know where to find the
3649 // ObjCPropertyImplDecls that implement this property.
3650 return clang_getNullCursor();
3651
3652 case Decl::ObjCCompatibleAlias:
3653 if (ObjCInterfaceDecl *Class
3654 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3655 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003656 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003657
Douglas Gregorb6998662010-01-19 19:34:47 +00003658 return clang_getNullCursor();
3659
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003660 case Decl::ObjCForwardProtocol:
3661 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003662 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003663
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003664 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003665 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003666 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003667
3668 case Decl::Friend:
3669 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003670 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003671 return clang_getNullCursor();
3672
3673 case Decl::FriendTemplate:
3674 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003675 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003676 return clang_getNullCursor();
3677 }
3678
3679 return clang_getNullCursor();
3680}
3681
3682unsigned clang_isCursorDefinition(CXCursor C) {
3683 if (!clang_isDeclaration(C.kind))
3684 return 0;
3685
3686 return clang_getCursorDefinition(C) == C;
3687}
3688
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003689unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003690 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003691 return 0;
3692
3693 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3694 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3695 return E->getNumDecls();
3696
3697 if (OverloadedTemplateStorage *S
3698 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3699 return S->size();
3700
3701 Decl *D = Storage.get<Decl*>();
3702 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003703 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003704 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3705 return Classes->size();
3706 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3707 return Protocols->protocol_size();
3708
3709 return 0;
3710}
3711
3712CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003713 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003714 return clang_getNullCursor();
3715
3716 if (index >= clang_getNumOverloadedDecls(cursor))
3717 return clang_getNullCursor();
3718
Ted Kremeneka60ed472010-11-16 08:15:36 +00003719 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003720 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3721 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003722 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003723
3724 if (OverloadedTemplateStorage *S
3725 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003726 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003727
3728 Decl *D = Storage.get<Decl*>();
3729 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3730 // FIXME: This is, unfortunately, linear time.
3731 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3732 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003733 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003734 }
3735
3736 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003737 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003738
3739 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003740 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003741
3742 return clang_getNullCursor();
3743}
3744
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003745void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003746 const char **startBuf,
3747 const char **endBuf,
3748 unsigned *startLine,
3749 unsigned *startColumn,
3750 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003751 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003752 assert(getCursorDecl(C) && "CXCursor has null decl");
3753 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003754 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3755 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003756
Steve Naroff4ade6d62009-09-23 17:52:52 +00003757 SourceManager &SM = FD->getASTContext().getSourceManager();
3758 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3759 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3760 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3761 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3762 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3763 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3764}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003765
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003766void clang_enableStackTraces(void) {
3767 llvm::sys::PrintStackTraceOnErrorSignal();
3768}
3769
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003770void clang_executeOnThread(void (*fn)(void*), void *user_data,
3771 unsigned stack_size) {
3772 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3773}
3774
Ted Kremenekfb480492010-01-13 21:46:36 +00003775} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003776
Ted Kremenekfb480492010-01-13 21:46:36 +00003777//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003778// Token-based Operations.
3779//===----------------------------------------------------------------------===//
3780
3781/* CXToken layout:
3782 * int_data[0]: a CXTokenKind
3783 * int_data[1]: starting token location
3784 * int_data[2]: token length
3785 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003786 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003787 * otherwise unused.
3788 */
3789extern "C" {
3790
3791CXTokenKind clang_getTokenKind(CXToken CXTok) {
3792 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3793}
3794
3795CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3796 switch (clang_getTokenKind(CXTok)) {
3797 case CXToken_Identifier:
3798 case CXToken_Keyword:
3799 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003800 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3801 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802
3803 case CXToken_Literal: {
3804 // We have stashed the starting pointer in the ptr_data field. Use it.
3805 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003806 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003808
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003809 case CXToken_Punctuation:
3810 case CXToken_Comment:
3811 break;
3812 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003813
3814 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003815 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003816 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003817 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003818 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003819
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3821 std::pair<FileID, unsigned> LocInfo
3822 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003823 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003824 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003825 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3826 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003827 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003828
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003829 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003830}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003831
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003832CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003833 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834 if (!CXXUnit)
3835 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3838 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3839}
3840
3841CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003842 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003843 if (!CXXUnit)
3844 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003845
3846 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003847 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3848}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003849
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003850void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3851 CXToken **Tokens, unsigned *NumTokens) {
3852 if (Tokens)
3853 *Tokens = 0;
3854 if (NumTokens)
3855 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003856
Ted Kremeneka60ed472010-11-16 08:15:36 +00003857 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003858 if (!CXXUnit || !Tokens || !NumTokens)
3859 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003860
Douglas Gregorbdf60622010-03-05 21:16:25 +00003861 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3862
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003863 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 if (R.isInvalid())
3865 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003866
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003867 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3868 std::pair<FileID, unsigned> BeginLocInfo
3869 = SourceMgr.getDecomposedLoc(R.getBegin());
3870 std::pair<FileID, unsigned> EndLocInfo
3871 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003872
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003873 // Cannot tokenize across files.
3874 if (BeginLocInfo.first != EndLocInfo.first)
3875 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003876
3877 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003878 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003879 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003880 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003881 if (Invalid)
3882 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003883
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003884 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3885 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003886 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003887 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003888
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003889 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003890 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891 llvm::SmallVector<CXToken, 32> CXTokens;
3892 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003893 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 do {
3895 // Lex the next token
3896 Lex.LexFromRawLexer(Tok);
3897 if (Tok.is(tok::eof))
3898 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003899
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003900 // Initialize the CXToken.
3901 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003902
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003903 // - Common fields
3904 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3905 CXTok.int_data[2] = Tok.getLength();
3906 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003907
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003908 // - Kind-specific fields
3909 if (Tok.isLiteral()) {
3910 CXTok.int_data[0] = CXToken_Literal;
3911 CXTok.ptr_data = (void *)Tok.getLiteralData();
3912 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003913 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003914 std::pair<FileID, unsigned> LocInfo
3915 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003916 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003917 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003918 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3919 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003920 return;
3921
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003922 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003923 IdentifierInfo *II
3924 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003925
David Chisnall096428b2010-10-13 21:44:48 +00003926 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003927 CXTok.int_data[0] = CXToken_Keyword;
3928 }
3929 else {
3930 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3931 CXToken_Identifier
3932 : CXToken_Keyword;
3933 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003934 CXTok.ptr_data = II;
3935 } else if (Tok.is(tok::comment)) {
3936 CXTok.int_data[0] = CXToken_Comment;
3937 CXTok.ptr_data = 0;
3938 } else {
3939 CXTok.int_data[0] = CXToken_Punctuation;
3940 CXTok.ptr_data = 0;
3941 }
3942 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003943 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003944 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003945
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003946 if (CXTokens.empty())
3947 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003948
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003949 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3950 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3951 *NumTokens = CXTokens.size();
3952}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003953
Ted Kremenek6db61092010-05-05 00:55:15 +00003954void clang_disposeTokens(CXTranslationUnit TU,
3955 CXToken *Tokens, unsigned NumTokens) {
3956 free(Tokens);
3957}
3958
3959} // end: extern "C"
3960
3961//===----------------------------------------------------------------------===//
3962// Token annotation APIs.
3963//===----------------------------------------------------------------------===//
3964
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003965typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003966static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3967 CXCursor parent,
3968 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003969namespace {
3970class AnnotateTokensWorker {
3971 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003972 CXToken *Tokens;
3973 CXCursor *Cursors;
3974 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003975 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003976 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003977 CursorVisitor AnnotateVis;
3978 SourceManager &SrcMgr;
3979
3980 bool MoreTokens() const { return TokIdx < NumTokens; }
3981 unsigned NextToken() const { return TokIdx; }
3982 void AdvanceToken() { ++TokIdx; }
3983 SourceLocation GetTokenLoc(unsigned tokI) {
3984 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3985 }
3986
Ted Kremenek6db61092010-05-05 00:55:15 +00003987public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003988 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003989 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003990 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003991 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003992 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003993 AnnotateVis(tu,
3994 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003995 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003996 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003997
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003998 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003999 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004000 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004001 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004002 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004003 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004004};
4005}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004006
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004007void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4008 // Walk the AST within the region of interest, annotating tokens
4009 // along the way.
4010 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004011
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004012 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4013 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004014 if (Pos != Annotated.end() &&
4015 (clang_isInvalid(Cursors[I].kind) ||
4016 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004017 Cursors[I] = Pos->second;
4018 }
4019
4020 // Finish up annotating any tokens left.
4021 if (!MoreTokens())
4022 return;
4023
4024 const CXCursor &C = clang_getNullCursor();
4025 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4026 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4027 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004028 }
4029}
4030
Ted Kremenek6db61092010-05-05 00:55:15 +00004031enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004032AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004033 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004034 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004035 if (cursorRange.isInvalid())
4036 return CXChildVisit_Recurse;
4037
Douglas Gregor4419b672010-10-21 06:10:04 +00004038 if (clang_isPreprocessing(cursor.kind)) {
4039 // For macro instantiations, just note where the beginning of the macro
4040 // instantiation occurs.
4041 if (cursor.kind == CXCursor_MacroInstantiation) {
4042 Annotated[Loc.int_data] = cursor;
4043 return CXChildVisit_Recurse;
4044 }
4045
Douglas Gregor4419b672010-10-21 06:10:04 +00004046 // Items in the preprocessing record are kept separate from items in
4047 // declarations, so we keep a separate token index.
4048 unsigned SavedTokIdx = TokIdx;
4049 TokIdx = PreprocessingTokIdx;
4050
4051 // Skip tokens up until we catch up to the beginning of the preprocessing
4052 // entry.
4053 while (MoreTokens()) {
4054 const unsigned I = NextToken();
4055 SourceLocation TokLoc = GetTokenLoc(I);
4056 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4057 case RangeBefore:
4058 AdvanceToken();
4059 continue;
4060 case RangeAfter:
4061 case RangeOverlap:
4062 break;
4063 }
4064 break;
4065 }
4066
4067 // Look at all of the tokens within this range.
4068 while (MoreTokens()) {
4069 const unsigned I = NextToken();
4070 SourceLocation TokLoc = GetTokenLoc(I);
4071 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4072 case RangeBefore:
4073 assert(0 && "Infeasible");
4074 case RangeAfter:
4075 break;
4076 case RangeOverlap:
4077 Cursors[I] = cursor;
4078 AdvanceToken();
4079 continue;
4080 }
4081 break;
4082 }
4083
4084 // Save the preprocessing token index; restore the non-preprocessing
4085 // token index.
4086 PreprocessingTokIdx = TokIdx;
4087 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004088 return CXChildVisit_Recurse;
4089 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004090
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004091 if (cursorRange.isInvalid())
4092 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004093
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004094 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4095
Ted Kremeneka333c662010-05-12 05:29:33 +00004096 // Adjust the annotated range based specific declarations.
4097 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4098 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004099 Decl *D = cxcursor::getCursorDecl(cursor);
4100 // Don't visit synthesized ObjC methods, since they have no syntatic
4101 // representation in the source.
4102 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4103 if (MD->isSynthesized())
4104 return CXChildVisit_Continue;
4105 }
4106 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004107 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4108 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004109 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004110 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004111 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004112 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004113 }
4114 }
4115 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004116
Ted Kremenek3f404602010-08-14 01:14:06 +00004117 // If the location of the cursor occurs within a macro instantiation, record
4118 // the spelling location of the cursor in our annotation map. We can then
4119 // paper over the token labelings during a post-processing step to try and
4120 // get cursor mappings for tokens that are the *arguments* of a macro
4121 // instantiation.
4122 if (L.isMacroID()) {
4123 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4124 // Only invalidate the old annotation if it isn't part of a preprocessing
4125 // directive. Here we assume that the default construction of CXCursor
4126 // results in CXCursor.kind being an initialized value (i.e., 0). If
4127 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004128
Ted Kremenek3f404602010-08-14 01:14:06 +00004129 CXCursor &oldC = Annotated[rawEncoding];
4130 if (!clang_isPreprocessing(oldC.kind))
4131 oldC = cursor;
4132 }
4133
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004134 const enum CXCursorKind K = clang_getCursorKind(parent);
4135 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004136 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4137 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004138
4139 while (MoreTokens()) {
4140 const unsigned I = NextToken();
4141 SourceLocation TokLoc = GetTokenLoc(I);
4142 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4143 case RangeBefore:
4144 Cursors[I] = updateC;
4145 AdvanceToken();
4146 continue;
4147 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004148 case RangeOverlap:
4149 break;
4150 }
4151 break;
4152 }
4153
4154 // Visit children to get their cursor information.
4155 const unsigned BeforeChildren = NextToken();
4156 VisitChildren(cursor);
4157 const unsigned AfterChildren = NextToken();
4158
4159 // Adjust 'Last' to the last token within the extent of the cursor.
4160 while (MoreTokens()) {
4161 const unsigned I = NextToken();
4162 SourceLocation TokLoc = GetTokenLoc(I);
4163 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4164 case RangeBefore:
4165 assert(0 && "Infeasible");
4166 case RangeAfter:
4167 break;
4168 case RangeOverlap:
4169 Cursors[I] = updateC;
4170 AdvanceToken();
4171 continue;
4172 }
4173 break;
4174 }
4175 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004176
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004177 // Scan the tokens that are at the beginning of the cursor, but are not
4178 // capture by the child cursors.
4179
4180 // For AST elements within macros, rely on a post-annotate pass to
4181 // to correctly annotate the tokens with cursors. Otherwise we can
4182 // get confusing results of having tokens that map to cursors that really
4183 // are expanded by an instantiation.
4184 if (L.isMacroID())
4185 cursor = clang_getNullCursor();
4186
4187 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4188 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4189 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004190
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004191 Cursors[I] = cursor;
4192 }
4193 // Scan the tokens that are at the end of the cursor, but are not captured
4194 // but the child cursors.
4195 for (unsigned I = AfterChildren; I != Last; ++I)
4196 Cursors[I] = cursor;
4197
4198 TokIdx = Last;
4199 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004200}
4201
Ted Kremenek6db61092010-05-05 00:55:15 +00004202static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4203 CXCursor parent,
4204 CXClientData client_data) {
4205 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4206}
4207
Ted Kremenekab979612010-11-11 08:05:23 +00004208// This gets run a separate thread to avoid stack blowout.
4209static void runAnnotateTokensWorker(void *UserData) {
4210 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4211}
4212
Ted Kremenek6db61092010-05-05 00:55:15 +00004213extern "C" {
4214
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004215void clang_annotateTokens(CXTranslationUnit TU,
4216 CXToken *Tokens, unsigned NumTokens,
4217 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004218
4219 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004220 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004221
Douglas Gregor4419b672010-10-21 06:10:04 +00004222 // Any token we don't specifically annotate will have a NULL cursor.
4223 CXCursor C = clang_getNullCursor();
4224 for (unsigned I = 0; I != NumTokens; ++I)
4225 Cursors[I] = C;
4226
Ted Kremeneka60ed472010-11-16 08:15:36 +00004227 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004228 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004229 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004230
Douglas Gregorbdf60622010-03-05 21:16:25 +00004231 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232
Douglas Gregor0396f462010-03-19 05:22:59 +00004233 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004234 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004235 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4236 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004237 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4238 clang_getTokenLocation(TU,
4239 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004240
Douglas Gregor0396f462010-03-19 05:22:59 +00004241 // A mapping from the source locations found when re-lexing or traversing the
4242 // region of interest to the corresponding cursors.
4243 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004244
4245 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004246 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004247 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4248 std::pair<FileID, unsigned> BeginLocInfo
4249 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4250 std::pair<FileID, unsigned> EndLocInfo
4251 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004254 bool Invalid = false;
4255 if (BeginLocInfo.first == EndLocInfo.first &&
4256 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4257 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004258 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4259 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004260 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004261 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004262 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004263
4264 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004265 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004266 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004267 Token Tok;
4268 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004269
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004270 reprocess:
4271 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4272 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004273 // don't see it while preprocessing these tokens later, but keep track
4274 // of all of the token locations inside this preprocessing directive so
4275 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004276 //
4277 // FIXME: Some simple tests here could identify macro definitions and
4278 // #undefs, to provide specific cursor kinds for those.
4279 std::vector<SourceLocation> Locations;
4280 do {
4281 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004282 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004283 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004284
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004285 using namespace cxcursor;
4286 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004287 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4288 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004289 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004290 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4291 Annotated[Locations[I].getRawEncoding()] = Cursor;
4292 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004293
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004294 if (Tok.isAtStartOfLine())
4295 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004296
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004297 continue;
4298 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004299
Douglas Gregor48072312010-03-18 15:23:44 +00004300 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004301 break;
4302 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004303 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004304
Douglas Gregor0396f462010-03-19 05:22:59 +00004305 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004306 // a specific cursor.
4307 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004308 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004309
4310 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004311 // FIXME: We use a ridiculous stack size here because the data-recursion
4312 // algorithm uses a large stack frame than the non-data recursive version,
4313 // and AnnotationTokensWorker currently transforms the data-recursion
4314 // algorithm back into a traditional recursion by explicitly calling
4315 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004316 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004317 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4318 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004319 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4320 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004321}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004322} // end: extern "C"
4323
4324//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004325// Operations for querying linkage of a cursor.
4326//===----------------------------------------------------------------------===//
4327
4328extern "C" {
4329CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004330 if (!clang_isDeclaration(cursor.kind))
4331 return CXLinkage_Invalid;
4332
Ted Kremenek16b42592010-03-03 06:36:57 +00004333 Decl *D = cxcursor::getCursorDecl(cursor);
4334 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4335 switch (ND->getLinkage()) {
4336 case NoLinkage: return CXLinkage_NoLinkage;
4337 case InternalLinkage: return CXLinkage_Internal;
4338 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4339 case ExternalLinkage: return CXLinkage_External;
4340 };
4341
4342 return CXLinkage_Invalid;
4343}
4344} // end: extern "C"
4345
4346//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004347// Operations for querying language of a cursor.
4348//===----------------------------------------------------------------------===//
4349
4350static CXLanguageKind getDeclLanguage(const Decl *D) {
4351 switch (D->getKind()) {
4352 default:
4353 break;
4354 case Decl::ImplicitParam:
4355 case Decl::ObjCAtDefsField:
4356 case Decl::ObjCCategory:
4357 case Decl::ObjCCategoryImpl:
4358 case Decl::ObjCClass:
4359 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004360 case Decl::ObjCForwardProtocol:
4361 case Decl::ObjCImplementation:
4362 case Decl::ObjCInterface:
4363 case Decl::ObjCIvar:
4364 case Decl::ObjCMethod:
4365 case Decl::ObjCProperty:
4366 case Decl::ObjCPropertyImpl:
4367 case Decl::ObjCProtocol:
4368 return CXLanguage_ObjC;
4369 case Decl::CXXConstructor:
4370 case Decl::CXXConversion:
4371 case Decl::CXXDestructor:
4372 case Decl::CXXMethod:
4373 case Decl::CXXRecord:
4374 case Decl::ClassTemplate:
4375 case Decl::ClassTemplatePartialSpecialization:
4376 case Decl::ClassTemplateSpecialization:
4377 case Decl::Friend:
4378 case Decl::FriendTemplate:
4379 case Decl::FunctionTemplate:
4380 case Decl::LinkageSpec:
4381 case Decl::Namespace:
4382 case Decl::NamespaceAlias:
4383 case Decl::NonTypeTemplateParm:
4384 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004385 case Decl::TemplateTemplateParm:
4386 case Decl::TemplateTypeParm:
4387 case Decl::UnresolvedUsingTypename:
4388 case Decl::UnresolvedUsingValue:
4389 case Decl::Using:
4390 case Decl::UsingDirective:
4391 case Decl::UsingShadow:
4392 return CXLanguage_CPlusPlus;
4393 }
4394
4395 return CXLanguage_C;
4396}
4397
4398extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004399
4400enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4401 if (clang_isDeclaration(cursor.kind))
4402 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4403 if (D->hasAttr<UnavailableAttr>() ||
4404 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4405 return CXAvailability_Available;
4406
4407 if (D->hasAttr<DeprecatedAttr>())
4408 return CXAvailability_Deprecated;
4409 }
4410
4411 return CXAvailability_Available;
4412}
4413
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004414CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4415 if (clang_isDeclaration(cursor.kind))
4416 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4417
4418 return CXLanguage_Invalid;
4419}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004420
4421CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4422 if (clang_isDeclaration(cursor.kind)) {
4423 if (Decl *D = getCursorDecl(cursor)) {
4424 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004425 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004426 }
4427 }
4428
4429 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4430 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004431 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004432 }
4433
4434 return clang_getNullCursor();
4435}
4436
4437CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4438 if (clang_isDeclaration(cursor.kind)) {
4439 if (Decl *D = getCursorDecl(cursor)) {
4440 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004441 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004442 }
4443 }
4444
4445 // FIXME: Note that we can't easily compute the lexical context of a
4446 // statement or expression, so we return nothing.
4447 return clang_getNullCursor();
4448}
4449
Douglas Gregor9f592342010-10-01 20:25:15 +00004450static void CollectOverriddenMethods(DeclContext *Ctx,
4451 ObjCMethodDecl *Method,
4452 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4453 if (!Ctx)
4454 return;
4455
4456 // If we have a class or category implementation, jump straight to the
4457 // interface.
4458 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4459 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4460
4461 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4462 if (!Container)
4463 return;
4464
4465 // Check whether we have a matching method at this level.
4466 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4467 Method->isInstanceMethod()))
4468 if (Method != Overridden) {
4469 // We found an override at this level; there is no need to look
4470 // into other protocols or categories.
4471 Methods.push_back(Overridden);
4472 return;
4473 }
4474
4475 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4476 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4477 PEnd = Protocol->protocol_end();
4478 P != PEnd; ++P)
4479 CollectOverriddenMethods(*P, Method, Methods);
4480 }
4481
4482 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4483 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4484 PEnd = Category->protocol_end();
4485 P != PEnd; ++P)
4486 CollectOverriddenMethods(*P, Method, Methods);
4487 }
4488
4489 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4490 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4491 PEnd = Interface->protocol_end();
4492 P != PEnd; ++P)
4493 CollectOverriddenMethods(*P, Method, Methods);
4494
4495 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4496 Category; Category = Category->getNextClassCategory())
4497 CollectOverriddenMethods(Category, Method, Methods);
4498
4499 // We only look into the superclass if we haven't found anything yet.
4500 if (Methods.empty())
4501 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4502 return CollectOverriddenMethods(Super, Method, Methods);
4503 }
4504}
4505
4506void clang_getOverriddenCursors(CXCursor cursor,
4507 CXCursor **overridden,
4508 unsigned *num_overridden) {
4509 if (overridden)
4510 *overridden = 0;
4511 if (num_overridden)
4512 *num_overridden = 0;
4513 if (!overridden || !num_overridden)
4514 return;
4515
4516 if (!clang_isDeclaration(cursor.kind))
4517 return;
4518
4519 Decl *D = getCursorDecl(cursor);
4520 if (!D)
4521 return;
4522
4523 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004524 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004525 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4526 *num_overridden = CXXMethod->size_overridden_methods();
4527 if (!*num_overridden)
4528 return;
4529
4530 *overridden = new CXCursor [*num_overridden];
4531 unsigned I = 0;
4532 for (CXXMethodDecl::method_iterator
4533 M = CXXMethod->begin_overridden_methods(),
4534 MEnd = CXXMethod->end_overridden_methods();
4535 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004536 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004537 return;
4538 }
4539
4540 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4541 if (!Method)
4542 return;
4543
4544 // Handle Objective-C methods.
4545 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4546 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4547
4548 if (Methods.empty())
4549 return;
4550
4551 *num_overridden = Methods.size();
4552 *overridden = new CXCursor [Methods.size()];
4553 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004554 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004555}
4556
4557void clang_disposeOverriddenCursors(CXCursor *overridden) {
4558 delete [] overridden;
4559}
4560
Douglas Gregorecdcb882010-10-20 22:00:55 +00004561CXFile clang_getIncludedFile(CXCursor cursor) {
4562 if (cursor.kind != CXCursor_InclusionDirective)
4563 return 0;
4564
4565 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4566 return (void *)ID->getFile();
4567}
4568
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004569} // end: extern "C"
4570
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004571
4572//===----------------------------------------------------------------------===//
4573// C++ AST instrospection.
4574//===----------------------------------------------------------------------===//
4575
4576extern "C" {
4577unsigned clang_CXXMethod_isStatic(CXCursor C) {
4578 if (!clang_isDeclaration(C.kind))
4579 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004580
4581 CXXMethodDecl *Method = 0;
4582 Decl *D = cxcursor::getCursorDecl(C);
4583 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4584 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4585 else
4586 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4587 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004588}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004589
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004590} // end: extern "C"
4591
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004592//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004593// Attribute introspection.
4594//===----------------------------------------------------------------------===//
4595
4596extern "C" {
4597CXType clang_getIBOutletCollectionType(CXCursor C) {
4598 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004599 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004600
4601 IBOutletCollectionAttr *A =
4602 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4603
Ted Kremeneka60ed472010-11-16 08:15:36 +00004604 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004605}
4606} // end: extern "C"
4607
4608//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004609// Misc. utility functions.
4610//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004611
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004612/// Default to using an 8 MB stack size on "safety" threads.
4613static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004614
4615namespace clang {
4616
4617bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004618 void (*Fn)(void*), void *UserData,
4619 unsigned Size) {
4620 if (!Size)
4621 Size = GetSafetyThreadStackSize();
4622 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004623 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4624 return CRC.RunSafely(Fn, UserData);
4625}
4626
4627unsigned GetSafetyThreadStackSize() {
4628 return SafetyStackThreadSize;
4629}
4630
4631void SetSafetyThreadStackSize(unsigned Value) {
4632 SafetyStackThreadSize = Value;
4633}
4634
4635}
4636
Ted Kremenek04bb7162010-01-22 22:44:15 +00004637extern "C" {
4638
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004639CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004640 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004641}
4642
4643} // end: extern "C"