blob: 717db17f0ed5f8942d559a1adc4695b71103d002 [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,
139 DeclRefExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000140protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000141 void *dataA;
142 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000143 CXCursor parent;
144 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000145 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
146 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147public:
148 Kind getKind() const { return K; }
149 const CXCursor &getParent() const { return parent; }
150 static bool classof(VisitorJob *VJ) { return true; }
151};
152
153typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
154
Douglas Gregorb1373d02010-01-20 20:59:29 +0000155// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000156class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000157 public TypeLocVisitor<CursorVisitor, bool>,
158 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000159{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000160 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000161 CXTranslationUnit TU;
162 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000163
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000164 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000166
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 /// \brief The declaration that serves at the parent of any statement or
168 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000169 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000175 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000177 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
178 // to the visitor. Declarations with a PCH level greater than this value will
179 // be suppressed.
180 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181
182 /// \brief When valid, a source range to which the cursor should restrict
183 /// its search.
184 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000186 // FIXME: Eventually remove. This part of a hack to support proper
187 // iteration over all Decls contained lexically within an ObjC container.
188 DeclContext::decl_iterator *DI_current;
189 DeclContext::decl_iterator DE_current;
190
Ted Kremenekd1ded662010-11-15 23:31:32 +0000191 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
192 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
193 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
194
Douglas Gregorb1373d02010-01-20 20:59:29 +0000195 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000196 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000197 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000198
199 /// \brief Determine whether this particular source range comes before, comes
200 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000201 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000202 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000203 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
204
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000205 class SetParentRAII {
206 CXCursor &Parent;
207 Decl *&StmtParent;
208 CXCursor OldParent;
209
210 public:
211 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
212 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
213 {
214 Parent = NewParent;
215 if (clang_isDeclaration(Parent.kind))
216 StmtParent = getCursorDecl(Parent);
217 }
218
219 ~SetParentRAII() {
220 Parent = OldParent;
221 if (clang_isDeclaration(Parent.kind))
222 StmtParent = getCursorDecl(Parent);
223 }
224 };
225
Steve Naroff89922f82009-08-31 00:59:03 +0000226public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000227 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
228 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000229 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000230 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000231 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
232 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000233 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
234 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000235 {
236 Parent.kind = CXCursor_NoDeclFound;
237 Parent.data[0] = 0;
238 Parent.data[1] = 0;
239 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000240 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242
Ted Kremenekd1ded662010-11-15 23:31:32 +0000243 ~CursorVisitor() {
244 // Free the pre-allocated worklists for data-recursion.
245 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
246 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
247 delete *I;
248 }
249 }
250
Ted Kremeneka60ed472010-11-16 08:15:36 +0000251 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
252 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000253
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000254 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000255
256 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
257 getPreprocessedEntities();
258
Douglas Gregorb1373d02010-01-20 20:59:29 +0000259 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000260
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000261 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000262 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000263 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000264 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000265 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000266 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000267 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
268 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000270 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000271 bool VisitClassTemplatePartialSpecializationDecl(
272 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000273 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000274 bool VisitEnumConstantDecl(EnumConstantDecl *D);
275 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
276 bool VisitFunctionDecl(FunctionDecl *ND);
277 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000278 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000279 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000280 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000281 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000282 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000283 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
284 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
285 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
286 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000287 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
289 bool VisitObjCImplDecl(ObjCImplDecl *D);
290 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
291 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000292 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
293 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
294 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000295 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000296 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000297 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000298 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000299 bool VisitUsingDecl(UsingDecl *D);
300 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
301 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000302
Douglas Gregor01829d32010-08-31 14:41:23 +0000303 // Name visitor
304 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000305 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000306
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000307 // Template visitors
308 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000309 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000310 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
311
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000312 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000313 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000315 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000316 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
317 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000318 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000319 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000320 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
322 bool VisitPointerTypeLoc(PointerTypeLoc TL);
323 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
324 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
325 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
326 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000327 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000329 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000330 // FIXME: Implement visitors here when the unimplemented TypeLocs get
331 // implemented
332 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
333 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000334
Douglas Gregora59e3902010-01-21 23:27:09 +0000335 // Statement visitors
336 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000337
Douglas Gregor336fd812010-01-23 00:40:08 +0000338 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000339 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000340 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000341 bool VisitAddrLabelExpr(AddrLabelExpr *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 Gregor36897b02010-09-10 00:22:18 +00001484bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1485 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1486}
1487
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001488bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1489 // Visit the designators.
1490 typedef DesignatedInitExpr::Designator Designator;
1491 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1492 DEnd = E->designators_end();
1493 D != DEnd; ++D) {
1494 if (D->isFieldDesignator()) {
1495 if (FieldDecl *Field = D->getField())
1496 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1497 return true;
1498
1499 continue;
1500 }
1501
1502 if (D->isArrayDesignator()) {
1503 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1504 return true;
1505
1506 continue;
1507 }
1508
1509 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1510 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1511 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1512 return true;
1513 }
1514
1515 // Visit the initializer value itself.
1516 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1517}
1518
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001519bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1520 if (E->isTypeOperand()) {
1521 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1522 return Visit(TSInfo->getTypeLoc());
1523
1524 return false;
1525 }
1526
1527 return VisitExpr(E);
1528}
1529
Douglas Gregorab6677e2010-09-08 00:15:04 +00001530bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1531 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1532 return Visit(TSInfo->getTypeLoc());
1533
1534 return false;
1535}
1536
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001537bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1538 // Visit base expression.
1539 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1540 return true;
1541
1542 // Visit the nested-name-specifier.
1543 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1544 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1545 return true;
1546
1547 // Visit the scope type that looks disturbingly like the nested-name-specifier
1548 // but isn't.
1549 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1550 if (Visit(TSInfo->getTypeLoc()))
1551 return true;
1552
1553 // Visit the name of the type being destroyed.
1554 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1555 if (Visit(TSInfo->getTypeLoc()))
1556 return true;
1557
1558 return false;
1559}
1560
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001561bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1562 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1563}
1564
Douglas Gregorbfebed22010-09-03 17:24:10 +00001565bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1566 DependentScopeDeclRefExpr *E) {
1567 // Visit the nested-name-specifier.
1568 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1569 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1570 return true;
1571
1572 // Visit the declaration name.
1573 if (VisitDeclarationNameInfo(E->getNameInfo()))
1574 return true;
1575
1576 // Visit the explicitly-specified template arguments.
1577 if (const ExplicitTemplateArgumentList *ArgList
1578 = E->getOptionalExplicitTemplateArgs()) {
1579 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1580 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1581 Arg != ArgEnd; ++Arg) {
1582 if (VisitTemplateArgumentLoc(*Arg))
1583 return true;
1584 }
1585 }
1586
1587 return false;
1588}
1589
Douglas Gregor25d63622010-09-03 17:35:34 +00001590bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1591 CXXDependentScopeMemberExpr *E) {
1592 // Visit the base expression, if there is one.
1593 if (!E->isImplicitAccess() &&
1594 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1595 return true;
1596
1597 // Visit the nested-name-specifier.
1598 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1599 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1600 return true;
1601
1602 // Visit the declaration name.
1603 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1604 return true;
1605
1606 // Visit the explicitly-specified template arguments.
1607 if (const ExplicitTemplateArgumentList *ArgList
1608 = E->getOptionalExplicitTemplateArgs()) {
1609 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1610 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1611 Arg != ArgEnd; ++Arg) {
1612 if (VisitTemplateArgumentLoc(*Arg))
1613 return true;
1614 }
1615 }
1616
1617 return false;
1618}
1619
Ted Kremenek09dfa372010-02-18 05:46:33 +00001620bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001621 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1622 i != e; ++i)
1623 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001624 return true;
1625
1626 return false;
1627}
1628
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001629//===----------------------------------------------------------------------===//
1630// Data-recursive visitor methods.
1631//===----------------------------------------------------------------------===//
1632
Ted Kremenek28a71942010-11-13 00:36:47 +00001633namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001634#define DEF_JOB(NAME, DATA, KIND)\
1635class NAME : public VisitorJob {\
1636public:\
1637 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1638 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1639 DATA *get() const { return static_cast<DATA*>(dataA); }\
1640};
1641
1642DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1643DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001644DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001645DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1646#undef DEF_JOB
1647
1648class DeclVisit : public VisitorJob {
1649public:
1650 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1651 VisitorJob(parent, VisitorJob::DeclVisitKind,
1652 d, isFirst ? (void*) 1 : (void*) 0) {}
1653 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001654 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001655 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001656 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001657 bool isFirst() const { return dataB ? true : false; }
1658};
1659
1660class TypeLocVisit : public VisitorJob {
1661public:
1662 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1663 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1664 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1665
1666 static bool classof(const VisitorJob *VJ) {
1667 return VJ->getKind() == TypeLocVisitKind;
1668 }
1669
Ted Kremenek82f3c502010-11-15 22:23:26 +00001670 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001671 QualType T = QualType::getFromOpaquePtr(dataA);
1672 return TypeLoc(T, dataB);
1673 }
1674};
1675
Ted Kremenek28a71942010-11-13 00:36:47 +00001676class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1677 VisitorWorkList &WL;
1678 CXCursor Parent;
1679public:
1680 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1681 : WL(wl), Parent(parent) {}
1682
Ted Kremenek73d15c42010-11-13 01:09:29 +00001683 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001684 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001685 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001686 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1687 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001688 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001689 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001690 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001691 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001692 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001693 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001694 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1695 void VisitForStmt(ForStmt *FS);
1696 void VisitIfStmt(IfStmt *If);
1697 void VisitInitListExpr(InitListExpr *IE);
1698 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001699 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001700 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1701 void VisitOverloadExpr(OverloadExpr *E);
1702 void VisitStmt(Stmt *S);
1703 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001704 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001705 void VisitWhileStmt(WhileStmt *W);
1706 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001707 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001708
1709private:
1710 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001711 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001712 void AddTypeLoc(TypeSourceInfo *TI);
1713 void EnqueueChildren(Stmt *S);
1714};
1715} // end anonyous namespace
1716
1717void EnqueueVisitor::AddStmt(Stmt *S) {
1718 if (S)
1719 WL.push_back(StmtVisit(S, Parent));
1720}
Ted Kremenek035dc412010-11-13 00:36:50 +00001721void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001722 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001723 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001724}
1725void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1726 if (TI)
1727 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1728 }
1729void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001730 unsigned size = WL.size();
1731 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1732 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001733 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001734 }
1735 if (size == WL.size())
1736 return;
1737 // Now reverse the entries we just added. This will match the DFS
1738 // ordering performed by the worklist.
1739 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1740 std::reverse(I, E);
1741}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001742void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1743 AddDecl(B->getBlockDecl());
1744}
Ted Kremenek28a71942010-11-13 00:36:47 +00001745void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1746 EnqueueChildren(E);
1747 AddTypeLoc(E->getTypeSourceInfo());
1748}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001749void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1750 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1751 E = S->body_rend(); I != E; ++I) {
1752 AddStmt(*I);
1753 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001754}
1755void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1756 // Enqueue the initializer or constructor arguments.
1757 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1758 AddStmt(E->getConstructorArg(I-1));
1759 // Enqueue the array size, if any.
1760 AddStmt(E->getArraySize());
1761 // Enqueue the allocated type.
1762 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1763 // Enqueue the placement arguments.
1764 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1765 AddStmt(E->getPlacementArg(I-1));
1766}
Ted Kremenek28a71942010-11-13 00:36:47 +00001767void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001768 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1769 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001770 AddStmt(CE->getCallee());
1771 AddStmt(CE->getArg(0));
1772}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001773void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1774 EnqueueChildren(E);
1775 AddTypeLoc(E->getTypeSourceInfo());
1776}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001777void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1778 EnqueueChildren(E);
1779 if (E->isTypeOperand())
1780 AddTypeLoc(E->getTypeOperandSourceInfo());
1781}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001782
1783void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1784 *E) {
1785 EnqueueChildren(E);
1786 AddTypeLoc(E->getTypeSourceInfo());
1787}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001788void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1789 WL.push_back(DeclRefExprParts(DR, Parent));
1790}
Ted Kremenek035dc412010-11-13 00:36:50 +00001791void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1792 unsigned size = WL.size();
1793 bool isFirst = true;
1794 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1795 D != DEnd; ++D) {
1796 AddDecl(*D, isFirst);
1797 isFirst = false;
1798 }
1799 if (size == WL.size())
1800 return;
1801 // Now reverse the entries we just added. This will match the DFS
1802 // ordering performed by the worklist.
1803 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1804 std::reverse(I, E);
1805}
Ted Kremenek28a71942010-11-13 00:36:47 +00001806void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1807 EnqueueChildren(E);
1808 AddTypeLoc(E->getTypeInfoAsWritten());
1809}
1810void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1811 AddStmt(FS->getBody());
1812 AddStmt(FS->getInc());
1813 AddStmt(FS->getCond());
1814 AddDecl(FS->getConditionVariable());
1815 AddStmt(FS->getInit());
1816}
1817void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1818 AddStmt(If->getElse());
1819 AddStmt(If->getThen());
1820 AddStmt(If->getCond());
1821 AddDecl(If->getConditionVariable());
1822}
1823void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1824 // We care about the syntactic form of the initializer list, only.
1825 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1826 IE = Syntactic;
1827 EnqueueChildren(IE);
1828}
1829void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1830 WL.push_back(MemberExprParts(M, Parent));
1831 AddStmt(M->getBase());
1832}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001833void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1834 AddTypeLoc(E->getEncodedTypeSourceInfo());
1835}
Ted Kremenek28a71942010-11-13 00:36:47 +00001836void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1837 EnqueueChildren(M);
1838 AddTypeLoc(M->getClassReceiverTypeInfo());
1839}
1840void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001841 WL.push_back(OverloadExprParts(E, Parent));
1842}
Ted Kremenek28a71942010-11-13 00:36:47 +00001843void EnqueueVisitor::VisitStmt(Stmt *S) {
1844 EnqueueChildren(S);
1845}
1846void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1847 AddStmt(S->getBody());
1848 AddStmt(S->getCond());
1849 AddDecl(S->getConditionVariable());
1850}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001851void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1852 AddTypeLoc(E->getArgTInfo2());
1853 AddTypeLoc(E->getArgTInfo1());
1854}
1855
Ted Kremenek28a71942010-11-13 00:36:47 +00001856void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1857 AddStmt(W->getBody());
1858 AddStmt(W->getCond());
1859 AddDecl(W->getConditionVariable());
1860}
1861void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1862 VisitOverloadExpr(U);
1863 if (!U->isImplicitAccess())
1864 AddStmt(U->getBase());
1865}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001866void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1867 AddStmt(E->getSubExpr());
1868 AddTypeLoc(E->getWrittenTypeInfo());
1869}
Ted Kremenek60458782010-11-12 21:34:16 +00001870
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001871void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001872 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001873}
1874
1875bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1876 if (RegionOfInterest.isValid()) {
1877 SourceRange Range = getRawCursorExtent(C);
1878 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1879 return false;
1880 }
1881 return true;
1882}
1883
1884bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1885 while (!WL.empty()) {
1886 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001887 VisitorJob LI = WL.back();
1888 WL.pop_back();
1889
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001890 // Set the Parent field, then back to its old value once we're done.
1891 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1892
1893 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001894 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001895 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001896 if (!D)
1897 continue;
1898
1899 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001900 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001901 return true;
1902
1903 continue;
1904 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001905 case VisitorJob::TypeLocVisitKind: {
1906 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001907 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001908 return true;
1909 continue;
1910 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001911 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001912 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001913 if (!S)
1914 continue;
1915
Ted Kremenekf1107452010-11-12 18:26:56 +00001916 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001917 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1918
1919 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001920 case Stmt::GotoStmtClass: {
1921 GotoStmt *GS = cast<GotoStmt>(S);
1922 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1923 GS->getLabelLoc(), TU))) {
1924 return true;
1925 }
1926 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001927 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001928 // Cases not yet handled by the data-recursion
1929 // algorithm.
1930 case Stmt::OffsetOfExprClass:
1931 case Stmt::SizeOfAlignOfExprClass:
1932 case Stmt::AddrLabelExprClass:
1933 case Stmt::TypesCompatibleExprClass:
1934 case Stmt::VAArgExprClass:
1935 case Stmt::DesignatedInitExprClass:
1936 case Stmt::CXXTypeidExprClass:
1937 case Stmt::CXXUuidofExprClass:
1938 case Stmt::CXXScalarValueInitExprClass:
1939 case Stmt::CXXPseudoDestructorExprClass:
1940 case Stmt::UnaryTypeTraitExprClass:
1941 case Stmt::DependentScopeDeclRefExprClass:
1942 case Stmt::CXXUnresolvedConstructExprClass:
1943 case Stmt::CXXDependentScopeMemberExprClass:
1944 if (Visit(Cursor))
1945 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001946 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001947 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001948 if (!IsInRegionOfInterest(Cursor))
1949 continue;
1950 switch (Visitor(Cursor, Parent, ClientData)) {
1951 case CXChildVisit_Break:
1952 return true;
1953 case CXChildVisit_Continue:
1954 break;
1955 case CXChildVisit_Recurse:
1956 EnqueueWorkList(WL, S);
1957 break;
1958 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001959 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001960 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001961 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001962 }
1963 case VisitorJob::MemberExprPartsKind: {
1964 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001965 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001966
1967 // Visit the nested-name-specifier
1968 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1969 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1970 return true;
1971
1972 // Visit the declaration name.
1973 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1974 return true;
1975
1976 // Visit the explicitly-specified template arguments, if any.
1977 if (M->hasExplicitTemplateArgs()) {
1978 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1979 *ArgEnd = Arg + M->getNumTemplateArgs();
1980 Arg != ArgEnd; ++Arg) {
1981 if (VisitTemplateArgumentLoc(*Arg))
1982 return true;
1983 }
1984 }
1985 continue;
1986 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001987 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001988 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001989 // Visit nested-name-specifier, if present.
1990 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
1991 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
1992 return true;
1993 // Visit declaration name.
1994 if (VisitDeclarationNameInfo(DR->getNameInfo()))
1995 return true;
1996 // Visit explicitly-specified template arguments.
1997 if (DR->hasExplicitTemplateArgs()) {
1998 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
1999 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2000 *ArgEnd = Arg + Args.NumTemplateArgs;
2001 Arg != ArgEnd; ++Arg)
2002 if (VisitTemplateArgumentLoc(*Arg))
2003 return true;
2004 }
2005 continue;
2006 }
Ted Kremenek60458782010-11-12 21:34:16 +00002007 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002008 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002009 // Visit the nested-name-specifier.
2010 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2011 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2012 return true;
2013 // Visit the declaration name.
2014 if (VisitDeclarationNameInfo(O->getNameInfo()))
2015 return true;
2016 // Visit the overloaded declaration reference.
2017 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2018 return true;
2019 // Visit the explicitly-specified template arguments.
2020 if (const ExplicitTemplateArgumentList *ArgList
2021 = O->getOptionalExplicitTemplateArgs()) {
2022 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2023 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2024 Arg != ArgEnd; ++Arg) {
2025 if (VisitTemplateArgumentLoc(*Arg))
2026 return true;
2027 }
2028 }
2029 continue;
2030 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002031 }
2032 }
2033 return false;
2034}
2035
2036bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002037 VisitorWorkList *WL = 0;
2038 if (!WorkListFreeList.empty()) {
2039 WL = WorkListFreeList.back();
2040 WL->clear();
2041 WorkListFreeList.pop_back();
2042 }
2043 else {
2044 WL = new VisitorWorkList();
2045 WorkListCache.push_back(WL);
2046 }
2047 EnqueueWorkList(*WL, S);
2048 bool result = RunVisitorWorkList(*WL);
2049 WorkListFreeList.push_back(WL);
2050 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002051}
2052
2053//===----------------------------------------------------------------------===//
2054// Misc. API hooks.
2055//===----------------------------------------------------------------------===//
2056
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002057static llvm::sys::Mutex EnableMultithreadingMutex;
2058static bool EnabledMultithreading;
2059
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002060extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002061CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2062 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002063 // Disable pretty stack trace functionality, which will otherwise be a very
2064 // poor citizen of the world and set up all sorts of signal handlers.
2065 llvm::DisablePrettyStackTrace = true;
2066
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002067 // We use crash recovery to make some of our APIs more reliable, implicitly
2068 // enable it.
2069 llvm::CrashRecoveryContext::Enable();
2070
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002071 // Enable support for multithreading in LLVM.
2072 {
2073 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2074 if (!EnabledMultithreading) {
2075 llvm::llvm_start_multithreaded();
2076 EnabledMultithreading = true;
2077 }
2078 }
2079
Douglas Gregora030b7c2010-01-22 20:35:53 +00002080 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002081 if (excludeDeclarationsFromPCH)
2082 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002083 if (displayDiagnostics)
2084 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002085 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002086}
2087
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002088void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002089 if (CIdx)
2090 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002091}
2092
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002093CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002094 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002095 if (!CIdx)
2096 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002097
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002098 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002099 FileSystemOptions FileSystemOpts;
2100 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002101
Douglas Gregor28019772010-04-05 23:52:57 +00002102 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002103 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002104 CXXIdx->getOnlyLocalDecls(),
2105 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002106 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002107}
2108
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002109unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002110 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002111 CXTranslationUnit_CacheCompletionResults |
2112 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002113}
2114
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002115CXTranslationUnit
2116clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2117 const char *source_filename,
2118 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002119 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002120 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002121 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002122 return clang_parseTranslationUnit(CIdx, source_filename,
2123 command_line_args, num_command_line_args,
2124 unsaved_files, num_unsaved_files,
2125 CXTranslationUnit_DetailedPreprocessingRecord);
2126}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002127
2128struct ParseTranslationUnitInfo {
2129 CXIndex CIdx;
2130 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002131 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002132 int num_command_line_args;
2133 struct CXUnsavedFile *unsaved_files;
2134 unsigned num_unsaved_files;
2135 unsigned options;
2136 CXTranslationUnit result;
2137};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002138static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002139 ParseTranslationUnitInfo *PTUI =
2140 static_cast<ParseTranslationUnitInfo*>(UserData);
2141 CXIndex CIdx = PTUI->CIdx;
2142 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002143 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002144 int num_command_line_args = PTUI->num_command_line_args;
2145 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2146 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2147 unsigned options = PTUI->options;
2148 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002149
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002150 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002151 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002152
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002153 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2154
Douglas Gregor44c181a2010-07-23 00:33:23 +00002155 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002156 bool CompleteTranslationUnit
2157 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002158 bool CacheCodeCompetionResults
2159 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002160 bool CXXPrecompilePreamble
2161 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2162 bool CXXChainedPCH
2163 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002164
Douglas Gregor5352ac02010-01-28 00:27:43 +00002165 // Configure the diagnostics.
2166 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002167 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2168 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002169
Douglas Gregor4db64a42010-01-23 00:14:00 +00002170 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2171 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002172 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002174 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002175 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2176 Buffer));
2177 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002178
Douglas Gregorb10daed2010-10-11 16:52:23 +00002179 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002180
Ted Kremenek139ba862009-10-22 00:03:57 +00002181 // The 'source_filename' argument is optional. If the caller does not
2182 // specify it then it is assumed that the source file is specified
2183 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002184 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002185 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002186
2187 // Since the Clang C library is primarily used by batch tools dealing with
2188 // (often very broken) source code, where spell-checking can have a
2189 // significant negative impact on performance (particularly when
2190 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002191 // Only do this if we haven't found a spell-checking-related argument.
2192 bool FoundSpellCheckingArgument = false;
2193 for (int I = 0; I != num_command_line_args; ++I) {
2194 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2195 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2196 FoundSpellCheckingArgument = true;
2197 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002198 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002199 }
2200 if (!FoundSpellCheckingArgument)
2201 Args.push_back("-fno-spell-checking");
2202
2203 Args.insert(Args.end(), command_line_args,
2204 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002205
Douglas Gregor44c181a2010-07-23 00:33:23 +00002206 // Do we need the detailed preprocessing record?
2207 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002208 Args.push_back("-Xclang");
2209 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002210 }
2211
Douglas Gregorb10daed2010-10-11 16:52:23 +00002212 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002213 llvm::OwningPtr<ASTUnit> Unit(
2214 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2215 Diags,
2216 CXXIdx->getClangResourcesPath(),
2217 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002218 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002219 RemappedFiles.data(),
2220 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002221 PrecompilePreamble,
2222 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002223 CacheCodeCompetionResults,
2224 CXXPrecompilePreamble,
2225 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002226
Douglas Gregorb10daed2010-10-11 16:52:23 +00002227 if (NumErrors != Diags->getNumErrors()) {
2228 // Make sure to check that 'Unit' is non-NULL.
2229 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2230 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2231 DEnd = Unit->stored_diag_end();
2232 D != DEnd; ++D) {
2233 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2234 CXString Msg = clang_formatDiagnostic(&Diag,
2235 clang_defaultDiagnosticDisplayOptions());
2236 fprintf(stderr, "%s\n", clang_getCString(Msg));
2237 clang_disposeString(Msg);
2238 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002239#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002240 // On Windows, force a flush, since there may be multiple copies of
2241 // stderr and stdout in the file system, all with different buffers
2242 // but writing to the same device.
2243 fflush(stderr);
2244#endif
2245 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002246 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002247
Ted Kremeneka60ed472010-11-16 08:15:36 +00002248 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002249}
2250CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2251 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002252 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002253 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002254 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002255 unsigned num_unsaved_files,
2256 unsigned options) {
2257 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002258 num_command_line_args, unsaved_files,
2259 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002260 llvm::CrashRecoveryContext CRC;
2261
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002262 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002263 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2264 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2265 fprintf(stderr, " 'command_line_args' : [");
2266 for (int i = 0; i != num_command_line_args; ++i) {
2267 if (i)
2268 fprintf(stderr, ", ");
2269 fprintf(stderr, "'%s'", command_line_args[i]);
2270 }
2271 fprintf(stderr, "],\n");
2272 fprintf(stderr, " 'unsaved_files' : [");
2273 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2274 if (i)
2275 fprintf(stderr, ", ");
2276 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2277 unsaved_files[i].Length);
2278 }
2279 fprintf(stderr, "],\n");
2280 fprintf(stderr, " 'options' : %d,\n", options);
2281 fprintf(stderr, "}\n");
2282
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002283 return 0;
2284 }
2285
2286 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002287}
2288
Douglas Gregor19998442010-08-13 15:35:05 +00002289unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2290 return CXSaveTranslationUnit_None;
2291}
2292
2293int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2294 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002295 if (!TU)
2296 return 1;
2297
Ted Kremeneka60ed472010-11-16 08:15:36 +00002298 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002299}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002300
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002301void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002302 if (CTUnit) {
2303 // If the translation unit has been marked as unsafe to free, just discard
2304 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002305 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002306 return;
2307
Ted Kremeneka60ed472010-11-16 08:15:36 +00002308 delete static_cast<ASTUnit *>(CTUnit->TUData);
2309 disposeCXStringPool(CTUnit->StringPool);
2310 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002311 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002312}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002313
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002314unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2315 return CXReparse_None;
2316}
2317
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002318struct ReparseTranslationUnitInfo {
2319 CXTranslationUnit TU;
2320 unsigned num_unsaved_files;
2321 struct CXUnsavedFile *unsaved_files;
2322 unsigned options;
2323 int result;
2324};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002325
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002326static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002327 ReparseTranslationUnitInfo *RTUI =
2328 static_cast<ReparseTranslationUnitInfo*>(UserData);
2329 CXTranslationUnit TU = RTUI->TU;
2330 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2331 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2332 unsigned options = RTUI->options;
2333 (void) options;
2334 RTUI->result = 1;
2335
Douglas Gregorabc563f2010-07-19 21:46:24 +00002336 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002337 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002338
Ted Kremeneka60ed472010-11-16 08:15:36 +00002339 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002340 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002341
2342 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2343 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2344 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2345 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002346 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002347 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2348 Buffer));
2349 }
2350
Douglas Gregor593b0c12010-09-23 18:47:53 +00002351 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2352 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002353}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002354
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002355int clang_reparseTranslationUnit(CXTranslationUnit TU,
2356 unsigned num_unsaved_files,
2357 struct CXUnsavedFile *unsaved_files,
2358 unsigned options) {
2359 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2360 options, 0 };
2361 llvm::CrashRecoveryContext CRC;
2362
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002363 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002364 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002365 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002366 return 1;
2367 }
2368
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002369
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002370 return RTUI.result;
2371}
2372
Douglas Gregordf95a132010-08-09 20:45:32 +00002373
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002374CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002375 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002376 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002377
Ted Kremeneka60ed472010-11-16 08:15:36 +00002378 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002379 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002380}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002381
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002382CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002383 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002384 return Result;
2385}
2386
Ted Kremenekfb480492010-01-13 21:46:36 +00002387} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002388
Ted Kremenekfb480492010-01-13 21:46:36 +00002389//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002390// CXSourceLocation and CXSourceRange Operations.
2391//===----------------------------------------------------------------------===//
2392
Douglas Gregorb9790342010-01-22 21:44:22 +00002393extern "C" {
2394CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002395 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002396 return Result;
2397}
2398
2399unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002400 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2401 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2402 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002403}
2404
2405CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2406 CXFile file,
2407 unsigned line,
2408 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002409 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002410 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002411
Ted Kremeneka60ed472010-11-16 08:15:36 +00002412 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002413 SourceLocation SLoc
2414 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002415 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002416 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002417 if (SLoc.isInvalid()) return clang_getNullLocation();
2418
2419 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2420}
2421
2422CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2423 CXFile file,
2424 unsigned offset) {
2425 if (!tu || !file)
2426 return clang_getNullLocation();
2427
Ted Kremeneka60ed472010-11-16 08:15:36 +00002428 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002429 SourceLocation Start
2430 = CXXUnit->getSourceManager().getLocation(
2431 static_cast<const FileEntry *>(file),
2432 1, 1);
2433 if (Start.isInvalid()) return clang_getNullLocation();
2434
2435 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2436
2437 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002438
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002439 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002440}
2441
Douglas Gregor5352ac02010-01-28 00:27:43 +00002442CXSourceRange clang_getNullRange() {
2443 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2444 return Result;
2445}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002446
Douglas Gregor5352ac02010-01-28 00:27:43 +00002447CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2448 if (begin.ptr_data[0] != end.ptr_data[0] ||
2449 begin.ptr_data[1] != end.ptr_data[1])
2450 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002451
2452 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002453 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002454 return Result;
2455}
2456
Douglas Gregor46766dc2010-01-26 19:19:08 +00002457void clang_getInstantiationLocation(CXSourceLocation location,
2458 CXFile *file,
2459 unsigned *line,
2460 unsigned *column,
2461 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002462 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2463
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002464 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002465 if (file)
2466 *file = 0;
2467 if (line)
2468 *line = 0;
2469 if (column)
2470 *column = 0;
2471 if (offset)
2472 *offset = 0;
2473 return;
2474 }
2475
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002476 const SourceManager &SM =
2477 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002478 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002479
2480 if (file)
2481 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2482 if (line)
2483 *line = SM.getInstantiationLineNumber(InstLoc);
2484 if (column)
2485 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002486 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002487 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002488}
2489
Douglas Gregora9b06d42010-11-09 06:24:54 +00002490void clang_getSpellingLocation(CXSourceLocation location,
2491 CXFile *file,
2492 unsigned *line,
2493 unsigned *column,
2494 unsigned *offset) {
2495 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2496
2497 if (!location.ptr_data[0] || Loc.isInvalid()) {
2498 if (file)
2499 *file = 0;
2500 if (line)
2501 *line = 0;
2502 if (column)
2503 *column = 0;
2504 if (offset)
2505 *offset = 0;
2506 return;
2507 }
2508
2509 const SourceManager &SM =
2510 *static_cast<const SourceManager*>(location.ptr_data[0]);
2511 SourceLocation SpellLoc = Loc;
2512 if (SpellLoc.isMacroID()) {
2513 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2514 if (SimpleSpellingLoc.isFileID() &&
2515 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2516 SpellLoc = SimpleSpellingLoc;
2517 else
2518 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2519 }
2520
2521 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2522 FileID FID = LocInfo.first;
2523 unsigned FileOffset = LocInfo.second;
2524
2525 if (file)
2526 *file = (void *)SM.getFileEntryForID(FID);
2527 if (line)
2528 *line = SM.getLineNumber(FID, FileOffset);
2529 if (column)
2530 *column = SM.getColumnNumber(FID, FileOffset);
2531 if (offset)
2532 *offset = FileOffset;
2533}
2534
Douglas Gregor1db19de2010-01-19 21:36:55 +00002535CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002536 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002537 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002538 return Result;
2539}
2540
2541CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002542 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002543 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002544 return Result;
2545}
2546
Douglas Gregorb9790342010-01-22 21:44:22 +00002547} // end: extern "C"
2548
Douglas Gregor1db19de2010-01-19 21:36:55 +00002549//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002550// CXFile Operations.
2551//===----------------------------------------------------------------------===//
2552
2553extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002554CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002555 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002556 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002557
Steve Naroff88145032009-10-27 14:35:18 +00002558 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002559 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002560}
2561
2562time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002563 if (!SFile)
2564 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002565
Steve Naroff88145032009-10-27 14:35:18 +00002566 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2567 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002568}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Douglas Gregorb9790342010-01-22 21:44:22 +00002570CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2571 if (!tu)
2572 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002573
Ted Kremeneka60ed472010-11-16 08:15:36 +00002574 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002575
Douglas Gregorb9790342010-01-22 21:44:22 +00002576 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002577 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2578 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002579 return const_cast<FileEntry *>(File);
2580}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Ted Kremenekfb480492010-01-13 21:46:36 +00002582} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002583
Ted Kremenekfb480492010-01-13 21:46:36 +00002584//===----------------------------------------------------------------------===//
2585// CXCursor Operations.
2586//===----------------------------------------------------------------------===//
2587
Ted Kremenekfb480492010-01-13 21:46:36 +00002588static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002589 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2590 return getDeclFromExpr(CE->getSubExpr());
2591
Ted Kremenekfb480492010-01-13 21:46:36 +00002592 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2593 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002594 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2595 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002596 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2597 return ME->getMemberDecl();
2598 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2599 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002600 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2601 return PRE->getProperty();
2602
Ted Kremenekfb480492010-01-13 21:46:36 +00002603 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2604 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002605 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2606 if (!CE->isElidable())
2607 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002608 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2609 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002610
Douglas Gregordb1314e2010-10-01 21:11:22 +00002611 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2612 return PE->getProtocol();
2613
Ted Kremenekfb480492010-01-13 21:46:36 +00002614 return 0;
2615}
2616
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002617static SourceLocation getLocationFromExpr(Expr *E) {
2618 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2619 return /*FIXME:*/Msg->getLeftLoc();
2620 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2621 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002622 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2623 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002624 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2625 return Member->getMemberLoc();
2626 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2627 return Ivar->getLocation();
2628 return E->getLocStart();
2629}
2630
Ted Kremenekfb480492010-01-13 21:46:36 +00002631extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002632
2633unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002634 CXCursorVisitor visitor,
2635 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002636 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2637 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002638 return CursorVis.VisitChildren(parent);
2639}
2640
David Chisnall3387c652010-11-03 14:12:26 +00002641#ifndef __has_feature
2642#define __has_feature(x) 0
2643#endif
2644#if __has_feature(blocks)
2645typedef enum CXChildVisitResult
2646 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2647
2648static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2649 CXClientData client_data) {
2650 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2651 return block(cursor, parent);
2652}
2653#else
2654// If we are compiled with a compiler that doesn't have native blocks support,
2655// define and call the block manually, so the
2656typedef struct _CXChildVisitResult
2657{
2658 void *isa;
2659 int flags;
2660 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002661 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2662 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002663} *CXCursorVisitorBlock;
2664
2665static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2666 CXClientData client_data) {
2667 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2668 return block->invoke(block, cursor, parent);
2669}
2670#endif
2671
2672
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002673unsigned clang_visitChildrenWithBlock(CXCursor parent,
2674 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002675 return clang_visitChildren(parent, visitWithBlock, block);
2676}
2677
Douglas Gregor78205d42010-01-20 21:45:58 +00002678static CXString getDeclSpelling(Decl *D) {
2679 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002680 if (!ND) {
2681 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2682 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2683 return createCXString(Property->getIdentifier()->getName());
2684
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002685 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002686 }
2687
Douglas Gregor78205d42010-01-20 21:45:58 +00002688 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002689 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002690
Douglas Gregor78205d42010-01-20 21:45:58 +00002691 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2692 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2693 // and returns different names. NamedDecl returns the class name and
2694 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002695 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002696
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002697 if (isa<UsingDirectiveDecl>(D))
2698 return createCXString("");
2699
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002700 llvm::SmallString<1024> S;
2701 llvm::raw_svector_ostream os(S);
2702 ND->printName(os);
2703
2704 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002705}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002706
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002707CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002708 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002709 return clang_getTranslationUnitSpelling(
2710 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002711
Steve Narofff334b4e2009-09-02 18:26:48 +00002712 if (clang_isReference(C.kind)) {
2713 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002714 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002715 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002716 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002717 }
2718 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002719 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002720 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002721 }
2722 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002723 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002724 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002725 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002726 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002727 case CXCursor_CXXBaseSpecifier: {
2728 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2729 return createCXString(B->getType().getAsString());
2730 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002731 case CXCursor_TypeRef: {
2732 TypeDecl *Type = getCursorTypeRef(C).first;
2733 assert(Type && "Missing type decl");
2734
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002735 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2736 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002737 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002738 case CXCursor_TemplateRef: {
2739 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002740 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002741
2742 return createCXString(Template->getNameAsString());
2743 }
Douglas Gregor69319002010-08-31 23:48:11 +00002744
2745 case CXCursor_NamespaceRef: {
2746 NamedDecl *NS = getCursorNamespaceRef(C).first;
2747 assert(NS && "Missing namespace decl");
2748
2749 return createCXString(NS->getNameAsString());
2750 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002751
Douglas Gregora67e03f2010-09-09 21:42:20 +00002752 case CXCursor_MemberRef: {
2753 FieldDecl *Field = getCursorMemberRef(C).first;
2754 assert(Field && "Missing member decl");
2755
2756 return createCXString(Field->getNameAsString());
2757 }
2758
Douglas Gregor36897b02010-09-10 00:22:18 +00002759 case CXCursor_LabelRef: {
2760 LabelStmt *Label = getCursorLabelRef(C).first;
2761 assert(Label && "Missing label");
2762
2763 return createCXString(Label->getID()->getName());
2764 }
2765
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002766 case CXCursor_OverloadedDeclRef: {
2767 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2768 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2769 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2770 return createCXString(ND->getNameAsString());
2771 return createCXString("");
2772 }
2773 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2774 return createCXString(E->getName().getAsString());
2775 OverloadedTemplateStorage *Ovl
2776 = Storage.get<OverloadedTemplateStorage*>();
2777 if (Ovl->size() == 0)
2778 return createCXString("");
2779 return createCXString((*Ovl->begin())->getNameAsString());
2780 }
2781
Daniel Dunbaracca7252009-11-30 20:42:49 +00002782 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002783 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002784 }
2785 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002786
2787 if (clang_isExpression(C.kind)) {
2788 Decl *D = getDeclFromExpr(getCursorExpr(C));
2789 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002790 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002791 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002792 }
2793
Douglas Gregor36897b02010-09-10 00:22:18 +00002794 if (clang_isStatement(C.kind)) {
2795 Stmt *S = getCursorStmt(C);
2796 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2797 return createCXString(Label->getID()->getName());
2798
2799 return createCXString("");
2800 }
2801
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002802 if (C.kind == CXCursor_MacroInstantiation)
2803 return createCXString(getCursorMacroInstantiation(C)->getName()
2804 ->getNameStart());
2805
Douglas Gregor572feb22010-03-18 18:04:21 +00002806 if (C.kind == CXCursor_MacroDefinition)
2807 return createCXString(getCursorMacroDefinition(C)->getName()
2808 ->getNameStart());
2809
Douglas Gregorecdcb882010-10-20 22:00:55 +00002810 if (C.kind == CXCursor_InclusionDirective)
2811 return createCXString(getCursorInclusionDirective(C)->getFileName());
2812
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002813 if (clang_isDeclaration(C.kind))
2814 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002815
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002816 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002817}
2818
Douglas Gregor358559d2010-10-02 22:49:11 +00002819CXString clang_getCursorDisplayName(CXCursor C) {
2820 if (!clang_isDeclaration(C.kind))
2821 return clang_getCursorSpelling(C);
2822
2823 Decl *D = getCursorDecl(C);
2824 if (!D)
2825 return createCXString("");
2826
2827 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2828 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2829 D = FunTmpl->getTemplatedDecl();
2830
2831 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2832 llvm::SmallString<64> Str;
2833 llvm::raw_svector_ostream OS(Str);
2834 OS << Function->getNameAsString();
2835 if (Function->getPrimaryTemplate())
2836 OS << "<>";
2837 OS << "(";
2838 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2839 if (I)
2840 OS << ", ";
2841 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2842 }
2843
2844 if (Function->isVariadic()) {
2845 if (Function->getNumParams())
2846 OS << ", ";
2847 OS << "...";
2848 }
2849 OS << ")";
2850 return createCXString(OS.str());
2851 }
2852
2853 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2854 llvm::SmallString<64> Str;
2855 llvm::raw_svector_ostream OS(Str);
2856 OS << ClassTemplate->getNameAsString();
2857 OS << "<";
2858 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2859 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2860 if (I)
2861 OS << ", ";
2862
2863 NamedDecl *Param = Params->getParam(I);
2864 if (Param->getIdentifier()) {
2865 OS << Param->getIdentifier()->getName();
2866 continue;
2867 }
2868
2869 // There is no parameter name, which makes this tricky. Try to come up
2870 // with something useful that isn't too long.
2871 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2872 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2873 else if (NonTypeTemplateParmDecl *NTTP
2874 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2875 OS << NTTP->getType().getAsString(Policy);
2876 else
2877 OS << "template<...> class";
2878 }
2879
2880 OS << ">";
2881 return createCXString(OS.str());
2882 }
2883
2884 if (ClassTemplateSpecializationDecl *ClassSpec
2885 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2886 // If the type was explicitly written, use that.
2887 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2888 return createCXString(TSInfo->getType().getAsString(Policy));
2889
2890 llvm::SmallString<64> Str;
2891 llvm::raw_svector_ostream OS(Str);
2892 OS << ClassSpec->getNameAsString();
2893 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002894 ClassSpec->getTemplateArgs().data(),
2895 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002896 Policy);
2897 return createCXString(OS.str());
2898 }
2899
2900 return clang_getCursorSpelling(C);
2901}
2902
Ted Kremeneke68fff62010-02-17 00:41:32 +00002903CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002904 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002905 case CXCursor_FunctionDecl:
2906 return createCXString("FunctionDecl");
2907 case CXCursor_TypedefDecl:
2908 return createCXString("TypedefDecl");
2909 case CXCursor_EnumDecl:
2910 return createCXString("EnumDecl");
2911 case CXCursor_EnumConstantDecl:
2912 return createCXString("EnumConstantDecl");
2913 case CXCursor_StructDecl:
2914 return createCXString("StructDecl");
2915 case CXCursor_UnionDecl:
2916 return createCXString("UnionDecl");
2917 case CXCursor_ClassDecl:
2918 return createCXString("ClassDecl");
2919 case CXCursor_FieldDecl:
2920 return createCXString("FieldDecl");
2921 case CXCursor_VarDecl:
2922 return createCXString("VarDecl");
2923 case CXCursor_ParmDecl:
2924 return createCXString("ParmDecl");
2925 case CXCursor_ObjCInterfaceDecl:
2926 return createCXString("ObjCInterfaceDecl");
2927 case CXCursor_ObjCCategoryDecl:
2928 return createCXString("ObjCCategoryDecl");
2929 case CXCursor_ObjCProtocolDecl:
2930 return createCXString("ObjCProtocolDecl");
2931 case CXCursor_ObjCPropertyDecl:
2932 return createCXString("ObjCPropertyDecl");
2933 case CXCursor_ObjCIvarDecl:
2934 return createCXString("ObjCIvarDecl");
2935 case CXCursor_ObjCInstanceMethodDecl:
2936 return createCXString("ObjCInstanceMethodDecl");
2937 case CXCursor_ObjCClassMethodDecl:
2938 return createCXString("ObjCClassMethodDecl");
2939 case CXCursor_ObjCImplementationDecl:
2940 return createCXString("ObjCImplementationDecl");
2941 case CXCursor_ObjCCategoryImplDecl:
2942 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002943 case CXCursor_CXXMethod:
2944 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002945 case CXCursor_UnexposedDecl:
2946 return createCXString("UnexposedDecl");
2947 case CXCursor_ObjCSuperClassRef:
2948 return createCXString("ObjCSuperClassRef");
2949 case CXCursor_ObjCProtocolRef:
2950 return createCXString("ObjCProtocolRef");
2951 case CXCursor_ObjCClassRef:
2952 return createCXString("ObjCClassRef");
2953 case CXCursor_TypeRef:
2954 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002955 case CXCursor_TemplateRef:
2956 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002957 case CXCursor_NamespaceRef:
2958 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002959 case CXCursor_MemberRef:
2960 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002961 case CXCursor_LabelRef:
2962 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002963 case CXCursor_OverloadedDeclRef:
2964 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002965 case CXCursor_UnexposedExpr:
2966 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002967 case CXCursor_BlockExpr:
2968 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002969 case CXCursor_DeclRefExpr:
2970 return createCXString("DeclRefExpr");
2971 case CXCursor_MemberRefExpr:
2972 return createCXString("MemberRefExpr");
2973 case CXCursor_CallExpr:
2974 return createCXString("CallExpr");
2975 case CXCursor_ObjCMessageExpr:
2976 return createCXString("ObjCMessageExpr");
2977 case CXCursor_UnexposedStmt:
2978 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002979 case CXCursor_LabelStmt:
2980 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002981 case CXCursor_InvalidFile:
2982 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002983 case CXCursor_InvalidCode:
2984 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002985 case CXCursor_NoDeclFound:
2986 return createCXString("NoDeclFound");
2987 case CXCursor_NotImplemented:
2988 return createCXString("NotImplemented");
2989 case CXCursor_TranslationUnit:
2990 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002991 case CXCursor_UnexposedAttr:
2992 return createCXString("UnexposedAttr");
2993 case CXCursor_IBActionAttr:
2994 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002995 case CXCursor_IBOutletAttr:
2996 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002997 case CXCursor_IBOutletCollectionAttr:
2998 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002999 case CXCursor_PreprocessingDirective:
3000 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003001 case CXCursor_MacroDefinition:
3002 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003003 case CXCursor_MacroInstantiation:
3004 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003005 case CXCursor_InclusionDirective:
3006 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003007 case CXCursor_Namespace:
3008 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003009 case CXCursor_LinkageSpec:
3010 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003011 case CXCursor_CXXBaseSpecifier:
3012 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003013 case CXCursor_Constructor:
3014 return createCXString("CXXConstructor");
3015 case CXCursor_Destructor:
3016 return createCXString("CXXDestructor");
3017 case CXCursor_ConversionFunction:
3018 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003019 case CXCursor_TemplateTypeParameter:
3020 return createCXString("TemplateTypeParameter");
3021 case CXCursor_NonTypeTemplateParameter:
3022 return createCXString("NonTypeTemplateParameter");
3023 case CXCursor_TemplateTemplateParameter:
3024 return createCXString("TemplateTemplateParameter");
3025 case CXCursor_FunctionTemplate:
3026 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003027 case CXCursor_ClassTemplate:
3028 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003029 case CXCursor_ClassTemplatePartialSpecialization:
3030 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003031 case CXCursor_NamespaceAlias:
3032 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003033 case CXCursor_UsingDirective:
3034 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003035 case CXCursor_UsingDeclaration:
3036 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003037 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003038
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003039 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003040 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003041}
Steve Naroff89922f82009-08-31 00:59:03 +00003042
Ted Kremeneke68fff62010-02-17 00:41:32 +00003043enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3044 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003045 CXClientData client_data) {
3046 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003047
3048 // If our current best cursor is the construction of a temporary object,
3049 // don't replace that cursor with a type reference, because we want
3050 // clang_getCursor() to point at the constructor.
3051 if (clang_isExpression(BestCursor->kind) &&
3052 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3053 cursor.kind == CXCursor_TypeRef)
3054 return CXChildVisit_Recurse;
3055
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003056 *BestCursor = cursor;
3057 return CXChildVisit_Recurse;
3058}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003059
Douglas Gregorb9790342010-01-22 21:44:22 +00003060CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3061 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003062 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003063
Ted Kremeneka60ed472010-11-16 08:15:36 +00003064 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003065 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3066
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003067 // Translate the given source location to make it point at the beginning of
3068 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003069 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003070
3071 // Guard against an invalid SourceLocation, or we may assert in one
3072 // of the following calls.
3073 if (SLoc.isInvalid())
3074 return clang_getNullCursor();
3075
Douglas Gregor40749ee2010-11-03 00:35:38 +00003076 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003077 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3078 CXXUnit->getASTContext().getLangOptions());
3079
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003080 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3081 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003082 // FIXME: Would be great to have a "hint" cursor, then walk from that
3083 // hint cursor upward until we find a cursor whose source range encloses
3084 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003085 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3086 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003087 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003088 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003089 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003090
3091 if (Logging) {
3092 CXFile SearchFile;
3093 unsigned SearchLine, SearchColumn;
3094 CXFile ResultFile;
3095 unsigned ResultLine, ResultColumn;
3096 CXString SearchFileName, ResultFileName, KindSpelling;
3097 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3098
3099 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3100 0);
3101 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3102 &ResultColumn, 0);
3103 SearchFileName = clang_getFileName(SearchFile);
3104 ResultFileName = clang_getFileName(ResultFile);
3105 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3106 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3107 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3108 clang_getCString(KindSpelling),
3109 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3110 clang_disposeString(SearchFileName);
3111 clang_disposeString(ResultFileName);
3112 clang_disposeString(KindSpelling);
3113 }
3114
Ted Kremeneke68fff62010-02-17 00:41:32 +00003115 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003116}
3117
Ted Kremenek73885552009-11-17 19:28:59 +00003118CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003119 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003120}
3121
3122unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003123 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003124}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003125
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003126unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003127 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3128}
3129
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003130unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003131 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3132}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003133
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003134unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003135 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3136}
3137
Douglas Gregor97b98722010-01-19 23:20:36 +00003138unsigned clang_isExpression(enum CXCursorKind K) {
3139 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3140}
3141
3142unsigned clang_isStatement(enum CXCursorKind K) {
3143 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3144}
3145
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003146unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3147 return K == CXCursor_TranslationUnit;
3148}
3149
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003150unsigned clang_isPreprocessing(enum CXCursorKind K) {
3151 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3152}
3153
Ted Kremenekad6eff62010-03-08 21:17:29 +00003154unsigned clang_isUnexposed(enum CXCursorKind K) {
3155 switch (K) {
3156 case CXCursor_UnexposedDecl:
3157 case CXCursor_UnexposedExpr:
3158 case CXCursor_UnexposedStmt:
3159 case CXCursor_UnexposedAttr:
3160 return true;
3161 default:
3162 return false;
3163 }
3164}
3165
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003166CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003167 return C.kind;
3168}
3169
Douglas Gregor98258af2010-01-18 22:46:11 +00003170CXSourceLocation clang_getCursorLocation(CXCursor C) {
3171 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003172 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003173 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003174 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3175 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003176 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003177 }
3178
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003179 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003180 std::pair<ObjCProtocolDecl *, SourceLocation> P
3181 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003182 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003183 }
3184
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003185 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003186 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3187 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003188 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003189 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003190
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003191 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003192 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003193 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003194 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003195
3196 case CXCursor_TemplateRef: {
3197 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3198 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3199 }
3200
Douglas Gregor69319002010-08-31 23:48:11 +00003201 case CXCursor_NamespaceRef: {
3202 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3203 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3204 }
3205
Douglas Gregora67e03f2010-09-09 21:42:20 +00003206 case CXCursor_MemberRef: {
3207 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3208 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3209 }
3210
Ted Kremenek3064ef92010-08-27 21:34:58 +00003211 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003212 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3213 if (!BaseSpec)
3214 return clang_getNullLocation();
3215
3216 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3217 return cxloc::translateSourceLocation(getCursorContext(C),
3218 TSInfo->getTypeLoc().getBeginLoc());
3219
3220 return cxloc::translateSourceLocation(getCursorContext(C),
3221 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003222 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003223
Douglas Gregor36897b02010-09-10 00:22:18 +00003224 case CXCursor_LabelRef: {
3225 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3226 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3227 }
3228
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003229 case CXCursor_OverloadedDeclRef:
3230 return cxloc::translateSourceLocation(getCursorContext(C),
3231 getCursorOverloadedDeclRef(C).second);
3232
Douglas Gregorf46034a2010-01-18 23:41:10 +00003233 default:
3234 // FIXME: Need a way to enumerate all non-reference cases.
3235 llvm_unreachable("Missed a reference kind");
3236 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003237 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003238
3239 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003240 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003241 getLocationFromExpr(getCursorExpr(C)));
3242
Douglas Gregor36897b02010-09-10 00:22:18 +00003243 if (clang_isStatement(C.kind))
3244 return cxloc::translateSourceLocation(getCursorContext(C),
3245 getCursorStmt(C)->getLocStart());
3246
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003247 if (C.kind == CXCursor_PreprocessingDirective) {
3248 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3249 return cxloc::translateSourceLocation(getCursorContext(C), L);
3250 }
Douglas Gregor48072312010-03-18 15:23:44 +00003251
3252 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003253 SourceLocation L
3254 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003255 return cxloc::translateSourceLocation(getCursorContext(C), L);
3256 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003257
3258 if (C.kind == CXCursor_MacroDefinition) {
3259 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3260 return cxloc::translateSourceLocation(getCursorContext(C), L);
3261 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003262
3263 if (C.kind == CXCursor_InclusionDirective) {
3264 SourceLocation L
3265 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3266 return cxloc::translateSourceLocation(getCursorContext(C), L);
3267 }
3268
Ted Kremenek9a700d22010-05-12 06:16:13 +00003269 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003270 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003271
Douglas Gregorf46034a2010-01-18 23:41:10 +00003272 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003273 SourceLocation Loc = D->getLocation();
3274 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3275 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003276 // FIXME: Multiple variables declared in a single declaration
3277 // currently lack the information needed to correctly determine their
3278 // ranges when accounting for the type-specifier. We use context
3279 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3280 // and if so, whether it is the first decl.
3281 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3282 if (!cxcursor::isFirstInDeclGroup(C))
3283 Loc = VD->getLocation();
3284 }
3285
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003286 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003287}
Douglas Gregora7bde202010-01-19 00:34:46 +00003288
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003289} // end extern "C"
3290
3291static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003292 if (clang_isReference(C.kind)) {
3293 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003294 case CXCursor_ObjCSuperClassRef:
3295 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003296
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003297 case CXCursor_ObjCProtocolRef:
3298 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003299
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003300 case CXCursor_ObjCClassRef:
3301 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003302
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003303 case CXCursor_TypeRef:
3304 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003305
3306 case CXCursor_TemplateRef:
3307 return getCursorTemplateRef(C).second;
3308
Douglas Gregor69319002010-08-31 23:48:11 +00003309 case CXCursor_NamespaceRef:
3310 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003311
3312 case CXCursor_MemberRef:
3313 return getCursorMemberRef(C).second;
3314
Ted Kremenek3064ef92010-08-27 21:34:58 +00003315 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003316 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003317
Douglas Gregor36897b02010-09-10 00:22:18 +00003318 case CXCursor_LabelRef:
3319 return getCursorLabelRef(C).second;
3320
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003321 case CXCursor_OverloadedDeclRef:
3322 return getCursorOverloadedDeclRef(C).second;
3323
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003324 default:
3325 // FIXME: Need a way to enumerate all non-reference cases.
3326 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003327 }
3328 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003329
3330 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003331 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003332
3333 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003334 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003335
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003336 if (C.kind == CXCursor_PreprocessingDirective)
3337 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003338
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003339 if (C.kind == CXCursor_MacroInstantiation)
3340 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003341
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003342 if (C.kind == CXCursor_MacroDefinition)
3343 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003344
3345 if (C.kind == CXCursor_InclusionDirective)
3346 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3347
Ted Kremenek007a7c92010-11-01 23:26:51 +00003348 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3349 Decl *D = cxcursor::getCursorDecl(C);
3350 SourceRange R = D->getSourceRange();
3351 // FIXME: Multiple variables declared in a single declaration
3352 // currently lack the information needed to correctly determine their
3353 // ranges when accounting for the type-specifier. We use context
3354 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3355 // and if so, whether it is the first decl.
3356 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3357 if (!cxcursor::isFirstInDeclGroup(C))
3358 R.setBegin(VD->getLocation());
3359 }
3360 return R;
3361 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003362 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003363
3364extern "C" {
3365
3366CXSourceRange clang_getCursorExtent(CXCursor C) {
3367 SourceRange R = getRawCursorExtent(C);
3368 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003369 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003370
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003371 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003372}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003373
3374CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003375 if (clang_isInvalid(C.kind))
3376 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003377
Ted Kremeneka60ed472010-11-16 08:15:36 +00003378 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003379 if (clang_isDeclaration(C.kind)) {
3380 Decl *D = getCursorDecl(C);
3381 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003382 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003383 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003384 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003385 if (ObjCForwardProtocolDecl *Protocols
3386 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003387 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003388 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3389 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3390 return MakeCXCursor(Property, tu);
3391
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003392 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003393 }
3394
Douglas Gregor97b98722010-01-19 23:20:36 +00003395 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003396 Expr *E = getCursorExpr(C);
3397 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003398 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003399 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003400
3401 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003402 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003403
Douglas Gregor97b98722010-01-19 23:20:36 +00003404 return clang_getNullCursor();
3405 }
3406
Douglas Gregor36897b02010-09-10 00:22:18 +00003407 if (clang_isStatement(C.kind)) {
3408 Stmt *S = getCursorStmt(C);
3409 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003410 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003411
3412 return clang_getNullCursor();
3413 }
3414
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003415 if (C.kind == CXCursor_MacroInstantiation) {
3416 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003417 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003418 }
3419
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003420 if (!clang_isReference(C.kind))
3421 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003422
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003423 switch (C.kind) {
3424 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003425 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003426
3427 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003428 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003429
3430 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003431 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003432
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003433 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003434 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003435
3436 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003437 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003438
Douglas Gregor69319002010-08-31 23:48:11 +00003439 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003440 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003441
Douglas Gregora67e03f2010-09-09 21:42:20 +00003442 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003443 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003444
Ted Kremenek3064ef92010-08-27 21:34:58 +00003445 case CXCursor_CXXBaseSpecifier: {
3446 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3447 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003448 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003449 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003450
Douglas Gregor36897b02010-09-10 00:22:18 +00003451 case CXCursor_LabelRef:
3452 // FIXME: We end up faking the "parent" declaration here because we
3453 // don't want to make CXCursor larger.
3454 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003455 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3456 .getTranslationUnitDecl(),
3457 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003458
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003459 case CXCursor_OverloadedDeclRef:
3460 return C;
3461
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003462 default:
3463 // We would prefer to enumerate all non-reference cursor kinds here.
3464 llvm_unreachable("Unhandled reference cursor kind");
3465 break;
3466 }
3467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003468
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003469 return clang_getNullCursor();
3470}
3471
Douglas Gregorb6998662010-01-19 19:34:47 +00003472CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003473 if (clang_isInvalid(C.kind))
3474 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003475
Ted Kremeneka60ed472010-11-16 08:15:36 +00003476 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003477
Douglas Gregorb6998662010-01-19 19:34:47 +00003478 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003479 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003480 C = clang_getCursorReferenced(C);
3481 WasReference = true;
3482 }
3483
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003484 if (C.kind == CXCursor_MacroInstantiation)
3485 return clang_getCursorReferenced(C);
3486
Douglas Gregorb6998662010-01-19 19:34:47 +00003487 if (!clang_isDeclaration(C.kind))
3488 return clang_getNullCursor();
3489
3490 Decl *D = getCursorDecl(C);
3491 if (!D)
3492 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003493
Douglas Gregorb6998662010-01-19 19:34:47 +00003494 switch (D->getKind()) {
3495 // Declaration kinds that don't really separate the notions of
3496 // declaration and definition.
3497 case Decl::Namespace:
3498 case Decl::Typedef:
3499 case Decl::TemplateTypeParm:
3500 case Decl::EnumConstant:
3501 case Decl::Field:
3502 case Decl::ObjCIvar:
3503 case Decl::ObjCAtDefsField:
3504 case Decl::ImplicitParam:
3505 case Decl::ParmVar:
3506 case Decl::NonTypeTemplateParm:
3507 case Decl::TemplateTemplateParm:
3508 case Decl::ObjCCategoryImpl:
3509 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003510 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003511 case Decl::LinkageSpec:
3512 case Decl::ObjCPropertyImpl:
3513 case Decl::FileScopeAsm:
3514 case Decl::StaticAssert:
3515 case Decl::Block:
3516 return C;
3517
3518 // Declaration kinds that don't make any sense here, but are
3519 // nonetheless harmless.
3520 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003521 break;
3522
3523 // Declaration kinds for which the definition is not resolvable.
3524 case Decl::UnresolvedUsingTypename:
3525 case Decl::UnresolvedUsingValue:
3526 break;
3527
3528 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003529 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003530 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003531
3532 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003533 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003534
3535 case Decl::Enum:
3536 case Decl::Record:
3537 case Decl::CXXRecord:
3538 case Decl::ClassTemplateSpecialization:
3539 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003540 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003541 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003542 return clang_getNullCursor();
3543
3544 case Decl::Function:
3545 case Decl::CXXMethod:
3546 case Decl::CXXConstructor:
3547 case Decl::CXXDestructor:
3548 case Decl::CXXConversion: {
3549 const FunctionDecl *Def = 0;
3550 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003551 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003552 return clang_getNullCursor();
3553 }
3554
3555 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003556 // Ask the variable if it has a definition.
3557 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003558 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003559 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003560 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003561
Douglas Gregorb6998662010-01-19 19:34:47 +00003562 case Decl::FunctionTemplate: {
3563 const FunctionDecl *Def = 0;
3564 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003565 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003566 return clang_getNullCursor();
3567 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003568
Douglas Gregorb6998662010-01-19 19:34:47 +00003569 case Decl::ClassTemplate: {
3570 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003571 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003572 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003573 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003574 return clang_getNullCursor();
3575 }
3576
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003577 case Decl::Using:
3578 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003579 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003580
3581 case Decl::UsingShadow:
3582 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003583 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003584 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003585
3586 case Decl::ObjCMethod: {
3587 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3588 if (Method->isThisDeclarationADefinition())
3589 return C;
3590
3591 // Dig out the method definition in the associated
3592 // @implementation, if we have it.
3593 // FIXME: The ASTs should make finding the definition easier.
3594 if (ObjCInterfaceDecl *Class
3595 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3596 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3597 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3598 Method->isInstanceMethod()))
3599 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003600 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003601
3602 return clang_getNullCursor();
3603 }
3604
3605 case Decl::ObjCCategory:
3606 if (ObjCCategoryImplDecl *Impl
3607 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003608 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003609 return clang_getNullCursor();
3610
3611 case Decl::ObjCProtocol:
3612 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3613 return C;
3614 return clang_getNullCursor();
3615
3616 case Decl::ObjCInterface:
3617 // There are two notions of a "definition" for an Objective-C
3618 // class: the interface and its implementation. When we resolved a
3619 // reference to an Objective-C class, produce the @interface as
3620 // the definition; when we were provided with the interface,
3621 // produce the @implementation as the definition.
3622 if (WasReference) {
3623 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3624 return C;
3625 } else if (ObjCImplementationDecl *Impl
3626 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003627 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003628 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003629
Douglas Gregorb6998662010-01-19 19:34:47 +00003630 case Decl::ObjCProperty:
3631 // FIXME: We don't really know where to find the
3632 // ObjCPropertyImplDecls that implement this property.
3633 return clang_getNullCursor();
3634
3635 case Decl::ObjCCompatibleAlias:
3636 if (ObjCInterfaceDecl *Class
3637 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3638 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003639 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003640
Douglas Gregorb6998662010-01-19 19:34:47 +00003641 return clang_getNullCursor();
3642
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003643 case Decl::ObjCForwardProtocol:
3644 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003645 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003646
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003647 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003648 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003649 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003650
3651 case Decl::Friend:
3652 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003653 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003654 return clang_getNullCursor();
3655
3656 case Decl::FriendTemplate:
3657 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003658 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003659 return clang_getNullCursor();
3660 }
3661
3662 return clang_getNullCursor();
3663}
3664
3665unsigned clang_isCursorDefinition(CXCursor C) {
3666 if (!clang_isDeclaration(C.kind))
3667 return 0;
3668
3669 return clang_getCursorDefinition(C) == C;
3670}
3671
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003672unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003673 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003674 return 0;
3675
3676 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3677 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3678 return E->getNumDecls();
3679
3680 if (OverloadedTemplateStorage *S
3681 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3682 return S->size();
3683
3684 Decl *D = Storage.get<Decl*>();
3685 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003686 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003687 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3688 return Classes->size();
3689 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3690 return Protocols->protocol_size();
3691
3692 return 0;
3693}
3694
3695CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003696 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003697 return clang_getNullCursor();
3698
3699 if (index >= clang_getNumOverloadedDecls(cursor))
3700 return clang_getNullCursor();
3701
Ted Kremeneka60ed472010-11-16 08:15:36 +00003702 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003703 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3704 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003705 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003706
3707 if (OverloadedTemplateStorage *S
3708 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003709 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003710
3711 Decl *D = Storage.get<Decl*>();
3712 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3713 // FIXME: This is, unfortunately, linear time.
3714 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3715 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003716 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003717 }
3718
3719 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003720 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003721
3722 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003723 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003724
3725 return clang_getNullCursor();
3726}
3727
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003728void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003729 const char **startBuf,
3730 const char **endBuf,
3731 unsigned *startLine,
3732 unsigned *startColumn,
3733 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003734 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003735 assert(getCursorDecl(C) && "CXCursor has null decl");
3736 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003737 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3738 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003739
Steve Naroff4ade6d62009-09-23 17:52:52 +00003740 SourceManager &SM = FD->getASTContext().getSourceManager();
3741 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3742 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3743 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3744 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3745 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3746 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3747}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003748
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003749void clang_enableStackTraces(void) {
3750 llvm::sys::PrintStackTraceOnErrorSignal();
3751}
3752
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003753void clang_executeOnThread(void (*fn)(void*), void *user_data,
3754 unsigned stack_size) {
3755 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3756}
3757
Ted Kremenekfb480492010-01-13 21:46:36 +00003758} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003759
Ted Kremenekfb480492010-01-13 21:46:36 +00003760//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003761// Token-based Operations.
3762//===----------------------------------------------------------------------===//
3763
3764/* CXToken layout:
3765 * int_data[0]: a CXTokenKind
3766 * int_data[1]: starting token location
3767 * int_data[2]: token length
3768 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003769 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003770 * otherwise unused.
3771 */
3772extern "C" {
3773
3774CXTokenKind clang_getTokenKind(CXToken CXTok) {
3775 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3776}
3777
3778CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3779 switch (clang_getTokenKind(CXTok)) {
3780 case CXToken_Identifier:
3781 case CXToken_Keyword:
3782 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003783 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3784 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003785
3786 case CXToken_Literal: {
3787 // We have stashed the starting pointer in the ptr_data field. Use it.
3788 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003789 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003790 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003791
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003792 case CXToken_Punctuation:
3793 case CXToken_Comment:
3794 break;
3795 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003796
3797 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003798 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003799 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003800 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003801 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003802
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003803 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3804 std::pair<FileID, unsigned> LocInfo
3805 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003806 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003807 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003808 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3809 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003810 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003811
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003812 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003813}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003814
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003815CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
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)
3818 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003819
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3821 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3822}
3823
3824CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003825 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003826 if (!CXXUnit)
3827 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003828
3829 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003830 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3831}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003833void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3834 CXToken **Tokens, unsigned *NumTokens) {
3835 if (Tokens)
3836 *Tokens = 0;
3837 if (NumTokens)
3838 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003839
Ted Kremeneka60ed472010-11-16 08:15:36 +00003840 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003841 if (!CXXUnit || !Tokens || !NumTokens)
3842 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
Douglas Gregorbdf60622010-03-05 21:16:25 +00003844 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3845
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003846 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003847 if (R.isInvalid())
3848 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003849
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003850 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3851 std::pair<FileID, unsigned> BeginLocInfo
3852 = SourceMgr.getDecomposedLoc(R.getBegin());
3853 std::pair<FileID, unsigned> EndLocInfo
3854 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003855
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003856 // Cannot tokenize across files.
3857 if (BeginLocInfo.first != EndLocInfo.first)
3858 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
3860 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003861 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003862 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003863 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003864 if (Invalid)
3865 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003866
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003867 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3868 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003869 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003871
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003872 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003873 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 llvm::SmallVector<CXToken, 32> CXTokens;
3875 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003876 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003877 do {
3878 // Lex the next token
3879 Lex.LexFromRawLexer(Tok);
3880 if (Tok.is(tok::eof))
3881 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003882
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003883 // Initialize the CXToken.
3884 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003885
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003886 // - Common fields
3887 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3888 CXTok.int_data[2] = Tok.getLength();
3889 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003890
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891 // - Kind-specific fields
3892 if (Tok.isLiteral()) {
3893 CXTok.int_data[0] = CXToken_Literal;
3894 CXTok.ptr_data = (void *)Tok.getLiteralData();
3895 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003896 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003897 std::pair<FileID, unsigned> LocInfo
3898 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003899 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003900 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003901 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3902 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003903 return;
3904
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003905 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003906 IdentifierInfo *II
3907 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003908
David Chisnall096428b2010-10-13 21:44:48 +00003909 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003910 CXTok.int_data[0] = CXToken_Keyword;
3911 }
3912 else {
3913 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3914 CXToken_Identifier
3915 : CXToken_Keyword;
3916 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003917 CXTok.ptr_data = II;
3918 } else if (Tok.is(tok::comment)) {
3919 CXTok.int_data[0] = CXToken_Comment;
3920 CXTok.ptr_data = 0;
3921 } else {
3922 CXTok.int_data[0] = CXToken_Punctuation;
3923 CXTok.ptr_data = 0;
3924 }
3925 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003926 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003927 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003928
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003929 if (CXTokens.empty())
3930 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003931
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003932 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3933 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3934 *NumTokens = CXTokens.size();
3935}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003936
Ted Kremenek6db61092010-05-05 00:55:15 +00003937void clang_disposeTokens(CXTranslationUnit TU,
3938 CXToken *Tokens, unsigned NumTokens) {
3939 free(Tokens);
3940}
3941
3942} // end: extern "C"
3943
3944//===----------------------------------------------------------------------===//
3945// Token annotation APIs.
3946//===----------------------------------------------------------------------===//
3947
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003948typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003949static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3950 CXCursor parent,
3951 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003952namespace {
3953class AnnotateTokensWorker {
3954 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003955 CXToken *Tokens;
3956 CXCursor *Cursors;
3957 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003958 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003959 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003960 CursorVisitor AnnotateVis;
3961 SourceManager &SrcMgr;
3962
3963 bool MoreTokens() const { return TokIdx < NumTokens; }
3964 unsigned NextToken() const { return TokIdx; }
3965 void AdvanceToken() { ++TokIdx; }
3966 SourceLocation GetTokenLoc(unsigned tokI) {
3967 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3968 }
3969
Ted Kremenek6db61092010-05-05 00:55:15 +00003970public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003971 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003972 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003973 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003974 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003975 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003976 AnnotateVis(tu,
3977 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003978 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003979 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003980
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003981 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003982 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003983 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003984 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003985 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00003986 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003987};
3988}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003989
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003990void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3991 // Walk the AST within the region of interest, annotating tokens
3992 // along the way.
3993 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003994
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003995 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3996 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003997 if (Pos != Annotated.end() &&
3998 (clang_isInvalid(Cursors[I].kind) ||
3999 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004000 Cursors[I] = Pos->second;
4001 }
4002
4003 // Finish up annotating any tokens left.
4004 if (!MoreTokens())
4005 return;
4006
4007 const CXCursor &C = clang_getNullCursor();
4008 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4009 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4010 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004011 }
4012}
4013
Ted Kremenek6db61092010-05-05 00:55:15 +00004014enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004015AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004016 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004017 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004018 if (cursorRange.isInvalid())
4019 return CXChildVisit_Recurse;
4020
Douglas Gregor4419b672010-10-21 06:10:04 +00004021 if (clang_isPreprocessing(cursor.kind)) {
4022 // For macro instantiations, just note where the beginning of the macro
4023 // instantiation occurs.
4024 if (cursor.kind == CXCursor_MacroInstantiation) {
4025 Annotated[Loc.int_data] = cursor;
4026 return CXChildVisit_Recurse;
4027 }
4028
Douglas Gregor4419b672010-10-21 06:10:04 +00004029 // Items in the preprocessing record are kept separate from items in
4030 // declarations, so we keep a separate token index.
4031 unsigned SavedTokIdx = TokIdx;
4032 TokIdx = PreprocessingTokIdx;
4033
4034 // Skip tokens up until we catch up to the beginning of the preprocessing
4035 // entry.
4036 while (MoreTokens()) {
4037 const unsigned I = NextToken();
4038 SourceLocation TokLoc = GetTokenLoc(I);
4039 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4040 case RangeBefore:
4041 AdvanceToken();
4042 continue;
4043 case RangeAfter:
4044 case RangeOverlap:
4045 break;
4046 }
4047 break;
4048 }
4049
4050 // Look at all of the tokens within this range.
4051 while (MoreTokens()) {
4052 const unsigned I = NextToken();
4053 SourceLocation TokLoc = GetTokenLoc(I);
4054 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4055 case RangeBefore:
4056 assert(0 && "Infeasible");
4057 case RangeAfter:
4058 break;
4059 case RangeOverlap:
4060 Cursors[I] = cursor;
4061 AdvanceToken();
4062 continue;
4063 }
4064 break;
4065 }
4066
4067 // Save the preprocessing token index; restore the non-preprocessing
4068 // token index.
4069 PreprocessingTokIdx = TokIdx;
4070 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004071 return CXChildVisit_Recurse;
4072 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004073
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004074 if (cursorRange.isInvalid())
4075 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004076
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004077 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4078
Ted Kremeneka333c662010-05-12 05:29:33 +00004079 // Adjust the annotated range based specific declarations.
4080 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4081 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004082 Decl *D = cxcursor::getCursorDecl(cursor);
4083 // Don't visit synthesized ObjC methods, since they have no syntatic
4084 // representation in the source.
4085 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4086 if (MD->isSynthesized())
4087 return CXChildVisit_Continue;
4088 }
4089 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004090 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4091 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004092 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004093 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004094 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004095 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004096 }
4097 }
4098 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004099
Ted Kremenek3f404602010-08-14 01:14:06 +00004100 // If the location of the cursor occurs within a macro instantiation, record
4101 // the spelling location of the cursor in our annotation map. We can then
4102 // paper over the token labelings during a post-processing step to try and
4103 // get cursor mappings for tokens that are the *arguments* of a macro
4104 // instantiation.
4105 if (L.isMacroID()) {
4106 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4107 // Only invalidate the old annotation if it isn't part of a preprocessing
4108 // directive. Here we assume that the default construction of CXCursor
4109 // results in CXCursor.kind being an initialized value (i.e., 0). If
4110 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004111
Ted Kremenek3f404602010-08-14 01:14:06 +00004112 CXCursor &oldC = Annotated[rawEncoding];
4113 if (!clang_isPreprocessing(oldC.kind))
4114 oldC = cursor;
4115 }
4116
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004117 const enum CXCursorKind K = clang_getCursorKind(parent);
4118 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004119 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4120 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004121
4122 while (MoreTokens()) {
4123 const unsigned I = NextToken();
4124 SourceLocation TokLoc = GetTokenLoc(I);
4125 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4126 case RangeBefore:
4127 Cursors[I] = updateC;
4128 AdvanceToken();
4129 continue;
4130 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004131 case RangeOverlap:
4132 break;
4133 }
4134 break;
4135 }
4136
4137 // Visit children to get their cursor information.
4138 const unsigned BeforeChildren = NextToken();
4139 VisitChildren(cursor);
4140 const unsigned AfterChildren = NextToken();
4141
4142 // Adjust 'Last' to the last token within the extent of the cursor.
4143 while (MoreTokens()) {
4144 const unsigned I = NextToken();
4145 SourceLocation TokLoc = GetTokenLoc(I);
4146 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4147 case RangeBefore:
4148 assert(0 && "Infeasible");
4149 case RangeAfter:
4150 break;
4151 case RangeOverlap:
4152 Cursors[I] = updateC;
4153 AdvanceToken();
4154 continue;
4155 }
4156 break;
4157 }
4158 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004159
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004160 // Scan the tokens that are at the beginning of the cursor, but are not
4161 // capture by the child cursors.
4162
4163 // For AST elements within macros, rely on a post-annotate pass to
4164 // to correctly annotate the tokens with cursors. Otherwise we can
4165 // get confusing results of having tokens that map to cursors that really
4166 // are expanded by an instantiation.
4167 if (L.isMacroID())
4168 cursor = clang_getNullCursor();
4169
4170 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4171 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4172 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004173
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004174 Cursors[I] = cursor;
4175 }
4176 // Scan the tokens that are at the end of the cursor, but are not captured
4177 // but the child cursors.
4178 for (unsigned I = AfterChildren; I != Last; ++I)
4179 Cursors[I] = cursor;
4180
4181 TokIdx = Last;
4182 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004183}
4184
Ted Kremenek6db61092010-05-05 00:55:15 +00004185static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4186 CXCursor parent,
4187 CXClientData client_data) {
4188 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4189}
4190
Ted Kremenekab979612010-11-11 08:05:23 +00004191// This gets run a separate thread to avoid stack blowout.
4192static void runAnnotateTokensWorker(void *UserData) {
4193 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4194}
4195
Ted Kremenek6db61092010-05-05 00:55:15 +00004196extern "C" {
4197
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004198void clang_annotateTokens(CXTranslationUnit TU,
4199 CXToken *Tokens, unsigned NumTokens,
4200 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004201
4202 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004203 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004204
Douglas Gregor4419b672010-10-21 06:10:04 +00004205 // Any token we don't specifically annotate will have a NULL cursor.
4206 CXCursor C = clang_getNullCursor();
4207 for (unsigned I = 0; I != NumTokens; ++I)
4208 Cursors[I] = C;
4209
Ted Kremeneka60ed472010-11-16 08:15:36 +00004210 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004211 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004212 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004213
Douglas Gregorbdf60622010-03-05 21:16:25 +00004214 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004215
Douglas Gregor0396f462010-03-19 05:22:59 +00004216 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004217 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004218 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4219 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004220 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4221 clang_getTokenLocation(TU,
4222 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004223
Douglas Gregor0396f462010-03-19 05:22:59 +00004224 // A mapping from the source locations found when re-lexing or traversing the
4225 // region of interest to the corresponding cursors.
4226 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227
4228 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004229 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004230 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4231 std::pair<FileID, unsigned> BeginLocInfo
4232 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4233 std::pair<FileID, unsigned> EndLocInfo
4234 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004235
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004236 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004237 bool Invalid = false;
4238 if (BeginLocInfo.first == EndLocInfo.first &&
4239 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4240 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004241 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4242 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004243 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004244 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004246
4247 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004248 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004249 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004250 Token Tok;
4251 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 reprocess:
4254 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4255 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004256 // don't see it while preprocessing these tokens later, but keep track
4257 // of all of the token locations inside this preprocessing directive so
4258 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004259 //
4260 // FIXME: Some simple tests here could identify macro definitions and
4261 // #undefs, to provide specific cursor kinds for those.
4262 std::vector<SourceLocation> Locations;
4263 do {
4264 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004265 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004266 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004267
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004268 using namespace cxcursor;
4269 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004270 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4271 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004272 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004273 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4274 Annotated[Locations[I].getRawEncoding()] = Cursor;
4275 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004276
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004277 if (Tok.isAtStartOfLine())
4278 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004280 continue;
4281 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004282
Douglas Gregor48072312010-03-18 15:23:44 +00004283 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004284 break;
4285 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004286 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004287
Douglas Gregor0396f462010-03-19 05:22:59 +00004288 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004289 // a specific cursor.
4290 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004291 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004292
4293 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004294 // FIXME: We use a ridiculous stack size here because the data-recursion
4295 // algorithm uses a large stack frame than the non-data recursive version,
4296 // and AnnotationTokensWorker currently transforms the data-recursion
4297 // algorithm back into a traditional recursion by explicitly calling
4298 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004299 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004300 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4301 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004302 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4303 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004304}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004305} // end: extern "C"
4306
4307//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004308// Operations for querying linkage of a cursor.
4309//===----------------------------------------------------------------------===//
4310
4311extern "C" {
4312CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004313 if (!clang_isDeclaration(cursor.kind))
4314 return CXLinkage_Invalid;
4315
Ted Kremenek16b42592010-03-03 06:36:57 +00004316 Decl *D = cxcursor::getCursorDecl(cursor);
4317 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4318 switch (ND->getLinkage()) {
4319 case NoLinkage: return CXLinkage_NoLinkage;
4320 case InternalLinkage: return CXLinkage_Internal;
4321 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4322 case ExternalLinkage: return CXLinkage_External;
4323 };
4324
4325 return CXLinkage_Invalid;
4326}
4327} // end: extern "C"
4328
4329//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004330// Operations for querying language of a cursor.
4331//===----------------------------------------------------------------------===//
4332
4333static CXLanguageKind getDeclLanguage(const Decl *D) {
4334 switch (D->getKind()) {
4335 default:
4336 break;
4337 case Decl::ImplicitParam:
4338 case Decl::ObjCAtDefsField:
4339 case Decl::ObjCCategory:
4340 case Decl::ObjCCategoryImpl:
4341 case Decl::ObjCClass:
4342 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004343 case Decl::ObjCForwardProtocol:
4344 case Decl::ObjCImplementation:
4345 case Decl::ObjCInterface:
4346 case Decl::ObjCIvar:
4347 case Decl::ObjCMethod:
4348 case Decl::ObjCProperty:
4349 case Decl::ObjCPropertyImpl:
4350 case Decl::ObjCProtocol:
4351 return CXLanguage_ObjC;
4352 case Decl::CXXConstructor:
4353 case Decl::CXXConversion:
4354 case Decl::CXXDestructor:
4355 case Decl::CXXMethod:
4356 case Decl::CXXRecord:
4357 case Decl::ClassTemplate:
4358 case Decl::ClassTemplatePartialSpecialization:
4359 case Decl::ClassTemplateSpecialization:
4360 case Decl::Friend:
4361 case Decl::FriendTemplate:
4362 case Decl::FunctionTemplate:
4363 case Decl::LinkageSpec:
4364 case Decl::Namespace:
4365 case Decl::NamespaceAlias:
4366 case Decl::NonTypeTemplateParm:
4367 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004368 case Decl::TemplateTemplateParm:
4369 case Decl::TemplateTypeParm:
4370 case Decl::UnresolvedUsingTypename:
4371 case Decl::UnresolvedUsingValue:
4372 case Decl::Using:
4373 case Decl::UsingDirective:
4374 case Decl::UsingShadow:
4375 return CXLanguage_CPlusPlus;
4376 }
4377
4378 return CXLanguage_C;
4379}
4380
4381extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004382
4383enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4384 if (clang_isDeclaration(cursor.kind))
4385 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4386 if (D->hasAttr<UnavailableAttr>() ||
4387 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4388 return CXAvailability_Available;
4389
4390 if (D->hasAttr<DeprecatedAttr>())
4391 return CXAvailability_Deprecated;
4392 }
4393
4394 return CXAvailability_Available;
4395}
4396
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004397CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4398 if (clang_isDeclaration(cursor.kind))
4399 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4400
4401 return CXLanguage_Invalid;
4402}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004403
4404CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4405 if (clang_isDeclaration(cursor.kind)) {
4406 if (Decl *D = getCursorDecl(cursor)) {
4407 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004408 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004409 }
4410 }
4411
4412 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4413 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004414 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004415 }
4416
4417 return clang_getNullCursor();
4418}
4419
4420CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4421 if (clang_isDeclaration(cursor.kind)) {
4422 if (Decl *D = getCursorDecl(cursor)) {
4423 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004424 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004425 }
4426 }
4427
4428 // FIXME: Note that we can't easily compute the lexical context of a
4429 // statement or expression, so we return nothing.
4430 return clang_getNullCursor();
4431}
4432
Douglas Gregor9f592342010-10-01 20:25:15 +00004433static void CollectOverriddenMethods(DeclContext *Ctx,
4434 ObjCMethodDecl *Method,
4435 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4436 if (!Ctx)
4437 return;
4438
4439 // If we have a class or category implementation, jump straight to the
4440 // interface.
4441 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4442 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4443
4444 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4445 if (!Container)
4446 return;
4447
4448 // Check whether we have a matching method at this level.
4449 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4450 Method->isInstanceMethod()))
4451 if (Method != Overridden) {
4452 // We found an override at this level; there is no need to look
4453 // into other protocols or categories.
4454 Methods.push_back(Overridden);
4455 return;
4456 }
4457
4458 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4459 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4460 PEnd = Protocol->protocol_end();
4461 P != PEnd; ++P)
4462 CollectOverriddenMethods(*P, Method, Methods);
4463 }
4464
4465 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4466 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4467 PEnd = Category->protocol_end();
4468 P != PEnd; ++P)
4469 CollectOverriddenMethods(*P, Method, Methods);
4470 }
4471
4472 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4473 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4474 PEnd = Interface->protocol_end();
4475 P != PEnd; ++P)
4476 CollectOverriddenMethods(*P, Method, Methods);
4477
4478 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4479 Category; Category = Category->getNextClassCategory())
4480 CollectOverriddenMethods(Category, Method, Methods);
4481
4482 // We only look into the superclass if we haven't found anything yet.
4483 if (Methods.empty())
4484 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4485 return CollectOverriddenMethods(Super, Method, Methods);
4486 }
4487}
4488
4489void clang_getOverriddenCursors(CXCursor cursor,
4490 CXCursor **overridden,
4491 unsigned *num_overridden) {
4492 if (overridden)
4493 *overridden = 0;
4494 if (num_overridden)
4495 *num_overridden = 0;
4496 if (!overridden || !num_overridden)
4497 return;
4498
4499 if (!clang_isDeclaration(cursor.kind))
4500 return;
4501
4502 Decl *D = getCursorDecl(cursor);
4503 if (!D)
4504 return;
4505
4506 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004507 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004508 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4509 *num_overridden = CXXMethod->size_overridden_methods();
4510 if (!*num_overridden)
4511 return;
4512
4513 *overridden = new CXCursor [*num_overridden];
4514 unsigned I = 0;
4515 for (CXXMethodDecl::method_iterator
4516 M = CXXMethod->begin_overridden_methods(),
4517 MEnd = CXXMethod->end_overridden_methods();
4518 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004519 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004520 return;
4521 }
4522
4523 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4524 if (!Method)
4525 return;
4526
4527 // Handle Objective-C methods.
4528 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4529 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4530
4531 if (Methods.empty())
4532 return;
4533
4534 *num_overridden = Methods.size();
4535 *overridden = new CXCursor [Methods.size()];
4536 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004537 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004538}
4539
4540void clang_disposeOverriddenCursors(CXCursor *overridden) {
4541 delete [] overridden;
4542}
4543
Douglas Gregorecdcb882010-10-20 22:00:55 +00004544CXFile clang_getIncludedFile(CXCursor cursor) {
4545 if (cursor.kind != CXCursor_InclusionDirective)
4546 return 0;
4547
4548 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4549 return (void *)ID->getFile();
4550}
4551
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004552} // end: extern "C"
4553
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004554
4555//===----------------------------------------------------------------------===//
4556// C++ AST instrospection.
4557//===----------------------------------------------------------------------===//
4558
4559extern "C" {
4560unsigned clang_CXXMethod_isStatic(CXCursor C) {
4561 if (!clang_isDeclaration(C.kind))
4562 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004563
4564 CXXMethodDecl *Method = 0;
4565 Decl *D = cxcursor::getCursorDecl(C);
4566 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4567 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4568 else
4569 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4570 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004571}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004572
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004573} // end: extern "C"
4574
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004575//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004576// Attribute introspection.
4577//===----------------------------------------------------------------------===//
4578
4579extern "C" {
4580CXType clang_getIBOutletCollectionType(CXCursor C) {
4581 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004582 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004583
4584 IBOutletCollectionAttr *A =
4585 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4586
Ted Kremeneka60ed472010-11-16 08:15:36 +00004587 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004588}
4589} // end: extern "C"
4590
4591//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004592// Misc. utility functions.
4593//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004594
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004595/// Default to using an 8 MB stack size on "safety" threads.
4596static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004597
4598namespace clang {
4599
4600bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004601 void (*Fn)(void*), void *UserData,
4602 unsigned Size) {
4603 if (!Size)
4604 Size = GetSafetyThreadStackSize();
4605 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004606 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4607 return CRC.RunSafely(Fn, UserData);
4608}
4609
4610unsigned GetSafetyThreadStackSize() {
4611 return SafetyStackThreadSize;
4612}
4613
4614void SetSafetyThreadStackSize(unsigned Value) {
4615 SafetyStackThreadSize = Value;
4616}
4617
4618}
4619
Ted Kremenek04bb7162010-01-22 22:44:15 +00004620extern "C" {
4621
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004622CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004623 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004624}
4625
4626} // end: extern "C"