blob: f344009948be3f11771c688c24d1cdabd5e12f3d [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 Gregor648220e2010-08-10 15:02:34 +0000342 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
343 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000344 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000345 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000346 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000347 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000348 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000349 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000350 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000351 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000352 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000353
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000354 // Data-recursive visitor functions.
355 bool IsInRegionOfInterest(CXCursor C);
356 bool RunVisitorWorkList(VisitorWorkList &WL);
357 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenek37f1ea02010-11-15 23:11:54 +0000358 bool VisitDataRecursive(Stmt *S) LLVM_ATTRIBUTE_NOINLINE;
Steve Naroff89922f82009-08-31 00:59:03 +0000359};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000360
Ted Kremenekab188932010-01-05 19:32:54 +0000361} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000362
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000363static SourceRange getRawCursorExtent(CXCursor C);
364
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000366 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367}
368
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369/// \brief Visit the given cursor and, if requested by the visitor,
370/// its children.
371///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372/// \param Cursor the cursor to visit.
373///
374/// \param CheckRegionOfInterest if true, then the caller already checked that
375/// this cursor is within the region of interest.
376///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377/// \returns true if the visitation should be aborted, false if it
378/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000379bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380 if (clang_isInvalid(Cursor.kind))
381 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000382
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383 if (clang_isDeclaration(Cursor.kind)) {
384 Decl *D = getCursorDecl(Cursor);
385 assert(D && "Invalid declaration cursor");
386 if (D->getPCHLevel() > MaxPCHLevel)
387 return false;
388
389 if (D->isImplicit())
390 return false;
391 }
392
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 // If we have a range of interest, and this cursor doesn't intersect with it,
394 // we're done.
395 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000396 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000397 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000398 return false;
399 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000400
Douglas Gregorb1373d02010-01-20 20:59:29 +0000401 switch (Visitor(Cursor, Parent, ClientData)) {
402 case CXChildVisit_Break:
403 return true;
404
405 case CXChildVisit_Continue:
406 return false;
407
408 case CXChildVisit_Recurse:
409 return VisitChildren(Cursor);
410 }
411
Douglas Gregorfd643772010-01-25 16:45:46 +0000412 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000413}
414
Douglas Gregor788f5a12010-03-20 00:41:21 +0000415std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
416CursorVisitor::getPreprocessedEntities() {
417 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000418 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000419
420 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000421 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000422
423 // There is no region of interest; we have to walk everything.
424 if (RegionOfInterest.isInvalid())
425 return std::make_pair(PPRec.begin(OnlyLocalDecls),
426 PPRec.end(OnlyLocalDecls));
427
428 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000429 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000430 std::pair<FileID, unsigned> Begin
431 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
432 std::pair<FileID, unsigned> End
433 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
434
435 // The region of interest spans files; we have to walk everything.
436 if (Begin.first != End.first)
437 return std::make_pair(PPRec.begin(OnlyLocalDecls),
438 PPRec.end(OnlyLocalDecls));
439
440 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000441 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000442 if (ByFileMap.empty()) {
443 // Build the mapping from files to sets of preprocessed entities.
444 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
445 EEnd = PPRec.end(OnlyLocalDecls);
446 E != EEnd; ++E) {
447 std::pair<FileID, unsigned> P
448 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
449 ByFileMap[P.first].push_back(*E);
450 }
451 }
452
453 return std::make_pair(ByFileMap[Begin.first].begin(),
454 ByFileMap[Begin.first].end());
455}
456
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000458///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000459/// \returns true if the visitation should be aborted, false if it
460/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000462 if (clang_isReference(Cursor.kind)) {
463 // By definition, references have no children.
464 return false;
465 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
467 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000469 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 if (clang_isDeclaration(Cursor.kind)) {
472 Decl *D = getCursorDecl(Cursor);
473 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000474 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000475 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
Douglas Gregora59e3902010-01-21 23:27:09 +0000477 if (clang_isStatement(Cursor.kind))
478 return Visit(getCursorStmt(Cursor));
479 if (clang_isExpression(Cursor.kind))
480 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000483 CXTranslationUnit tu = getCursorTU(Cursor);
484 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000485 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
486 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000487 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
488 TLEnd = CXXUnit->top_level_end();
489 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000490 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000491 return true;
492 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 } else if (VisitDeclContext(
494 CXXUnit->getASTContext().getTranslationUnitDecl()))
495 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000496
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000498 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000499 // FIXME: Once we have the ability to deserialize a preprocessing record,
500 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000501 PreprocessingRecord::iterator E, EEnd;
502 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000504 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000505 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000506
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 continue;
508 }
509
510 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000511 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 return true;
513
514 continue;
515 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000516
517 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000518 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000519 return true;
520
521 continue;
522 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000523 }
524 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000525 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000527
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 return false;
530}
531
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000532bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000533 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
534 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000535
Ted Kremenek664cffd2010-07-22 11:30:19 +0000536 if (Stmt *Body = B->getBody())
537 return Visit(MakeCXCursor(Body, StmtParent, TU));
538
539 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000540}
541
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000542llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
543 if (RegionOfInterest.isValid()) {
544 SourceRange Range = getRawCursorExtent(Cursor);
545 if (Range.isInvalid())
546 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000547
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000548 switch (CompareRegionOfInterest(Range)) {
549 case RangeBefore:
550 // This declaration comes before the region of interest; skip it.
551 return llvm::Optional<bool>();
552
553 case RangeAfter:
554 // This declaration comes after the region of interest; we're done.
555 return false;
556
557 case RangeOverlap:
558 // This declaration overlaps the region of interest; visit it.
559 break;
560 }
561 }
562 return true;
563}
564
565bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
566 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
567
568 // FIXME: Eventually remove. This part of a hack to support proper
569 // iteration over all Decls contained lexically within an ObjC container.
570 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
571 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
572
573 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000574 Decl *D = *I;
575 if (D->getLexicalDeclContext() != DC)
576 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000577 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000578 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
579 if (!V.hasValue())
580 continue;
581 if (!V.getValue())
582 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000583 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return true;
585 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000586 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000587}
588
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000589bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
590 llvm_unreachable("Translation units are visited directly by Visit()");
591 return false;
592}
593
594bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
595 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
596 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598 return false;
599}
600
601bool CursorVisitor::VisitTagDecl(TagDecl *D) {
602 return VisitDeclContext(D);
603}
604
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000605bool CursorVisitor::VisitClassTemplateSpecializationDecl(
606 ClassTemplateSpecializationDecl *D) {
607 bool ShouldVisitBody = false;
608 switch (D->getSpecializationKind()) {
609 case TSK_Undeclared:
610 case TSK_ImplicitInstantiation:
611 // Nothing to visit
612 return false;
613
614 case TSK_ExplicitInstantiationDeclaration:
615 case TSK_ExplicitInstantiationDefinition:
616 break;
617
618 case TSK_ExplicitSpecialization:
619 ShouldVisitBody = true;
620 break;
621 }
622
623 // Visit the template arguments used in the specialization.
624 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
625 TypeLoc TL = SpecType->getTypeLoc();
626 if (TemplateSpecializationTypeLoc *TSTLoc
627 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
628 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
629 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
630 return true;
631 }
632 }
633
634 if (ShouldVisitBody && VisitCXXRecordDecl(D))
635 return true;
636
637 return false;
638}
639
Douglas Gregor74dbe642010-08-31 19:31:58 +0000640bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
641 ClassTemplatePartialSpecializationDecl *D) {
642 // FIXME: Visit the "outer" template parameter lists on the TagDecl
643 // before visiting these template parameters.
644 if (VisitTemplateParameters(D->getTemplateParameters()))
645 return true;
646
647 // Visit the partial specialization arguments.
648 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
649 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
650 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
651 return true;
652
653 return VisitCXXRecordDecl(D);
654}
655
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000656bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000657 // Visit the default argument.
658 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
659 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
660 if (Visit(DefArg->getTypeLoc()))
661 return true;
662
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000663 return false;
664}
665
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000666bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
667 if (Expr *Init = D->getInitExpr())
668 return Visit(MakeCXCursor(Init, StmtParent, TU));
669 return false;
670}
671
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000672bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
673 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
674 if (Visit(TSInfo->getTypeLoc()))
675 return true;
676
677 return false;
678}
679
Douglas Gregora67e03f2010-09-09 21:42:20 +0000680/// \brief Compare two base or member initializers based on their source order.
681static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
682 CXXBaseOrMemberInitializer const * const *X
683 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
684 CXXBaseOrMemberInitializer const * const *Y
685 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
686
687 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
688 return -1;
689 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
690 return 1;
691 else
692 return 0;
693}
694
Douglas Gregorb1373d02010-01-20 20:59:29 +0000695bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000696 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
697 // Visit the function declaration's syntactic components in the order
698 // written. This requires a bit of work.
699 TypeLoc TL = TSInfo->getTypeLoc();
700 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
701
702 // If we have a function declared directly (without the use of a typedef),
703 // visit just the return type. Otherwise, just visit the function's type
704 // now.
705 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
706 (!FTL && Visit(TL)))
707 return true;
708
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000709 // Visit the nested-name-specifier, if present.
710 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
711 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
712 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000713
714 // Visit the declaration name.
715 if (VisitDeclarationNameInfo(ND->getNameInfo()))
716 return true;
717
718 // FIXME: Visit explicitly-specified template arguments!
719
720 // Visit the function parameters, if we have a function type.
721 if (FTL && VisitFunctionTypeLoc(*FTL, true))
722 return true;
723
724 // FIXME: Attributes?
725 }
726
Douglas Gregora67e03f2010-09-09 21:42:20 +0000727 if (ND->isThisDeclarationADefinition()) {
728 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
729 // Find the initializers that were written in the source.
730 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
731 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
732 IEnd = Constructor->init_end();
733 I != IEnd; ++I) {
734 if (!(*I)->isWritten())
735 continue;
736
737 WrittenInits.push_back(*I);
738 }
739
740 // Sort the initializers in source order
741 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
742 &CompareCXXBaseOrMemberInitializers);
743
744 // Visit the initializers in source order
745 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
746 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
747 if (Init->isMemberInitializer()) {
748 if (Visit(MakeCursorMemberRef(Init->getMember(),
749 Init->getMemberLocation(), TU)))
750 return true;
751 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
752 if (Visit(BaseInfo->getTypeLoc()))
753 return true;
754 }
755
756 // Visit the initializer value.
757 if (Expr *Initializer = Init->getInit())
758 if (Visit(MakeCXCursor(Initializer, ND, TU)))
759 return true;
760 }
761 }
762
763 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
764 return true;
765 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000766
Douglas Gregorb1373d02010-01-20 20:59:29 +0000767 return false;
768}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
771 if (VisitDeclaratorDecl(D))
772 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000773
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000774 if (Expr *BitWidth = D->getBitWidth())
775 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000777 return false;
778}
779
780bool CursorVisitor::VisitVarDecl(VarDecl *D) {
781 if (VisitDeclaratorDecl(D))
782 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 if (Expr *Init = D->getInit())
785 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 return false;
788}
789
Douglas Gregor84b51d72010-09-01 20:16:53 +0000790bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
791 if (VisitDeclaratorDecl(D))
792 return true;
793
794 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
795 if (Expr *DefArg = D->getDefaultArgument())
796 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
797
798 return false;
799}
800
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000801bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
802 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
803 // before visiting these template parameters.
804 if (VisitTemplateParameters(D->getTemplateParameters()))
805 return true;
806
807 return VisitFunctionDecl(D->getTemplatedDecl());
808}
809
Douglas Gregor39d6f072010-08-31 19:02:00 +0000810bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
811 // FIXME: Visit the "outer" template parameter lists on the TagDecl
812 // before visiting these template parameters.
813 if (VisitTemplateParameters(D->getTemplateParameters()))
814 return true;
815
816 return VisitCXXRecordDecl(D->getTemplatedDecl());
817}
818
Douglas Gregor84b51d72010-09-01 20:16:53 +0000819bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
820 if (VisitTemplateParameters(D->getTemplateParameters()))
821 return true;
822
823 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
824 VisitTemplateArgumentLoc(D->getDefaultArgument()))
825 return true;
826
827 return false;
828}
829
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000830bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000831 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
832 if (Visit(TSInfo->getTypeLoc()))
833 return true;
834
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000835 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836 PEnd = ND->param_end();
837 P != PEnd; ++P) {
838 if (Visit(MakeCXCursor(*P, TU)))
839 return true;
840 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 if (ND->isThisDeclarationADefinition() &&
843 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
844 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000846 return false;
847}
848
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000849namespace {
850 struct ContainerDeclsSort {
851 SourceManager &SM;
852 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
853 bool operator()(Decl *A, Decl *B) {
854 SourceLocation L_A = A->getLocStart();
855 SourceLocation L_B = B->getLocStart();
856 assert(L_A.isValid() && L_B.isValid());
857 return SM.isBeforeInTranslationUnit(L_A, L_B);
858 }
859 };
860}
861
Douglas Gregora59e3902010-01-21 23:27:09 +0000862bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000863 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
864 // an @implementation can lexically contain Decls that are not properly
865 // nested in the AST. When we identify such cases, we need to retrofit
866 // this nesting here.
867 if (!DI_current)
868 return VisitDeclContext(D);
869
870 // Scan the Decls that immediately come after the container
871 // in the current DeclContext. If any fall within the
872 // container's lexical region, stash them into a vector
873 // for later processing.
874 llvm::SmallVector<Decl *, 24> DeclsInContainer;
875 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000876 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000877 if (EndLoc.isValid()) {
878 DeclContext::decl_iterator next = *DI_current;
879 while (++next != DE_current) {
880 Decl *D_next = *next;
881 if (!D_next)
882 break;
883 SourceLocation L = D_next->getLocStart();
884 if (!L.isValid())
885 break;
886 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
887 *DI_current = next;
888 DeclsInContainer.push_back(D_next);
889 continue;
890 }
891 break;
892 }
893 }
894
895 // The common case.
896 if (DeclsInContainer.empty())
897 return VisitDeclContext(D);
898
899 // Get all the Decls in the DeclContext, and sort them with the
900 // additional ones we've collected. Then visit them.
901 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
902 I!=E; ++I) {
903 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000904 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
905 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000906 continue;
907 DeclsInContainer.push_back(subDecl);
908 }
909
910 // Now sort the Decls so that they appear in lexical order.
911 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
912 ContainerDeclsSort(SM));
913
914 // Now visit the decls.
915 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
916 E = DeclsInContainer.end(); I != E; ++I) {
917 CXCursor Cursor = MakeCXCursor(*I, TU);
918 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
919 if (!V.hasValue())
920 continue;
921 if (!V.getValue())
922 return false;
923 if (Visit(Cursor, true))
924 return true;
925 }
926 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000927}
928
Douglas Gregorb1373d02010-01-20 20:59:29 +0000929bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000930 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
931 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000932 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000933
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000934 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
935 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
936 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000937 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000938 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000939
Douglas Gregora59e3902010-01-21 23:27:09 +0000940 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000941}
942
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000943bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
944 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
945 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
946 E = PID->protocol_end(); I != E; ++I, ++PL)
947 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
948 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000950 return VisitObjCContainerDecl(PID);
951}
952
Ted Kremenek23173d72010-05-18 21:09:07 +0000953bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000954 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000955 return true;
956
Ted Kremenek23173d72010-05-18 21:09:07 +0000957 // FIXME: This implements a workaround with @property declarations also being
958 // installed in the DeclContext for the @interface. Eventually this code
959 // should be removed.
960 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
961 if (!CDecl || !CDecl->IsClassExtension())
962 return false;
963
964 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
965 if (!ID)
966 return false;
967
968 IdentifierInfo *PropertyId = PD->getIdentifier();
969 ObjCPropertyDecl *prevDecl =
970 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
971
972 if (!prevDecl)
973 return false;
974
975 // Visit synthesized methods since they will be skipped when visiting
976 // the @interface.
977 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000978 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000979 if (Visit(MakeCXCursor(MD, TU)))
980 return true;
981
982 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000983 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000984 if (Visit(MakeCXCursor(MD, TU)))
985 return true;
986
987 return false;
988}
989
Douglas Gregorb1373d02010-01-20 20:59:29 +0000990bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000991 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000992 if (D->getSuperClass() &&
993 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000995 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000996 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000997
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000998 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
999 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1000 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001001 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001002 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001003
Douglas Gregora59e3902010-01-21 23:27:09 +00001004 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001005}
1006
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001007bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1008 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001009}
1010
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001011bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001012 // 'ID' could be null when dealing with invalid code.
1013 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1014 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001017 return VisitObjCImplDecl(D);
1018}
1019
1020bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1021#if 0
1022 // Issue callbacks for super class.
1023 // FIXME: No source location information!
1024 if (D->getSuperClass() &&
1025 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001027 TU)))
1028 return true;
1029#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001030
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001031 return VisitObjCImplDecl(D);
1032}
1033
1034bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1035 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1036 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1037 E = D->protocol_end();
1038 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001039 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001040 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041
1042 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001043}
1044
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1046 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1047 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1048 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001050 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001051}
1052
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001053bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1054 return VisitDeclContext(D);
1055}
1056
Douglas Gregor69319002010-08-31 23:48:11 +00001057bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001058 // Visit nested-name-specifier.
1059 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1060 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1061 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001062
1063 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1064 D->getTargetNameLoc(), TU));
1065}
1066
Douglas Gregor7e242562010-09-01 19:52:22 +00001067bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001068 // Visit nested-name-specifier.
1069 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1070 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1071 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001072
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001073 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1074 return true;
1075
Douglas Gregor7e242562010-09-01 19:52:22 +00001076 return VisitDeclarationNameInfo(D->getNameInfo());
1077}
1078
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001079bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080 // Visit nested-name-specifier.
1081 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1082 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1083 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001084
1085 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1086 D->getIdentLocation(), TU));
1087}
1088
Douglas Gregor7e242562010-09-01 19:52:22 +00001089bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 // Visit nested-name-specifier.
1091 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1092 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1093 return true;
1094
Douglas Gregor7e242562010-09-01 19:52:22 +00001095 return VisitDeclarationNameInfo(D->getNameInfo());
1096}
1097
1098bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1099 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 // Visit nested-name-specifier.
1101 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1102 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1103 return true;
1104
Douglas Gregor7e242562010-09-01 19:52:22 +00001105 return false;
1106}
1107
Douglas Gregor01829d32010-08-31 14:41:23 +00001108bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1109 switch (Name.getName().getNameKind()) {
1110 case clang::DeclarationName::Identifier:
1111 case clang::DeclarationName::CXXLiteralOperatorName:
1112 case clang::DeclarationName::CXXOperatorName:
1113 case clang::DeclarationName::CXXUsingDirective:
1114 return false;
1115
1116 case clang::DeclarationName::CXXConstructorName:
1117 case clang::DeclarationName::CXXDestructorName:
1118 case clang::DeclarationName::CXXConversionFunctionName:
1119 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1120 return Visit(TSInfo->getTypeLoc());
1121 return false;
1122
1123 case clang::DeclarationName::ObjCZeroArgSelector:
1124 case clang::DeclarationName::ObjCOneArgSelector:
1125 case clang::DeclarationName::ObjCMultiArgSelector:
1126 // FIXME: Per-identifier location info?
1127 return false;
1128 }
1129
1130 return false;
1131}
1132
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1134 SourceRange Range) {
1135 // FIXME: This whole routine is a hack to work around the lack of proper
1136 // source information in nested-name-specifiers (PR5791). Since we do have
1137 // a beginning source location, we can visit the first component of the
1138 // nested-name-specifier, if it's a single-token component.
1139 if (!NNS)
1140 return false;
1141
1142 // Get the first component in the nested-name-specifier.
1143 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1144 NNS = Prefix;
1145
1146 switch (NNS->getKind()) {
1147 case NestedNameSpecifier::Namespace:
1148 // FIXME: The token at this source location might actually have been a
1149 // namespace alias, but we don't model that. Lame!
1150 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1151 TU));
1152
1153 case NestedNameSpecifier::TypeSpec: {
1154 // If the type has a form where we know that the beginning of the source
1155 // range matches up with a reference cursor. Visit the appropriate reference
1156 // cursor.
1157 Type *T = NNS->getAsType();
1158 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1159 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1160 if (const TagType *Tag = dyn_cast<TagType>(T))
1161 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1162 if (const TemplateSpecializationType *TST
1163 = dyn_cast<TemplateSpecializationType>(T))
1164 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1165 break;
1166 }
1167
1168 case NestedNameSpecifier::TypeSpecWithTemplate:
1169 case NestedNameSpecifier::Global:
1170 case NestedNameSpecifier::Identifier:
1171 break;
1172 }
1173
1174 return false;
1175}
1176
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001177bool CursorVisitor::VisitTemplateParameters(
1178 const TemplateParameterList *Params) {
1179 if (!Params)
1180 return false;
1181
1182 for (TemplateParameterList::const_iterator P = Params->begin(),
1183 PEnd = Params->end();
1184 P != PEnd; ++P) {
1185 if (Visit(MakeCXCursor(*P, TU)))
1186 return true;
1187 }
1188
1189 return false;
1190}
1191
Douglas Gregor0b36e612010-08-31 20:37:03 +00001192bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1193 switch (Name.getKind()) {
1194 case TemplateName::Template:
1195 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1196
1197 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001198 // Visit the overloaded template set.
1199 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1200 return true;
1201
Douglas Gregor0b36e612010-08-31 20:37:03 +00001202 return false;
1203
1204 case TemplateName::DependentTemplate:
1205 // FIXME: Visit nested-name-specifier.
1206 return false;
1207
1208 case TemplateName::QualifiedTemplate:
1209 // FIXME: Visit nested-name-specifier.
1210 return Visit(MakeCursorTemplateRef(
1211 Name.getAsQualifiedTemplateName()->getDecl(),
1212 Loc, TU));
1213 }
1214
1215 return false;
1216}
1217
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001218bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1219 switch (TAL.getArgument().getKind()) {
1220 case TemplateArgument::Null:
1221 case TemplateArgument::Integral:
1222 return false;
1223
1224 case TemplateArgument::Pack:
1225 // FIXME: Implement when variadic templates come along.
1226 return false;
1227
1228 case TemplateArgument::Type:
1229 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1230 return Visit(TSInfo->getTypeLoc());
1231 return false;
1232
1233 case TemplateArgument::Declaration:
1234 if (Expr *E = TAL.getSourceDeclExpression())
1235 return Visit(MakeCXCursor(E, StmtParent, TU));
1236 return false;
1237
1238 case TemplateArgument::Expression:
1239 if (Expr *E = TAL.getSourceExpression())
1240 return Visit(MakeCXCursor(E, StmtParent, TU));
1241 return false;
1242
1243 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001244 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1245 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001246 }
1247
1248 return false;
1249}
1250
Ted Kremeneka0536d82010-05-07 01:04:29 +00001251bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1252 return VisitDeclContext(D);
1253}
1254
Douglas Gregor01829d32010-08-31 14:41:23 +00001255bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1256 return Visit(TL.getUnqualifiedLoc());
1257}
1258
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001259bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001260 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001261
1262 // Some builtin types (such as Objective-C's "id", "sel", and
1263 // "Class") have associated declarations. Create cursors for those.
1264 QualType VisitType;
1265 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001266 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001268 case BuiltinType::Char_U:
1269 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270 case BuiltinType::Char16:
1271 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001272 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273 case BuiltinType::UInt:
1274 case BuiltinType::ULong:
1275 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001276 case BuiltinType::UInt128:
1277 case BuiltinType::Char_S:
1278 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001279 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001280 case BuiltinType::Short:
1281 case BuiltinType::Int:
1282 case BuiltinType::Long:
1283 case BuiltinType::LongLong:
1284 case BuiltinType::Int128:
1285 case BuiltinType::Float:
1286 case BuiltinType::Double:
1287 case BuiltinType::LongDouble:
1288 case BuiltinType::NullPtr:
1289 case BuiltinType::Overload:
1290 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001292
1293 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001294 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001295
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001296 case BuiltinType::ObjCId:
1297 VisitType = Context.getObjCIdType();
1298 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001299
1300 case BuiltinType::ObjCClass:
1301 VisitType = Context.getObjCClassType();
1302 break;
1303
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001304 case BuiltinType::ObjCSel:
1305 VisitType = Context.getObjCSelType();
1306 break;
1307 }
1308
1309 if (!VisitType.isNull()) {
1310 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001311 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001312 TU));
1313 }
1314
1315 return false;
1316}
1317
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001318bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1319 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1320}
1321
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001322bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1323 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1324}
1325
1326bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1327 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1328}
1329
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001330bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001331 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001332 // no context information with which we can match up the depth/index in the
1333 // type to the appropriate
1334 return false;
1335}
1336
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1338 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1339 return true;
1340
John McCallc12c5bb2010-05-15 11:32:37 +00001341 return false;
1342}
1343
1344bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1345 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1346 return true;
1347
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1349 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1350 TU)))
1351 return true;
1352 }
1353
1354 return false;
1355}
1356
1357bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001358 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359}
1360
1361bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1362 return Visit(TL.getPointeeLoc());
1363}
1364
1365bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1366 return Visit(TL.getPointeeLoc());
1367}
1368
1369bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1370 return Visit(TL.getPointeeLoc());
1371}
1372
1373bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001374 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375}
1376
1377bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001378 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001379}
1380
Douglas Gregor01829d32010-08-31 14:41:23 +00001381bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1382 bool SkipResultType) {
1383 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384 return true;
1385
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001387 if (Decl *D = TL.getArg(I))
1388 if (Visit(MakeCXCursor(D, TU)))
1389 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390
1391 return false;
1392}
1393
1394bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1395 if (Visit(TL.getElementLoc()))
1396 return true;
1397
1398 if (Expr *Size = TL.getSizeExpr())
1399 return Visit(MakeCXCursor(Size, StmtParent, TU));
1400
1401 return false;
1402}
1403
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001404bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1405 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001406 // Visit the template name.
1407 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1408 TL.getTemplateNameLoc()))
1409 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001410
1411 // Visit the template arguments.
1412 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1413 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1414 return true;
1415
1416 return false;
1417}
1418
Douglas Gregor2332c112010-01-21 20:48:56 +00001419bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1420 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1421}
1422
1423bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1424 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1425 return Visit(TSInfo->getTypeLoc());
1426
1427 return false;
1428}
1429
Douglas Gregora59e3902010-01-21 23:27:09 +00001430bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001431 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001432}
1433
Ted Kremenek3064ef92010-08-27 21:34:58 +00001434bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1435 if (D->isDefinition()) {
1436 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1437 E = D->bases_end(); I != E; ++I) {
1438 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1439 return true;
1440 }
1441 }
1442
1443 return VisitTagDecl(D);
1444}
1445
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001446bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001447 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001448 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1449 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001450
1451 // Visit the components of the offsetof expression.
1452 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1453 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1454 const OffsetOfNode &Node = E->getComponent(I);
1455 switch (Node.getKind()) {
1456 case OffsetOfNode::Array:
1457 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1458 StmtParent, TU)))
1459 return true;
1460 break;
1461
1462 case OffsetOfNode::Field:
1463 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1464 TU)))
1465 return true;
1466 break;
1467
1468 case OffsetOfNode::Identifier:
1469 case OffsetOfNode::Base:
1470 continue;
1471 }
1472 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001473
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001474 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001475}
1476
Douglas Gregor336fd812010-01-23 00:40:08 +00001477bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1478 if (E->isArgumentType()) {
1479 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1480 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001481
Douglas Gregor336fd812010-01-23 00:40:08 +00001482 return false;
1483 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001484
Douglas Gregor336fd812010-01-23 00:40:08 +00001485 return VisitExpr(E);
1486}
1487
Douglas Gregor36897b02010-09-10 00:22:18 +00001488bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1489 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1490}
1491
Douglas Gregor648220e2010-08-10 15:02:34 +00001492bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1493 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1494 Visit(E->getArgTInfo2()->getTypeLoc());
1495}
1496
1497bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1498 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1499 return true;
1500
1501 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1502}
1503
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001504bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1505 // Visit the designators.
1506 typedef DesignatedInitExpr::Designator Designator;
1507 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1508 DEnd = E->designators_end();
1509 D != DEnd; ++D) {
1510 if (D->isFieldDesignator()) {
1511 if (FieldDecl *Field = D->getField())
1512 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1513 return true;
1514
1515 continue;
1516 }
1517
1518 if (D->isArrayDesignator()) {
1519 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1520 return true;
1521
1522 continue;
1523 }
1524
1525 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1526 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1527 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1528 return true;
1529 }
1530
1531 // Visit the initializer value itself.
1532 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1533}
1534
Douglas Gregor94802292010-09-02 21:20:16 +00001535bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1536 if (E->isTypeOperand()) {
1537 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1538 return Visit(TSInfo->getTypeLoc());
1539
1540 return false;
1541 }
1542
1543 return VisitExpr(E);
1544}
1545
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001546bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1547 if (E->isTypeOperand()) {
1548 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1549 return Visit(TSInfo->getTypeLoc());
1550
1551 return false;
1552 }
1553
1554 return VisitExpr(E);
1555}
1556
Douglas Gregorab6677e2010-09-08 00:15:04 +00001557bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1558 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1559 return Visit(TSInfo->getTypeLoc());
1560
1561 return false;
1562}
1563
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001564bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1565 // Visit base expression.
1566 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1567 return true;
1568
1569 // Visit the nested-name-specifier.
1570 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1571 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1572 return true;
1573
1574 // Visit the scope type that looks disturbingly like the nested-name-specifier
1575 // but isn't.
1576 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1577 if (Visit(TSInfo->getTypeLoc()))
1578 return true;
1579
1580 // Visit the name of the type being destroyed.
1581 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1582 if (Visit(TSInfo->getTypeLoc()))
1583 return true;
1584
1585 return false;
1586}
1587
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001588bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1589 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1590}
1591
Douglas Gregorbfebed22010-09-03 17:24:10 +00001592bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1593 DependentScopeDeclRefExpr *E) {
1594 // Visit the nested-name-specifier.
1595 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1596 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1597 return true;
1598
1599 // Visit the declaration name.
1600 if (VisitDeclarationNameInfo(E->getNameInfo()))
1601 return true;
1602
1603 // Visit the explicitly-specified template arguments.
1604 if (const ExplicitTemplateArgumentList *ArgList
1605 = E->getOptionalExplicitTemplateArgs()) {
1606 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1607 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1608 Arg != ArgEnd; ++Arg) {
1609 if (VisitTemplateArgumentLoc(*Arg))
1610 return true;
1611 }
1612 }
1613
1614 return false;
1615}
1616
Douglas Gregorab6677e2010-09-08 00:15:04 +00001617bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1618 CXXUnresolvedConstructExpr *E) {
1619 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1620 if (Visit(TSInfo->getTypeLoc()))
1621 return true;
1622
1623 return VisitExpr(E);
1624}
1625
Douglas Gregor25d63622010-09-03 17:35:34 +00001626bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1627 CXXDependentScopeMemberExpr *E) {
1628 // Visit the base expression, if there is one.
1629 if (!E->isImplicitAccess() &&
1630 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1631 return true;
1632
1633 // Visit the nested-name-specifier.
1634 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1635 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1636 return true;
1637
1638 // Visit the declaration name.
1639 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1640 return true;
1641
1642 // Visit the explicitly-specified template arguments.
1643 if (const ExplicitTemplateArgumentList *ArgList
1644 = E->getOptionalExplicitTemplateArgs()) {
1645 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1646 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1647 Arg != ArgEnd; ++Arg) {
1648 if (VisitTemplateArgumentLoc(*Arg))
1649 return true;
1650 }
1651 }
1652
1653 return false;
1654}
1655
Ted Kremenek09dfa372010-02-18 05:46:33 +00001656bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001657 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1658 i != e; ++i)
1659 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001660 return true;
1661
1662 return false;
1663}
1664
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001665//===----------------------------------------------------------------------===//
1666// Data-recursive visitor methods.
1667//===----------------------------------------------------------------------===//
1668
Ted Kremenek28a71942010-11-13 00:36:47 +00001669namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001670#define DEF_JOB(NAME, DATA, KIND)\
1671class NAME : public VisitorJob {\
1672public:\
1673 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1674 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1675 DATA *get() const { return static_cast<DATA*>(dataA); }\
1676};
1677
1678DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1679DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001680DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001681DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1682#undef DEF_JOB
1683
1684class DeclVisit : public VisitorJob {
1685public:
1686 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1687 VisitorJob(parent, VisitorJob::DeclVisitKind,
1688 d, isFirst ? (void*) 1 : (void*) 0) {}
1689 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001690 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001691 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001692 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001693 bool isFirst() const { return dataB ? true : false; }
1694};
1695
1696class TypeLocVisit : public VisitorJob {
1697public:
1698 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1699 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1700 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1701
1702 static bool classof(const VisitorJob *VJ) {
1703 return VJ->getKind() == TypeLocVisitKind;
1704 }
1705
Ted Kremenek82f3c502010-11-15 22:23:26 +00001706 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001707 QualType T = QualType::getFromOpaquePtr(dataA);
1708 return TypeLoc(T, dataB);
1709 }
1710};
1711
Ted Kremenek28a71942010-11-13 00:36:47 +00001712class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1713 VisitorWorkList &WL;
1714 CXCursor Parent;
1715public:
1716 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1717 : WL(wl), Parent(parent) {}
1718
Ted Kremenek73d15c42010-11-13 01:09:29 +00001719 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001720 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001721 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001722 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1723 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001724 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001725 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001726 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001727 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001728 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1729 void VisitForStmt(ForStmt *FS);
1730 void VisitIfStmt(IfStmt *If);
1731 void VisitInitListExpr(InitListExpr *IE);
1732 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001733 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001734 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1735 void VisitOverloadExpr(OverloadExpr *E);
1736 void VisitStmt(Stmt *S);
1737 void VisitSwitchStmt(SwitchStmt *S);
1738 void VisitWhileStmt(WhileStmt *W);
1739 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1740
1741private:
1742 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001743 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001744 void AddTypeLoc(TypeSourceInfo *TI);
1745 void EnqueueChildren(Stmt *S);
1746};
1747} // end anonyous namespace
1748
1749void EnqueueVisitor::AddStmt(Stmt *S) {
1750 if (S)
1751 WL.push_back(StmtVisit(S, Parent));
1752}
Ted Kremenek035dc412010-11-13 00:36:50 +00001753void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001754 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001755 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001756}
1757void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1758 if (TI)
1759 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1760 }
1761void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001762 unsigned size = WL.size();
1763 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1764 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001765 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001766 }
1767 if (size == WL.size())
1768 return;
1769 // Now reverse the entries we just added. This will match the DFS
1770 // ordering performed by the worklist.
1771 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1772 std::reverse(I, E);
1773}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001774void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1775 AddDecl(B->getBlockDecl());
1776}
Ted Kremenek28a71942010-11-13 00:36:47 +00001777void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1778 EnqueueChildren(E);
1779 AddTypeLoc(E->getTypeSourceInfo());
1780}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001781void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1782 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1783 E = S->body_rend(); I != E; ++I) {
1784 AddStmt(*I);
1785 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001786}
1787void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1788 // Enqueue the initializer or constructor arguments.
1789 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1790 AddStmt(E->getConstructorArg(I-1));
1791 // Enqueue the array size, if any.
1792 AddStmt(E->getArraySize());
1793 // Enqueue the allocated type.
1794 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1795 // Enqueue the placement arguments.
1796 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1797 AddStmt(E->getPlacementArg(I-1));
1798}
Ted Kremenek28a71942010-11-13 00:36:47 +00001799void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001800 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1801 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001802 AddStmt(CE->getCallee());
1803 AddStmt(CE->getArg(0));
1804}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001805void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1806 EnqueueChildren(E);
1807 AddTypeLoc(E->getTypeSourceInfo());
1808}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001809void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1810 WL.push_back(DeclRefExprParts(DR, Parent));
1811}
Ted Kremenek035dc412010-11-13 00:36:50 +00001812void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1813 unsigned size = WL.size();
1814 bool isFirst = true;
1815 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1816 D != DEnd; ++D) {
1817 AddDecl(*D, isFirst);
1818 isFirst = false;
1819 }
1820 if (size == WL.size())
1821 return;
1822 // Now reverse the entries we just added. This will match the DFS
1823 // ordering performed by the worklist.
1824 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1825 std::reverse(I, E);
1826}
Ted Kremenek28a71942010-11-13 00:36:47 +00001827void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1828 EnqueueChildren(E);
1829 AddTypeLoc(E->getTypeInfoAsWritten());
1830}
1831void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1832 AddStmt(FS->getBody());
1833 AddStmt(FS->getInc());
1834 AddStmt(FS->getCond());
1835 AddDecl(FS->getConditionVariable());
1836 AddStmt(FS->getInit());
1837}
1838void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1839 AddStmt(If->getElse());
1840 AddStmt(If->getThen());
1841 AddStmt(If->getCond());
1842 AddDecl(If->getConditionVariable());
1843}
1844void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1845 // We care about the syntactic form of the initializer list, only.
1846 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1847 IE = Syntactic;
1848 EnqueueChildren(IE);
1849}
1850void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1851 WL.push_back(MemberExprParts(M, Parent));
1852 AddStmt(M->getBase());
1853}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001854void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1855 AddTypeLoc(E->getEncodedTypeSourceInfo());
1856}
Ted Kremenek28a71942010-11-13 00:36:47 +00001857void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1858 EnqueueChildren(M);
1859 AddTypeLoc(M->getClassReceiverTypeInfo());
1860}
1861void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001862 WL.push_back(OverloadExprParts(E, Parent));
1863}
Ted Kremenek28a71942010-11-13 00:36:47 +00001864void EnqueueVisitor::VisitStmt(Stmt *S) {
1865 EnqueueChildren(S);
1866}
1867void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1868 AddStmt(S->getBody());
1869 AddStmt(S->getCond());
1870 AddDecl(S->getConditionVariable());
1871}
1872void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1873 AddStmt(W->getBody());
1874 AddStmt(W->getCond());
1875 AddDecl(W->getConditionVariable());
1876}
1877void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1878 VisitOverloadExpr(U);
1879 if (!U->isImplicitAccess())
1880 AddStmt(U->getBase());
1881}
Ted Kremenek60458782010-11-12 21:34:16 +00001882
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001883void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001884 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001885}
1886
1887bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1888 if (RegionOfInterest.isValid()) {
1889 SourceRange Range = getRawCursorExtent(C);
1890 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1891 return false;
1892 }
1893 return true;
1894}
1895
1896bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1897 while (!WL.empty()) {
1898 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001899 VisitorJob LI = WL.back();
1900 WL.pop_back();
1901
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001902 // Set the Parent field, then back to its old value once we're done.
1903 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1904
1905 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001906 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001907 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001908 if (!D)
1909 continue;
1910
1911 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001912 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001913 return true;
1914
1915 continue;
1916 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001917 case VisitorJob::TypeLocVisitKind: {
1918 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001919 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001920 return true;
1921 continue;
1922 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001923 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001924 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001925 if (!S)
1926 continue;
1927
Ted Kremenekf1107452010-11-12 18:26:56 +00001928 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001929 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1930
1931 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001932 case Stmt::GotoStmtClass: {
1933 GotoStmt *GS = cast<GotoStmt>(S);
1934 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1935 GS->getLabelLoc(), TU))) {
1936 return true;
1937 }
1938 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001939 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001940 // Cases not yet handled by the data-recursion
1941 // algorithm.
1942 case Stmt::OffsetOfExprClass:
1943 case Stmt::SizeOfAlignOfExprClass:
1944 case Stmt::AddrLabelExprClass:
1945 case Stmt::TypesCompatibleExprClass:
1946 case Stmt::VAArgExprClass:
1947 case Stmt::DesignatedInitExprClass:
1948 case Stmt::CXXTypeidExprClass:
1949 case Stmt::CXXUuidofExprClass:
1950 case Stmt::CXXScalarValueInitExprClass:
1951 case Stmt::CXXPseudoDestructorExprClass:
1952 case Stmt::UnaryTypeTraitExprClass:
1953 case Stmt::DependentScopeDeclRefExprClass:
1954 case Stmt::CXXUnresolvedConstructExprClass:
1955 case Stmt::CXXDependentScopeMemberExprClass:
1956 if (Visit(Cursor))
1957 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001958 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001959 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001960 if (!IsInRegionOfInterest(Cursor))
1961 continue;
1962 switch (Visitor(Cursor, Parent, ClientData)) {
1963 case CXChildVisit_Break:
1964 return true;
1965 case CXChildVisit_Continue:
1966 break;
1967 case CXChildVisit_Recurse:
1968 EnqueueWorkList(WL, S);
1969 break;
1970 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001971 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001972 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001973 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001974 }
1975 case VisitorJob::MemberExprPartsKind: {
1976 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001977 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001978
1979 // Visit the nested-name-specifier
1980 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1981 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1982 return true;
1983
1984 // Visit the declaration name.
1985 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1986 return true;
1987
1988 // Visit the explicitly-specified template arguments, if any.
1989 if (M->hasExplicitTemplateArgs()) {
1990 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1991 *ArgEnd = Arg + M->getNumTemplateArgs();
1992 Arg != ArgEnd; ++Arg) {
1993 if (VisitTemplateArgumentLoc(*Arg))
1994 return true;
1995 }
1996 }
1997 continue;
1998 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001999 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002000 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002001 // Visit nested-name-specifier, if present.
2002 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2003 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2004 return true;
2005 // Visit declaration name.
2006 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2007 return true;
2008 // Visit explicitly-specified template arguments.
2009 if (DR->hasExplicitTemplateArgs()) {
2010 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2011 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2012 *ArgEnd = Arg + Args.NumTemplateArgs;
2013 Arg != ArgEnd; ++Arg)
2014 if (VisitTemplateArgumentLoc(*Arg))
2015 return true;
2016 }
2017 continue;
2018 }
Ted Kremenek60458782010-11-12 21:34:16 +00002019 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002020 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002021 // Visit the nested-name-specifier.
2022 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2023 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2024 return true;
2025 // Visit the declaration name.
2026 if (VisitDeclarationNameInfo(O->getNameInfo()))
2027 return true;
2028 // Visit the overloaded declaration reference.
2029 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2030 return true;
2031 // Visit the explicitly-specified template arguments.
2032 if (const ExplicitTemplateArgumentList *ArgList
2033 = O->getOptionalExplicitTemplateArgs()) {
2034 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2035 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2036 Arg != ArgEnd; ++Arg) {
2037 if (VisitTemplateArgumentLoc(*Arg))
2038 return true;
2039 }
2040 }
2041 continue;
2042 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002043 }
2044 }
2045 return false;
2046}
2047
2048bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002049 VisitorWorkList *WL = 0;
2050 if (!WorkListFreeList.empty()) {
2051 WL = WorkListFreeList.back();
2052 WL->clear();
2053 WorkListFreeList.pop_back();
2054 }
2055 else {
2056 WL = new VisitorWorkList();
2057 WorkListCache.push_back(WL);
2058 }
2059 EnqueueWorkList(*WL, S);
2060 bool result = RunVisitorWorkList(*WL);
2061 WorkListFreeList.push_back(WL);
2062 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002063}
2064
2065//===----------------------------------------------------------------------===//
2066// Misc. API hooks.
2067//===----------------------------------------------------------------------===//
2068
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002069static llvm::sys::Mutex EnableMultithreadingMutex;
2070static bool EnabledMultithreading;
2071
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002072extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002073CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2074 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002075 // Disable pretty stack trace functionality, which will otherwise be a very
2076 // poor citizen of the world and set up all sorts of signal handlers.
2077 llvm::DisablePrettyStackTrace = true;
2078
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002079 // We use crash recovery to make some of our APIs more reliable, implicitly
2080 // enable it.
2081 llvm::CrashRecoveryContext::Enable();
2082
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002083 // Enable support for multithreading in LLVM.
2084 {
2085 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2086 if (!EnabledMultithreading) {
2087 llvm::llvm_start_multithreaded();
2088 EnabledMultithreading = true;
2089 }
2090 }
2091
Douglas Gregora030b7c2010-01-22 20:35:53 +00002092 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002093 if (excludeDeclarationsFromPCH)
2094 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002095 if (displayDiagnostics)
2096 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002097 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002098}
2099
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002100void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002101 if (CIdx)
2102 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002103}
2104
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002105CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002106 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002107 if (!CIdx)
2108 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002109
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002110 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002111 FileSystemOptions FileSystemOpts;
2112 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002113
Douglas Gregor28019772010-04-05 23:52:57 +00002114 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002115 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002116 CXXIdx->getOnlyLocalDecls(),
2117 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002118 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002119}
2120
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002121unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002122 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002123 CXTranslationUnit_CacheCompletionResults |
2124 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002125}
2126
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002127CXTranslationUnit
2128clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2129 const char *source_filename,
2130 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002131 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002132 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002133 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002134 return clang_parseTranslationUnit(CIdx, source_filename,
2135 command_line_args, num_command_line_args,
2136 unsaved_files, num_unsaved_files,
2137 CXTranslationUnit_DetailedPreprocessingRecord);
2138}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002139
2140struct ParseTranslationUnitInfo {
2141 CXIndex CIdx;
2142 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002143 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002144 int num_command_line_args;
2145 struct CXUnsavedFile *unsaved_files;
2146 unsigned num_unsaved_files;
2147 unsigned options;
2148 CXTranslationUnit result;
2149};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002150static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002151 ParseTranslationUnitInfo *PTUI =
2152 static_cast<ParseTranslationUnitInfo*>(UserData);
2153 CXIndex CIdx = PTUI->CIdx;
2154 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002155 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002156 int num_command_line_args = PTUI->num_command_line_args;
2157 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2158 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2159 unsigned options = PTUI->options;
2160 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002161
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002162 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002163 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002164
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002165 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2166
Douglas Gregor44c181a2010-07-23 00:33:23 +00002167 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002168 bool CompleteTranslationUnit
2169 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002170 bool CacheCodeCompetionResults
2171 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002172 bool CXXPrecompilePreamble
2173 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2174 bool CXXChainedPCH
2175 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002176
Douglas Gregor5352ac02010-01-28 00:27:43 +00002177 // Configure the diagnostics.
2178 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002179 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2180 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002181
Douglas Gregor4db64a42010-01-23 00:14:00 +00002182 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2183 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002184 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002185 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002186 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002187 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2188 Buffer));
2189 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002190
Douglas Gregorb10daed2010-10-11 16:52:23 +00002191 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002192
Ted Kremenek139ba862009-10-22 00:03:57 +00002193 // The 'source_filename' argument is optional. If the caller does not
2194 // specify it then it is assumed that the source file is specified
2195 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002196 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002197 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002198
2199 // Since the Clang C library is primarily used by batch tools dealing with
2200 // (often very broken) source code, where spell-checking can have a
2201 // significant negative impact on performance (particularly when
2202 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002203 // Only do this if we haven't found a spell-checking-related argument.
2204 bool FoundSpellCheckingArgument = false;
2205 for (int I = 0; I != num_command_line_args; ++I) {
2206 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2207 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2208 FoundSpellCheckingArgument = true;
2209 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002210 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002211 }
2212 if (!FoundSpellCheckingArgument)
2213 Args.push_back("-fno-spell-checking");
2214
2215 Args.insert(Args.end(), command_line_args,
2216 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002217
Douglas Gregor44c181a2010-07-23 00:33:23 +00002218 // Do we need the detailed preprocessing record?
2219 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002220 Args.push_back("-Xclang");
2221 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002222 }
2223
Douglas Gregorb10daed2010-10-11 16:52:23 +00002224 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002225 llvm::OwningPtr<ASTUnit> Unit(
2226 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2227 Diags,
2228 CXXIdx->getClangResourcesPath(),
2229 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002230 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002231 RemappedFiles.data(),
2232 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002233 PrecompilePreamble,
2234 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002235 CacheCodeCompetionResults,
2236 CXXPrecompilePreamble,
2237 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002238
Douglas Gregorb10daed2010-10-11 16:52:23 +00002239 if (NumErrors != Diags->getNumErrors()) {
2240 // Make sure to check that 'Unit' is non-NULL.
2241 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2242 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2243 DEnd = Unit->stored_diag_end();
2244 D != DEnd; ++D) {
2245 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2246 CXString Msg = clang_formatDiagnostic(&Diag,
2247 clang_defaultDiagnosticDisplayOptions());
2248 fprintf(stderr, "%s\n", clang_getCString(Msg));
2249 clang_disposeString(Msg);
2250 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002251#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002252 // On Windows, force a flush, since there may be multiple copies of
2253 // stderr and stdout in the file system, all with different buffers
2254 // but writing to the same device.
2255 fflush(stderr);
2256#endif
2257 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002258 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002259
Ted Kremeneka60ed472010-11-16 08:15:36 +00002260 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002261}
2262CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2263 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002264 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002265 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002266 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002267 unsigned num_unsaved_files,
2268 unsigned options) {
2269 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002270 num_command_line_args, unsaved_files,
2271 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002272 llvm::CrashRecoveryContext CRC;
2273
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002274 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002275 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2276 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2277 fprintf(stderr, " 'command_line_args' : [");
2278 for (int i = 0; i != num_command_line_args; ++i) {
2279 if (i)
2280 fprintf(stderr, ", ");
2281 fprintf(stderr, "'%s'", command_line_args[i]);
2282 }
2283 fprintf(stderr, "],\n");
2284 fprintf(stderr, " 'unsaved_files' : [");
2285 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2286 if (i)
2287 fprintf(stderr, ", ");
2288 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2289 unsaved_files[i].Length);
2290 }
2291 fprintf(stderr, "],\n");
2292 fprintf(stderr, " 'options' : %d,\n", options);
2293 fprintf(stderr, "}\n");
2294
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002295 return 0;
2296 }
2297
2298 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002299}
2300
Douglas Gregor19998442010-08-13 15:35:05 +00002301unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2302 return CXSaveTranslationUnit_None;
2303}
2304
2305int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2306 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002307 if (!TU)
2308 return 1;
2309
Ted Kremeneka60ed472010-11-16 08:15:36 +00002310 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002311}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002312
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002313void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002314 if (CTUnit) {
2315 // If the translation unit has been marked as unsafe to free, just discard
2316 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002317 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002318 return;
2319
Ted Kremeneka60ed472010-11-16 08:15:36 +00002320 delete static_cast<ASTUnit *>(CTUnit->TUData);
2321 disposeCXStringPool(CTUnit->StringPool);
2322 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002323 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002324}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002325
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002326unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2327 return CXReparse_None;
2328}
2329
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002330struct ReparseTranslationUnitInfo {
2331 CXTranslationUnit TU;
2332 unsigned num_unsaved_files;
2333 struct CXUnsavedFile *unsaved_files;
2334 unsigned options;
2335 int result;
2336};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002337
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002338static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002339 ReparseTranslationUnitInfo *RTUI =
2340 static_cast<ReparseTranslationUnitInfo*>(UserData);
2341 CXTranslationUnit TU = RTUI->TU;
2342 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2343 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2344 unsigned options = RTUI->options;
2345 (void) options;
2346 RTUI->result = 1;
2347
Douglas Gregorabc563f2010-07-19 21:46:24 +00002348 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002349 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002350
Ted Kremeneka60ed472010-11-16 08:15:36 +00002351 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002352 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002353
2354 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2355 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2356 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2357 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002358 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002359 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2360 Buffer));
2361 }
2362
Douglas Gregor593b0c12010-09-23 18:47:53 +00002363 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2364 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002365}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002366
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002367int clang_reparseTranslationUnit(CXTranslationUnit TU,
2368 unsigned num_unsaved_files,
2369 struct CXUnsavedFile *unsaved_files,
2370 unsigned options) {
2371 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2372 options, 0 };
2373 llvm::CrashRecoveryContext CRC;
2374
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002375 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002376 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002377 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002378 return 1;
2379 }
2380
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002381
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002382 return RTUI.result;
2383}
2384
Douglas Gregordf95a132010-08-09 20:45:32 +00002385
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002386CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002387 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002388 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002389
Ted Kremeneka60ed472010-11-16 08:15:36 +00002390 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002391 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002392}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002393
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002394CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002395 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002396 return Result;
2397}
2398
Ted Kremenekfb480492010-01-13 21:46:36 +00002399} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002400
Ted Kremenekfb480492010-01-13 21:46:36 +00002401//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002402// CXSourceLocation and CXSourceRange Operations.
2403//===----------------------------------------------------------------------===//
2404
Douglas Gregorb9790342010-01-22 21:44:22 +00002405extern "C" {
2406CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002407 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002408 return Result;
2409}
2410
2411unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002412 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2413 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2414 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002415}
2416
2417CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2418 CXFile file,
2419 unsigned line,
2420 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002421 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002422 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002423
Ted Kremeneka60ed472010-11-16 08:15:36 +00002424 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002425 SourceLocation SLoc
2426 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002428 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002429 if (SLoc.isInvalid()) return clang_getNullLocation();
2430
2431 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2432}
2433
2434CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2435 CXFile file,
2436 unsigned offset) {
2437 if (!tu || !file)
2438 return clang_getNullLocation();
2439
Ted Kremeneka60ed472010-11-16 08:15:36 +00002440 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002441 SourceLocation Start
2442 = CXXUnit->getSourceManager().getLocation(
2443 static_cast<const FileEntry *>(file),
2444 1, 1);
2445 if (Start.isInvalid()) return clang_getNullLocation();
2446
2447 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2448
2449 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002450
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002451 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002452}
2453
Douglas Gregor5352ac02010-01-28 00:27:43 +00002454CXSourceRange clang_getNullRange() {
2455 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2456 return Result;
2457}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002458
Douglas Gregor5352ac02010-01-28 00:27:43 +00002459CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2460 if (begin.ptr_data[0] != end.ptr_data[0] ||
2461 begin.ptr_data[1] != end.ptr_data[1])
2462 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002463
2464 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002465 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002466 return Result;
2467}
2468
Douglas Gregor46766dc2010-01-26 19:19:08 +00002469void clang_getInstantiationLocation(CXSourceLocation location,
2470 CXFile *file,
2471 unsigned *line,
2472 unsigned *column,
2473 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002474 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2475
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002476 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002477 if (file)
2478 *file = 0;
2479 if (line)
2480 *line = 0;
2481 if (column)
2482 *column = 0;
2483 if (offset)
2484 *offset = 0;
2485 return;
2486 }
2487
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002488 const SourceManager &SM =
2489 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002490 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002491
2492 if (file)
2493 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2494 if (line)
2495 *line = SM.getInstantiationLineNumber(InstLoc);
2496 if (column)
2497 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002498 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002499 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002500}
2501
Douglas Gregora9b06d42010-11-09 06:24:54 +00002502void clang_getSpellingLocation(CXSourceLocation location,
2503 CXFile *file,
2504 unsigned *line,
2505 unsigned *column,
2506 unsigned *offset) {
2507 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2508
2509 if (!location.ptr_data[0] || Loc.isInvalid()) {
2510 if (file)
2511 *file = 0;
2512 if (line)
2513 *line = 0;
2514 if (column)
2515 *column = 0;
2516 if (offset)
2517 *offset = 0;
2518 return;
2519 }
2520
2521 const SourceManager &SM =
2522 *static_cast<const SourceManager*>(location.ptr_data[0]);
2523 SourceLocation SpellLoc = Loc;
2524 if (SpellLoc.isMacroID()) {
2525 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2526 if (SimpleSpellingLoc.isFileID() &&
2527 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2528 SpellLoc = SimpleSpellingLoc;
2529 else
2530 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2531 }
2532
2533 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2534 FileID FID = LocInfo.first;
2535 unsigned FileOffset = LocInfo.second;
2536
2537 if (file)
2538 *file = (void *)SM.getFileEntryForID(FID);
2539 if (line)
2540 *line = SM.getLineNumber(FID, FileOffset);
2541 if (column)
2542 *column = SM.getColumnNumber(FID, FileOffset);
2543 if (offset)
2544 *offset = FileOffset;
2545}
2546
Douglas Gregor1db19de2010-01-19 21:36:55 +00002547CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002548 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002549 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002550 return Result;
2551}
2552
2553CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002554 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002555 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002556 return Result;
2557}
2558
Douglas Gregorb9790342010-01-22 21:44:22 +00002559} // end: extern "C"
2560
Douglas Gregor1db19de2010-01-19 21:36:55 +00002561//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002562// CXFile Operations.
2563//===----------------------------------------------------------------------===//
2564
2565extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002566CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002567 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002568 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Steve Naroff88145032009-10-27 14:35:18 +00002570 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002571 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002572}
2573
2574time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002575 if (!SFile)
2576 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002577
Steve Naroff88145032009-10-27 14:35:18 +00002578 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2579 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002580}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Douglas Gregorb9790342010-01-22 21:44:22 +00002582CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2583 if (!tu)
2584 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Ted Kremeneka60ed472010-11-16 08:15:36 +00002586 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002587
Douglas Gregorb9790342010-01-22 21:44:22 +00002588 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002589 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2590 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002591 return const_cast<FileEntry *>(File);
2592}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002593
Ted Kremenekfb480492010-01-13 21:46:36 +00002594} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002595
Ted Kremenekfb480492010-01-13 21:46:36 +00002596//===----------------------------------------------------------------------===//
2597// CXCursor Operations.
2598//===----------------------------------------------------------------------===//
2599
Ted Kremenekfb480492010-01-13 21:46:36 +00002600static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002601 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2602 return getDeclFromExpr(CE->getSubExpr());
2603
Ted Kremenekfb480492010-01-13 21:46:36 +00002604 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2605 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002606 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2607 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002608 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2609 return ME->getMemberDecl();
2610 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2611 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002612 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2613 return PRE->getProperty();
2614
Ted Kremenekfb480492010-01-13 21:46:36 +00002615 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2616 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002617 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2618 if (!CE->isElidable())
2619 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002620 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2621 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002622
Douglas Gregordb1314e2010-10-01 21:11:22 +00002623 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2624 return PE->getProtocol();
2625
Ted Kremenekfb480492010-01-13 21:46:36 +00002626 return 0;
2627}
2628
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002629static SourceLocation getLocationFromExpr(Expr *E) {
2630 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2631 return /*FIXME:*/Msg->getLeftLoc();
2632 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2633 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002634 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2635 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002636 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2637 return Member->getMemberLoc();
2638 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2639 return Ivar->getLocation();
2640 return E->getLocStart();
2641}
2642
Ted Kremenekfb480492010-01-13 21:46:36 +00002643extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002644
2645unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002646 CXCursorVisitor visitor,
2647 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002648 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2649 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002650 return CursorVis.VisitChildren(parent);
2651}
2652
David Chisnall3387c652010-11-03 14:12:26 +00002653#ifndef __has_feature
2654#define __has_feature(x) 0
2655#endif
2656#if __has_feature(blocks)
2657typedef enum CXChildVisitResult
2658 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2659
2660static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2661 CXClientData client_data) {
2662 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2663 return block(cursor, parent);
2664}
2665#else
2666// If we are compiled with a compiler that doesn't have native blocks support,
2667// define and call the block manually, so the
2668typedef struct _CXChildVisitResult
2669{
2670 void *isa;
2671 int flags;
2672 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002673 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2674 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002675} *CXCursorVisitorBlock;
2676
2677static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2678 CXClientData client_data) {
2679 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2680 return block->invoke(block, cursor, parent);
2681}
2682#endif
2683
2684
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002685unsigned clang_visitChildrenWithBlock(CXCursor parent,
2686 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002687 return clang_visitChildren(parent, visitWithBlock, block);
2688}
2689
Douglas Gregor78205d42010-01-20 21:45:58 +00002690static CXString getDeclSpelling(Decl *D) {
2691 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2692 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002693 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002694
Douglas Gregor78205d42010-01-20 21:45:58 +00002695 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002696 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002697
Douglas Gregor78205d42010-01-20 21:45:58 +00002698 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2699 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2700 // and returns different names. NamedDecl returns the class name and
2701 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002702 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002703
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002704 if (isa<UsingDirectiveDecl>(D))
2705 return createCXString("");
2706
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002707 llvm::SmallString<1024> S;
2708 llvm::raw_svector_ostream os(S);
2709 ND->printName(os);
2710
2711 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002712}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002713
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002714CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002715 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002716 return clang_getTranslationUnitSpelling(
2717 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002718
Steve Narofff334b4e2009-09-02 18:26:48 +00002719 if (clang_isReference(C.kind)) {
2720 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002721 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002722 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002723 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002724 }
2725 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002726 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002727 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002728 }
2729 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002730 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002731 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002732 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002733 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002734 case CXCursor_CXXBaseSpecifier: {
2735 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2736 return createCXString(B->getType().getAsString());
2737 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002738 case CXCursor_TypeRef: {
2739 TypeDecl *Type = getCursorTypeRef(C).first;
2740 assert(Type && "Missing type decl");
2741
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002742 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2743 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002744 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002745 case CXCursor_TemplateRef: {
2746 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002747 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002748
2749 return createCXString(Template->getNameAsString());
2750 }
Douglas Gregor69319002010-08-31 23:48:11 +00002751
2752 case CXCursor_NamespaceRef: {
2753 NamedDecl *NS = getCursorNamespaceRef(C).first;
2754 assert(NS && "Missing namespace decl");
2755
2756 return createCXString(NS->getNameAsString());
2757 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002758
Douglas Gregora67e03f2010-09-09 21:42:20 +00002759 case CXCursor_MemberRef: {
2760 FieldDecl *Field = getCursorMemberRef(C).first;
2761 assert(Field && "Missing member decl");
2762
2763 return createCXString(Field->getNameAsString());
2764 }
2765
Douglas Gregor36897b02010-09-10 00:22:18 +00002766 case CXCursor_LabelRef: {
2767 LabelStmt *Label = getCursorLabelRef(C).first;
2768 assert(Label && "Missing label");
2769
2770 return createCXString(Label->getID()->getName());
2771 }
2772
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002773 case CXCursor_OverloadedDeclRef: {
2774 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2775 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2776 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2777 return createCXString(ND->getNameAsString());
2778 return createCXString("");
2779 }
2780 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2781 return createCXString(E->getName().getAsString());
2782 OverloadedTemplateStorage *Ovl
2783 = Storage.get<OverloadedTemplateStorage*>();
2784 if (Ovl->size() == 0)
2785 return createCXString("");
2786 return createCXString((*Ovl->begin())->getNameAsString());
2787 }
2788
Daniel Dunbaracca7252009-11-30 20:42:49 +00002789 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002790 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002791 }
2792 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002793
2794 if (clang_isExpression(C.kind)) {
2795 Decl *D = getDeclFromExpr(getCursorExpr(C));
2796 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002797 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002798 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002799 }
2800
Douglas Gregor36897b02010-09-10 00:22:18 +00002801 if (clang_isStatement(C.kind)) {
2802 Stmt *S = getCursorStmt(C);
2803 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2804 return createCXString(Label->getID()->getName());
2805
2806 return createCXString("");
2807 }
2808
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002809 if (C.kind == CXCursor_MacroInstantiation)
2810 return createCXString(getCursorMacroInstantiation(C)->getName()
2811 ->getNameStart());
2812
Douglas Gregor572feb22010-03-18 18:04:21 +00002813 if (C.kind == CXCursor_MacroDefinition)
2814 return createCXString(getCursorMacroDefinition(C)->getName()
2815 ->getNameStart());
2816
Douglas Gregorecdcb882010-10-20 22:00:55 +00002817 if (C.kind == CXCursor_InclusionDirective)
2818 return createCXString(getCursorInclusionDirective(C)->getFileName());
2819
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002820 if (clang_isDeclaration(C.kind))
2821 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002822
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002823 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002824}
2825
Douglas Gregor358559d2010-10-02 22:49:11 +00002826CXString clang_getCursorDisplayName(CXCursor C) {
2827 if (!clang_isDeclaration(C.kind))
2828 return clang_getCursorSpelling(C);
2829
2830 Decl *D = getCursorDecl(C);
2831 if (!D)
2832 return createCXString("");
2833
2834 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2835 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2836 D = FunTmpl->getTemplatedDecl();
2837
2838 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2839 llvm::SmallString<64> Str;
2840 llvm::raw_svector_ostream OS(Str);
2841 OS << Function->getNameAsString();
2842 if (Function->getPrimaryTemplate())
2843 OS << "<>";
2844 OS << "(";
2845 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2846 if (I)
2847 OS << ", ";
2848 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2849 }
2850
2851 if (Function->isVariadic()) {
2852 if (Function->getNumParams())
2853 OS << ", ";
2854 OS << "...";
2855 }
2856 OS << ")";
2857 return createCXString(OS.str());
2858 }
2859
2860 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2861 llvm::SmallString<64> Str;
2862 llvm::raw_svector_ostream OS(Str);
2863 OS << ClassTemplate->getNameAsString();
2864 OS << "<";
2865 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2866 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2867 if (I)
2868 OS << ", ";
2869
2870 NamedDecl *Param = Params->getParam(I);
2871 if (Param->getIdentifier()) {
2872 OS << Param->getIdentifier()->getName();
2873 continue;
2874 }
2875
2876 // There is no parameter name, which makes this tricky. Try to come up
2877 // with something useful that isn't too long.
2878 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2879 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2880 else if (NonTypeTemplateParmDecl *NTTP
2881 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2882 OS << NTTP->getType().getAsString(Policy);
2883 else
2884 OS << "template<...> class";
2885 }
2886
2887 OS << ">";
2888 return createCXString(OS.str());
2889 }
2890
2891 if (ClassTemplateSpecializationDecl *ClassSpec
2892 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2893 // If the type was explicitly written, use that.
2894 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2895 return createCXString(TSInfo->getType().getAsString(Policy));
2896
2897 llvm::SmallString<64> Str;
2898 llvm::raw_svector_ostream OS(Str);
2899 OS << ClassSpec->getNameAsString();
2900 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002901 ClassSpec->getTemplateArgs().data(),
2902 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002903 Policy);
2904 return createCXString(OS.str());
2905 }
2906
2907 return clang_getCursorSpelling(C);
2908}
2909
Ted Kremeneke68fff62010-02-17 00:41:32 +00002910CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002911 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002912 case CXCursor_FunctionDecl:
2913 return createCXString("FunctionDecl");
2914 case CXCursor_TypedefDecl:
2915 return createCXString("TypedefDecl");
2916 case CXCursor_EnumDecl:
2917 return createCXString("EnumDecl");
2918 case CXCursor_EnumConstantDecl:
2919 return createCXString("EnumConstantDecl");
2920 case CXCursor_StructDecl:
2921 return createCXString("StructDecl");
2922 case CXCursor_UnionDecl:
2923 return createCXString("UnionDecl");
2924 case CXCursor_ClassDecl:
2925 return createCXString("ClassDecl");
2926 case CXCursor_FieldDecl:
2927 return createCXString("FieldDecl");
2928 case CXCursor_VarDecl:
2929 return createCXString("VarDecl");
2930 case CXCursor_ParmDecl:
2931 return createCXString("ParmDecl");
2932 case CXCursor_ObjCInterfaceDecl:
2933 return createCXString("ObjCInterfaceDecl");
2934 case CXCursor_ObjCCategoryDecl:
2935 return createCXString("ObjCCategoryDecl");
2936 case CXCursor_ObjCProtocolDecl:
2937 return createCXString("ObjCProtocolDecl");
2938 case CXCursor_ObjCPropertyDecl:
2939 return createCXString("ObjCPropertyDecl");
2940 case CXCursor_ObjCIvarDecl:
2941 return createCXString("ObjCIvarDecl");
2942 case CXCursor_ObjCInstanceMethodDecl:
2943 return createCXString("ObjCInstanceMethodDecl");
2944 case CXCursor_ObjCClassMethodDecl:
2945 return createCXString("ObjCClassMethodDecl");
2946 case CXCursor_ObjCImplementationDecl:
2947 return createCXString("ObjCImplementationDecl");
2948 case CXCursor_ObjCCategoryImplDecl:
2949 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002950 case CXCursor_CXXMethod:
2951 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002952 case CXCursor_UnexposedDecl:
2953 return createCXString("UnexposedDecl");
2954 case CXCursor_ObjCSuperClassRef:
2955 return createCXString("ObjCSuperClassRef");
2956 case CXCursor_ObjCProtocolRef:
2957 return createCXString("ObjCProtocolRef");
2958 case CXCursor_ObjCClassRef:
2959 return createCXString("ObjCClassRef");
2960 case CXCursor_TypeRef:
2961 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002962 case CXCursor_TemplateRef:
2963 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002964 case CXCursor_NamespaceRef:
2965 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002966 case CXCursor_MemberRef:
2967 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002968 case CXCursor_LabelRef:
2969 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002970 case CXCursor_OverloadedDeclRef:
2971 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002972 case CXCursor_UnexposedExpr:
2973 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002974 case CXCursor_BlockExpr:
2975 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002976 case CXCursor_DeclRefExpr:
2977 return createCXString("DeclRefExpr");
2978 case CXCursor_MemberRefExpr:
2979 return createCXString("MemberRefExpr");
2980 case CXCursor_CallExpr:
2981 return createCXString("CallExpr");
2982 case CXCursor_ObjCMessageExpr:
2983 return createCXString("ObjCMessageExpr");
2984 case CXCursor_UnexposedStmt:
2985 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002986 case CXCursor_LabelStmt:
2987 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002988 case CXCursor_InvalidFile:
2989 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002990 case CXCursor_InvalidCode:
2991 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002992 case CXCursor_NoDeclFound:
2993 return createCXString("NoDeclFound");
2994 case CXCursor_NotImplemented:
2995 return createCXString("NotImplemented");
2996 case CXCursor_TranslationUnit:
2997 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002998 case CXCursor_UnexposedAttr:
2999 return createCXString("UnexposedAttr");
3000 case CXCursor_IBActionAttr:
3001 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003002 case CXCursor_IBOutletAttr:
3003 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003004 case CXCursor_IBOutletCollectionAttr:
3005 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003006 case CXCursor_PreprocessingDirective:
3007 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003008 case CXCursor_MacroDefinition:
3009 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003010 case CXCursor_MacroInstantiation:
3011 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003012 case CXCursor_InclusionDirective:
3013 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003014 case CXCursor_Namespace:
3015 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003016 case CXCursor_LinkageSpec:
3017 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003018 case CXCursor_CXXBaseSpecifier:
3019 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003020 case CXCursor_Constructor:
3021 return createCXString("CXXConstructor");
3022 case CXCursor_Destructor:
3023 return createCXString("CXXDestructor");
3024 case CXCursor_ConversionFunction:
3025 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003026 case CXCursor_TemplateTypeParameter:
3027 return createCXString("TemplateTypeParameter");
3028 case CXCursor_NonTypeTemplateParameter:
3029 return createCXString("NonTypeTemplateParameter");
3030 case CXCursor_TemplateTemplateParameter:
3031 return createCXString("TemplateTemplateParameter");
3032 case CXCursor_FunctionTemplate:
3033 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003034 case CXCursor_ClassTemplate:
3035 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003036 case CXCursor_ClassTemplatePartialSpecialization:
3037 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003038 case CXCursor_NamespaceAlias:
3039 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003040 case CXCursor_UsingDirective:
3041 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003042 case CXCursor_UsingDeclaration:
3043 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003044 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003045
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003046 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003047 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003048}
Steve Naroff89922f82009-08-31 00:59:03 +00003049
Ted Kremeneke68fff62010-02-17 00:41:32 +00003050enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3051 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003052 CXClientData client_data) {
3053 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003054
3055 // If our current best cursor is the construction of a temporary object,
3056 // don't replace that cursor with a type reference, because we want
3057 // clang_getCursor() to point at the constructor.
3058 if (clang_isExpression(BestCursor->kind) &&
3059 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3060 cursor.kind == CXCursor_TypeRef)
3061 return CXChildVisit_Recurse;
3062
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003063 *BestCursor = cursor;
3064 return CXChildVisit_Recurse;
3065}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003066
Douglas Gregorb9790342010-01-22 21:44:22 +00003067CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3068 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003069 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003070
Ted Kremeneka60ed472010-11-16 08:15:36 +00003071 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003072 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3073
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003074 // Translate the given source location to make it point at the beginning of
3075 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003076 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003077
3078 // Guard against an invalid SourceLocation, or we may assert in one
3079 // of the following calls.
3080 if (SLoc.isInvalid())
3081 return clang_getNullCursor();
3082
Douglas Gregor40749ee2010-11-03 00:35:38 +00003083 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003084 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3085 CXXUnit->getASTContext().getLangOptions());
3086
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003087 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3088 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003089 // FIXME: Would be great to have a "hint" cursor, then walk from that
3090 // hint cursor upward until we find a cursor whose source range encloses
3091 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003092 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3093 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003094 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003095 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003096 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003097
3098 if (Logging) {
3099 CXFile SearchFile;
3100 unsigned SearchLine, SearchColumn;
3101 CXFile ResultFile;
3102 unsigned ResultLine, ResultColumn;
3103 CXString SearchFileName, ResultFileName, KindSpelling;
3104 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3105
3106 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3107 0);
3108 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3109 &ResultColumn, 0);
3110 SearchFileName = clang_getFileName(SearchFile);
3111 ResultFileName = clang_getFileName(ResultFile);
3112 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3113 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3114 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3115 clang_getCString(KindSpelling),
3116 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3117 clang_disposeString(SearchFileName);
3118 clang_disposeString(ResultFileName);
3119 clang_disposeString(KindSpelling);
3120 }
3121
Ted Kremeneke68fff62010-02-17 00:41:32 +00003122 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003123}
3124
Ted Kremenek73885552009-11-17 19:28:59 +00003125CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003126 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003127}
3128
3129unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003130 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003131}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003132
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003133unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003134 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3135}
3136
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003137unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003138 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3139}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003140
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003141unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003142 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3143}
3144
Douglas Gregor97b98722010-01-19 23:20:36 +00003145unsigned clang_isExpression(enum CXCursorKind K) {
3146 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3147}
3148
3149unsigned clang_isStatement(enum CXCursorKind K) {
3150 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3151}
3152
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003153unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3154 return K == CXCursor_TranslationUnit;
3155}
3156
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003157unsigned clang_isPreprocessing(enum CXCursorKind K) {
3158 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3159}
3160
Ted Kremenekad6eff62010-03-08 21:17:29 +00003161unsigned clang_isUnexposed(enum CXCursorKind K) {
3162 switch (K) {
3163 case CXCursor_UnexposedDecl:
3164 case CXCursor_UnexposedExpr:
3165 case CXCursor_UnexposedStmt:
3166 case CXCursor_UnexposedAttr:
3167 return true;
3168 default:
3169 return false;
3170 }
3171}
3172
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003173CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003174 return C.kind;
3175}
3176
Douglas Gregor98258af2010-01-18 22:46:11 +00003177CXSourceLocation clang_getCursorLocation(CXCursor C) {
3178 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003179 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003180 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003181 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3182 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003183 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003184 }
3185
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003186 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003187 std::pair<ObjCProtocolDecl *, SourceLocation> P
3188 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003189 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003190 }
3191
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003192 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003193 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3194 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003195 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003196 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003197
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003198 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003199 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003200 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003201 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003202
3203 case CXCursor_TemplateRef: {
3204 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3205 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3206 }
3207
Douglas Gregor69319002010-08-31 23:48:11 +00003208 case CXCursor_NamespaceRef: {
3209 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3210 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3211 }
3212
Douglas Gregora67e03f2010-09-09 21:42:20 +00003213 case CXCursor_MemberRef: {
3214 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3215 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3216 }
3217
Ted Kremenek3064ef92010-08-27 21:34:58 +00003218 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003219 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3220 if (!BaseSpec)
3221 return clang_getNullLocation();
3222
3223 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3224 return cxloc::translateSourceLocation(getCursorContext(C),
3225 TSInfo->getTypeLoc().getBeginLoc());
3226
3227 return cxloc::translateSourceLocation(getCursorContext(C),
3228 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003229 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003230
Douglas Gregor36897b02010-09-10 00:22:18 +00003231 case CXCursor_LabelRef: {
3232 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3233 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3234 }
3235
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003236 case CXCursor_OverloadedDeclRef:
3237 return cxloc::translateSourceLocation(getCursorContext(C),
3238 getCursorOverloadedDeclRef(C).second);
3239
Douglas Gregorf46034a2010-01-18 23:41:10 +00003240 default:
3241 // FIXME: Need a way to enumerate all non-reference cases.
3242 llvm_unreachable("Missed a reference kind");
3243 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003244 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003245
3246 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003247 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003248 getLocationFromExpr(getCursorExpr(C)));
3249
Douglas Gregor36897b02010-09-10 00:22:18 +00003250 if (clang_isStatement(C.kind))
3251 return cxloc::translateSourceLocation(getCursorContext(C),
3252 getCursorStmt(C)->getLocStart());
3253
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003254 if (C.kind == CXCursor_PreprocessingDirective) {
3255 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3256 return cxloc::translateSourceLocation(getCursorContext(C), L);
3257 }
Douglas Gregor48072312010-03-18 15:23:44 +00003258
3259 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003260 SourceLocation L
3261 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003262 return cxloc::translateSourceLocation(getCursorContext(C), L);
3263 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003264
3265 if (C.kind == CXCursor_MacroDefinition) {
3266 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3267 return cxloc::translateSourceLocation(getCursorContext(C), L);
3268 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003269
3270 if (C.kind == CXCursor_InclusionDirective) {
3271 SourceLocation L
3272 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3273 return cxloc::translateSourceLocation(getCursorContext(C), L);
3274 }
3275
Ted Kremenek9a700d22010-05-12 06:16:13 +00003276 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003277 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003278
Douglas Gregorf46034a2010-01-18 23:41:10 +00003279 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003280 SourceLocation Loc = D->getLocation();
3281 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3282 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003283 // FIXME: Multiple variables declared in a single declaration
3284 // currently lack the information needed to correctly determine their
3285 // ranges when accounting for the type-specifier. We use context
3286 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3287 // and if so, whether it is the first decl.
3288 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3289 if (!cxcursor::isFirstInDeclGroup(C))
3290 Loc = VD->getLocation();
3291 }
3292
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003293 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003294}
Douglas Gregora7bde202010-01-19 00:34:46 +00003295
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003296} // end extern "C"
3297
3298static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003299 if (clang_isReference(C.kind)) {
3300 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003301 case CXCursor_ObjCSuperClassRef:
3302 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003303
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003304 case CXCursor_ObjCProtocolRef:
3305 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003306
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003307 case CXCursor_ObjCClassRef:
3308 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003309
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003310 case CXCursor_TypeRef:
3311 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003312
3313 case CXCursor_TemplateRef:
3314 return getCursorTemplateRef(C).second;
3315
Douglas Gregor69319002010-08-31 23:48:11 +00003316 case CXCursor_NamespaceRef:
3317 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003318
3319 case CXCursor_MemberRef:
3320 return getCursorMemberRef(C).second;
3321
Ted Kremenek3064ef92010-08-27 21:34:58 +00003322 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003323 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003324
Douglas Gregor36897b02010-09-10 00:22:18 +00003325 case CXCursor_LabelRef:
3326 return getCursorLabelRef(C).second;
3327
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003328 case CXCursor_OverloadedDeclRef:
3329 return getCursorOverloadedDeclRef(C).second;
3330
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003331 default:
3332 // FIXME: Need a way to enumerate all non-reference cases.
3333 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003334 }
3335 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003336
3337 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003338 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003339
3340 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003341 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003342
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003343 if (C.kind == CXCursor_PreprocessingDirective)
3344 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003345
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003346 if (C.kind == CXCursor_MacroInstantiation)
3347 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003348
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003349 if (C.kind == CXCursor_MacroDefinition)
3350 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003351
3352 if (C.kind == CXCursor_InclusionDirective)
3353 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3354
Ted Kremenek007a7c92010-11-01 23:26:51 +00003355 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3356 Decl *D = cxcursor::getCursorDecl(C);
3357 SourceRange R = D->getSourceRange();
3358 // FIXME: Multiple variables declared in a single declaration
3359 // currently lack the information needed to correctly determine their
3360 // ranges when accounting for the type-specifier. We use context
3361 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3362 // and if so, whether it is the first decl.
3363 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3364 if (!cxcursor::isFirstInDeclGroup(C))
3365 R.setBegin(VD->getLocation());
3366 }
3367 return R;
3368 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003369 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003370
3371extern "C" {
3372
3373CXSourceRange clang_getCursorExtent(CXCursor C) {
3374 SourceRange R = getRawCursorExtent(C);
3375 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003376 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003377
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003378 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003379}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003380
3381CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003382 if (clang_isInvalid(C.kind))
3383 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003384
Ted Kremeneka60ed472010-11-16 08:15:36 +00003385 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003386 if (clang_isDeclaration(C.kind)) {
3387 Decl *D = getCursorDecl(C);
3388 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003389 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003390 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003391 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003392 if (ObjCForwardProtocolDecl *Protocols
3393 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003394 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003395
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003396 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003397 }
3398
Douglas Gregor97b98722010-01-19 23:20:36 +00003399 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003400 Expr *E = getCursorExpr(C);
3401 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003402 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003403 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003404
3405 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003406 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003407
Douglas Gregor97b98722010-01-19 23:20:36 +00003408 return clang_getNullCursor();
3409 }
3410
Douglas Gregor36897b02010-09-10 00:22:18 +00003411 if (clang_isStatement(C.kind)) {
3412 Stmt *S = getCursorStmt(C);
3413 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003414 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003415
3416 return clang_getNullCursor();
3417 }
3418
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003419 if (C.kind == CXCursor_MacroInstantiation) {
3420 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003421 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003422 }
3423
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003424 if (!clang_isReference(C.kind))
3425 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003426
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003427 switch (C.kind) {
3428 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003429 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003430
3431 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003432 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003433
3434 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003435 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003436
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003437 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003438 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003439
3440 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003441 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003442
Douglas Gregor69319002010-08-31 23:48:11 +00003443 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003444 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003445
Douglas Gregora67e03f2010-09-09 21:42:20 +00003446 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003447 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003448
Ted Kremenek3064ef92010-08-27 21:34:58 +00003449 case CXCursor_CXXBaseSpecifier: {
3450 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3451 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003452 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003453 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003454
Douglas Gregor36897b02010-09-10 00:22:18 +00003455 case CXCursor_LabelRef:
3456 // FIXME: We end up faking the "parent" declaration here because we
3457 // don't want to make CXCursor larger.
3458 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003459 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3460 .getTranslationUnitDecl(),
3461 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003462
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003463 case CXCursor_OverloadedDeclRef:
3464 return C;
3465
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003466 default:
3467 // We would prefer to enumerate all non-reference cursor kinds here.
3468 llvm_unreachable("Unhandled reference cursor kind");
3469 break;
3470 }
3471 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003472
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003473 return clang_getNullCursor();
3474}
3475
Douglas Gregorb6998662010-01-19 19:34:47 +00003476CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003477 if (clang_isInvalid(C.kind))
3478 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003479
Ted Kremeneka60ed472010-11-16 08:15:36 +00003480 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003481
Douglas Gregorb6998662010-01-19 19:34:47 +00003482 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003483 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003484 C = clang_getCursorReferenced(C);
3485 WasReference = true;
3486 }
3487
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003488 if (C.kind == CXCursor_MacroInstantiation)
3489 return clang_getCursorReferenced(C);
3490
Douglas Gregorb6998662010-01-19 19:34:47 +00003491 if (!clang_isDeclaration(C.kind))
3492 return clang_getNullCursor();
3493
3494 Decl *D = getCursorDecl(C);
3495 if (!D)
3496 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003497
Douglas Gregorb6998662010-01-19 19:34:47 +00003498 switch (D->getKind()) {
3499 // Declaration kinds that don't really separate the notions of
3500 // declaration and definition.
3501 case Decl::Namespace:
3502 case Decl::Typedef:
3503 case Decl::TemplateTypeParm:
3504 case Decl::EnumConstant:
3505 case Decl::Field:
3506 case Decl::ObjCIvar:
3507 case Decl::ObjCAtDefsField:
3508 case Decl::ImplicitParam:
3509 case Decl::ParmVar:
3510 case Decl::NonTypeTemplateParm:
3511 case Decl::TemplateTemplateParm:
3512 case Decl::ObjCCategoryImpl:
3513 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003514 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003515 case Decl::LinkageSpec:
3516 case Decl::ObjCPropertyImpl:
3517 case Decl::FileScopeAsm:
3518 case Decl::StaticAssert:
3519 case Decl::Block:
3520 return C;
3521
3522 // Declaration kinds that don't make any sense here, but are
3523 // nonetheless harmless.
3524 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003525 break;
3526
3527 // Declaration kinds for which the definition is not resolvable.
3528 case Decl::UnresolvedUsingTypename:
3529 case Decl::UnresolvedUsingValue:
3530 break;
3531
3532 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003533 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003534 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003535
3536 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003537 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003538
3539 case Decl::Enum:
3540 case Decl::Record:
3541 case Decl::CXXRecord:
3542 case Decl::ClassTemplateSpecialization:
3543 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003544 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003545 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003546 return clang_getNullCursor();
3547
3548 case Decl::Function:
3549 case Decl::CXXMethod:
3550 case Decl::CXXConstructor:
3551 case Decl::CXXDestructor:
3552 case Decl::CXXConversion: {
3553 const FunctionDecl *Def = 0;
3554 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003555 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003556 return clang_getNullCursor();
3557 }
3558
3559 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003560 // Ask the variable if it has a definition.
3561 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003562 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003563 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003564 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003565
Douglas Gregorb6998662010-01-19 19:34:47 +00003566 case Decl::FunctionTemplate: {
3567 const FunctionDecl *Def = 0;
3568 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003569 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003570 return clang_getNullCursor();
3571 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003572
Douglas Gregorb6998662010-01-19 19:34:47 +00003573 case Decl::ClassTemplate: {
3574 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003575 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003576 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003577 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 return clang_getNullCursor();
3579 }
3580
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003581 case Decl::Using:
3582 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003583 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003584
3585 case Decl::UsingShadow:
3586 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003587 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003588 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003589
3590 case Decl::ObjCMethod: {
3591 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3592 if (Method->isThisDeclarationADefinition())
3593 return C;
3594
3595 // Dig out the method definition in the associated
3596 // @implementation, if we have it.
3597 // FIXME: The ASTs should make finding the definition easier.
3598 if (ObjCInterfaceDecl *Class
3599 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3600 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3601 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3602 Method->isInstanceMethod()))
3603 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003604 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003605
3606 return clang_getNullCursor();
3607 }
3608
3609 case Decl::ObjCCategory:
3610 if (ObjCCategoryImplDecl *Impl
3611 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003612 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003613 return clang_getNullCursor();
3614
3615 case Decl::ObjCProtocol:
3616 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3617 return C;
3618 return clang_getNullCursor();
3619
3620 case Decl::ObjCInterface:
3621 // There are two notions of a "definition" for an Objective-C
3622 // class: the interface and its implementation. When we resolved a
3623 // reference to an Objective-C class, produce the @interface as
3624 // the definition; when we were provided with the interface,
3625 // produce the @implementation as the definition.
3626 if (WasReference) {
3627 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3628 return C;
3629 } else if (ObjCImplementationDecl *Impl
3630 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003631 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003632 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003633
Douglas Gregorb6998662010-01-19 19:34:47 +00003634 case Decl::ObjCProperty:
3635 // FIXME: We don't really know where to find the
3636 // ObjCPropertyImplDecls that implement this property.
3637 return clang_getNullCursor();
3638
3639 case Decl::ObjCCompatibleAlias:
3640 if (ObjCInterfaceDecl *Class
3641 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3642 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003643 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003644
Douglas Gregorb6998662010-01-19 19:34:47 +00003645 return clang_getNullCursor();
3646
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003647 case Decl::ObjCForwardProtocol:
3648 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003649 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003650
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003651 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003652 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003653 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003654
3655 case Decl::Friend:
3656 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003657 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003658 return clang_getNullCursor();
3659
3660 case Decl::FriendTemplate:
3661 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003662 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003663 return clang_getNullCursor();
3664 }
3665
3666 return clang_getNullCursor();
3667}
3668
3669unsigned clang_isCursorDefinition(CXCursor C) {
3670 if (!clang_isDeclaration(C.kind))
3671 return 0;
3672
3673 return clang_getCursorDefinition(C) == C;
3674}
3675
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003676unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003677 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003678 return 0;
3679
3680 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3681 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3682 return E->getNumDecls();
3683
3684 if (OverloadedTemplateStorage *S
3685 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3686 return S->size();
3687
3688 Decl *D = Storage.get<Decl*>();
3689 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003690 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003691 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3692 return Classes->size();
3693 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3694 return Protocols->protocol_size();
3695
3696 return 0;
3697}
3698
3699CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003700 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003701 return clang_getNullCursor();
3702
3703 if (index >= clang_getNumOverloadedDecls(cursor))
3704 return clang_getNullCursor();
3705
Ted Kremeneka60ed472010-11-16 08:15:36 +00003706 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003707 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3708 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003709 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003710
3711 if (OverloadedTemplateStorage *S
3712 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003713 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003714
3715 Decl *D = Storage.get<Decl*>();
3716 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3717 // FIXME: This is, unfortunately, linear time.
3718 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3719 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003720 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003721 }
3722
3723 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003724 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003725
3726 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003727 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003728
3729 return clang_getNullCursor();
3730}
3731
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003732void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003733 const char **startBuf,
3734 const char **endBuf,
3735 unsigned *startLine,
3736 unsigned *startColumn,
3737 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003738 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003739 assert(getCursorDecl(C) && "CXCursor has null decl");
3740 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003741 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3742 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003743
Steve Naroff4ade6d62009-09-23 17:52:52 +00003744 SourceManager &SM = FD->getASTContext().getSourceManager();
3745 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3746 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3747 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3748 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3749 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3750 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3751}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003752
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003753void clang_enableStackTraces(void) {
3754 llvm::sys::PrintStackTraceOnErrorSignal();
3755}
3756
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003757void clang_executeOnThread(void (*fn)(void*), void *user_data,
3758 unsigned stack_size) {
3759 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3760}
3761
Ted Kremenekfb480492010-01-13 21:46:36 +00003762} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003763
Ted Kremenekfb480492010-01-13 21:46:36 +00003764//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003765// Token-based Operations.
3766//===----------------------------------------------------------------------===//
3767
3768/* CXToken layout:
3769 * int_data[0]: a CXTokenKind
3770 * int_data[1]: starting token location
3771 * int_data[2]: token length
3772 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003773 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003774 * otherwise unused.
3775 */
3776extern "C" {
3777
3778CXTokenKind clang_getTokenKind(CXToken CXTok) {
3779 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3780}
3781
3782CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3783 switch (clang_getTokenKind(CXTok)) {
3784 case CXToken_Identifier:
3785 case CXToken_Keyword:
3786 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003787 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3788 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003789
3790 case CXToken_Literal: {
3791 // We have stashed the starting pointer in the ptr_data field. Use it.
3792 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003793 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003794 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003795
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003796 case CXToken_Punctuation:
3797 case CXToken_Comment:
3798 break;
3799 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003800
3801 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003803 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003804 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003805 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3808 std::pair<FileID, unsigned> LocInfo
3809 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003810 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003811 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003812 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3813 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003814 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003815
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003816 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003817}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003818
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003819CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003820 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003821 if (!CXXUnit)
3822 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003823
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003824 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3825 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3826}
3827
3828CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003829 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003830 if (!CXXUnit)
3831 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832
3833 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3835}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3838 CXToken **Tokens, unsigned *NumTokens) {
3839 if (Tokens)
3840 *Tokens = 0;
3841 if (NumTokens)
3842 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
Ted Kremeneka60ed472010-11-16 08:15:36 +00003844 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003845 if (!CXXUnit || !Tokens || !NumTokens)
3846 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
Douglas Gregorbdf60622010-03-05 21:16:25 +00003848 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3849
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003850 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003851 if (R.isInvalid())
3852 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003853
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003854 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3855 std::pair<FileID, unsigned> BeginLocInfo
3856 = SourceMgr.getDecomposedLoc(R.getBegin());
3857 std::pair<FileID, unsigned> EndLocInfo
3858 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003860 // Cannot tokenize across files.
3861 if (BeginLocInfo.first != EndLocInfo.first)
3862 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
3864 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003865 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003866 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003867 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003868 if (Invalid)
3869 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003870
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003871 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3872 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003873 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003875
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003876 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003877 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 llvm::SmallVector<CXToken, 32> CXTokens;
3879 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003880 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003881 do {
3882 // Lex the next token
3883 Lex.LexFromRawLexer(Tok);
3884 if (Tok.is(tok::eof))
3885 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003886
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003887 // Initialize the CXToken.
3888 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003889
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 // - Common fields
3891 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3892 CXTok.int_data[2] = Tok.getLength();
3893 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895 // - Kind-specific fields
3896 if (Tok.isLiteral()) {
3897 CXTok.int_data[0] = CXToken_Literal;
3898 CXTok.ptr_data = (void *)Tok.getLiteralData();
3899 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003900 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003901 std::pair<FileID, unsigned> LocInfo
3902 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003903 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003904 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003905 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3906 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003907 return;
3908
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003909 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003910 IdentifierInfo *II
3911 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003912
David Chisnall096428b2010-10-13 21:44:48 +00003913 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003914 CXTok.int_data[0] = CXToken_Keyword;
3915 }
3916 else {
3917 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3918 CXToken_Identifier
3919 : CXToken_Keyword;
3920 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003921 CXTok.ptr_data = II;
3922 } else if (Tok.is(tok::comment)) {
3923 CXTok.int_data[0] = CXToken_Comment;
3924 CXTok.ptr_data = 0;
3925 } else {
3926 CXTok.int_data[0] = CXToken_Punctuation;
3927 CXTok.ptr_data = 0;
3928 }
3929 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003930 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003931 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003932
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003933 if (CXTokens.empty())
3934 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003935
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003936 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3937 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3938 *NumTokens = CXTokens.size();
3939}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003940
Ted Kremenek6db61092010-05-05 00:55:15 +00003941void clang_disposeTokens(CXTranslationUnit TU,
3942 CXToken *Tokens, unsigned NumTokens) {
3943 free(Tokens);
3944}
3945
3946} // end: extern "C"
3947
3948//===----------------------------------------------------------------------===//
3949// Token annotation APIs.
3950//===----------------------------------------------------------------------===//
3951
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003952typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003953static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3954 CXCursor parent,
3955 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003956namespace {
3957class AnnotateTokensWorker {
3958 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003959 CXToken *Tokens;
3960 CXCursor *Cursors;
3961 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003962 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003963 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003964 CursorVisitor AnnotateVis;
3965 SourceManager &SrcMgr;
3966
3967 bool MoreTokens() const { return TokIdx < NumTokens; }
3968 unsigned NextToken() const { return TokIdx; }
3969 void AdvanceToken() { ++TokIdx; }
3970 SourceLocation GetTokenLoc(unsigned tokI) {
3971 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3972 }
3973
Ted Kremenek6db61092010-05-05 00:55:15 +00003974public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003975 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003976 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003977 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003978 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003979 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003980 AnnotateVis(tu,
3981 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003982 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003983 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003984
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003985 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003986 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003987 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003988 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003989 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00003990 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003991};
3992}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003993
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003994void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3995 // Walk the AST within the region of interest, annotating tokens
3996 // along the way.
3997 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003998
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003999 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4000 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004001 if (Pos != Annotated.end() &&
4002 (clang_isInvalid(Cursors[I].kind) ||
4003 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004 Cursors[I] = Pos->second;
4005 }
4006
4007 // Finish up annotating any tokens left.
4008 if (!MoreTokens())
4009 return;
4010
4011 const CXCursor &C = clang_getNullCursor();
4012 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4013 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4014 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004015 }
4016}
4017
Ted Kremenek6db61092010-05-05 00:55:15 +00004018enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004019AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004020 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004021 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004022 if (cursorRange.isInvalid())
4023 return CXChildVisit_Recurse;
4024
Douglas Gregor4419b672010-10-21 06:10:04 +00004025 if (clang_isPreprocessing(cursor.kind)) {
4026 // For macro instantiations, just note where the beginning of the macro
4027 // instantiation occurs.
4028 if (cursor.kind == CXCursor_MacroInstantiation) {
4029 Annotated[Loc.int_data] = cursor;
4030 return CXChildVisit_Recurse;
4031 }
4032
Douglas Gregor4419b672010-10-21 06:10:04 +00004033 // Items in the preprocessing record are kept separate from items in
4034 // declarations, so we keep a separate token index.
4035 unsigned SavedTokIdx = TokIdx;
4036 TokIdx = PreprocessingTokIdx;
4037
4038 // Skip tokens up until we catch up to the beginning of the preprocessing
4039 // entry.
4040 while (MoreTokens()) {
4041 const unsigned I = NextToken();
4042 SourceLocation TokLoc = GetTokenLoc(I);
4043 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4044 case RangeBefore:
4045 AdvanceToken();
4046 continue;
4047 case RangeAfter:
4048 case RangeOverlap:
4049 break;
4050 }
4051 break;
4052 }
4053
4054 // Look at all of the tokens within this range.
4055 while (MoreTokens()) {
4056 const unsigned I = NextToken();
4057 SourceLocation TokLoc = GetTokenLoc(I);
4058 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4059 case RangeBefore:
4060 assert(0 && "Infeasible");
4061 case RangeAfter:
4062 break;
4063 case RangeOverlap:
4064 Cursors[I] = cursor;
4065 AdvanceToken();
4066 continue;
4067 }
4068 break;
4069 }
4070
4071 // Save the preprocessing token index; restore the non-preprocessing
4072 // token index.
4073 PreprocessingTokIdx = TokIdx;
4074 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004075 return CXChildVisit_Recurse;
4076 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004077
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004078 if (cursorRange.isInvalid())
4079 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004080
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004081 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4082
Ted Kremeneka333c662010-05-12 05:29:33 +00004083 // Adjust the annotated range based specific declarations.
4084 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4085 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004086 Decl *D = cxcursor::getCursorDecl(cursor);
4087 // Don't visit synthesized ObjC methods, since they have no syntatic
4088 // representation in the source.
4089 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4090 if (MD->isSynthesized())
4091 return CXChildVisit_Continue;
4092 }
4093 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004094 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4095 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004096 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004097 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004098 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004099 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004100 }
4101 }
4102 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004103
Ted Kremenek3f404602010-08-14 01:14:06 +00004104 // If the location of the cursor occurs within a macro instantiation, record
4105 // the spelling location of the cursor in our annotation map. We can then
4106 // paper over the token labelings during a post-processing step to try and
4107 // get cursor mappings for tokens that are the *arguments* of a macro
4108 // instantiation.
4109 if (L.isMacroID()) {
4110 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4111 // Only invalidate the old annotation if it isn't part of a preprocessing
4112 // directive. Here we assume that the default construction of CXCursor
4113 // results in CXCursor.kind being an initialized value (i.e., 0). If
4114 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004115
Ted Kremenek3f404602010-08-14 01:14:06 +00004116 CXCursor &oldC = Annotated[rawEncoding];
4117 if (!clang_isPreprocessing(oldC.kind))
4118 oldC = cursor;
4119 }
4120
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004121 const enum CXCursorKind K = clang_getCursorKind(parent);
4122 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004123 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4124 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004125
4126 while (MoreTokens()) {
4127 const unsigned I = NextToken();
4128 SourceLocation TokLoc = GetTokenLoc(I);
4129 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4130 case RangeBefore:
4131 Cursors[I] = updateC;
4132 AdvanceToken();
4133 continue;
4134 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004135 case RangeOverlap:
4136 break;
4137 }
4138 break;
4139 }
4140
4141 // Visit children to get their cursor information.
4142 const unsigned BeforeChildren = NextToken();
4143 VisitChildren(cursor);
4144 const unsigned AfterChildren = NextToken();
4145
4146 // Adjust 'Last' to the last token within the extent of the cursor.
4147 while (MoreTokens()) {
4148 const unsigned I = NextToken();
4149 SourceLocation TokLoc = GetTokenLoc(I);
4150 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4151 case RangeBefore:
4152 assert(0 && "Infeasible");
4153 case RangeAfter:
4154 break;
4155 case RangeOverlap:
4156 Cursors[I] = updateC;
4157 AdvanceToken();
4158 continue;
4159 }
4160 break;
4161 }
4162 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004163
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004164 // Scan the tokens that are at the beginning of the cursor, but are not
4165 // capture by the child cursors.
4166
4167 // For AST elements within macros, rely on a post-annotate pass to
4168 // to correctly annotate the tokens with cursors. Otherwise we can
4169 // get confusing results of having tokens that map to cursors that really
4170 // are expanded by an instantiation.
4171 if (L.isMacroID())
4172 cursor = clang_getNullCursor();
4173
4174 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4175 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4176 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004177
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004178 Cursors[I] = cursor;
4179 }
4180 // Scan the tokens that are at the end of the cursor, but are not captured
4181 // but the child cursors.
4182 for (unsigned I = AfterChildren; I != Last; ++I)
4183 Cursors[I] = cursor;
4184
4185 TokIdx = Last;
4186 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004187}
4188
Ted Kremenek6db61092010-05-05 00:55:15 +00004189static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4190 CXCursor parent,
4191 CXClientData client_data) {
4192 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4193}
4194
Ted Kremenekab979612010-11-11 08:05:23 +00004195// This gets run a separate thread to avoid stack blowout.
4196static void runAnnotateTokensWorker(void *UserData) {
4197 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4198}
4199
Ted Kremenek6db61092010-05-05 00:55:15 +00004200extern "C" {
4201
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004202void clang_annotateTokens(CXTranslationUnit TU,
4203 CXToken *Tokens, unsigned NumTokens,
4204 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004205
4206 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004207 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004208
Douglas Gregor4419b672010-10-21 06:10:04 +00004209 // Any token we don't specifically annotate will have a NULL cursor.
4210 CXCursor C = clang_getNullCursor();
4211 for (unsigned I = 0; I != NumTokens; ++I)
4212 Cursors[I] = C;
4213
Ted Kremeneka60ed472010-11-16 08:15:36 +00004214 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004215 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004216 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004217
Douglas Gregorbdf60622010-03-05 21:16:25 +00004218 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004219
Douglas Gregor0396f462010-03-19 05:22:59 +00004220 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004221 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004222 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4223 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004224 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4225 clang_getTokenLocation(TU,
4226 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227
Douglas Gregor0396f462010-03-19 05:22:59 +00004228 // A mapping from the source locations found when re-lexing or traversing the
4229 // region of interest to the corresponding cursors.
4230 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004231
4232 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004233 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004234 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4235 std::pair<FileID, unsigned> BeginLocInfo
4236 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4237 std::pair<FileID, unsigned> EndLocInfo
4238 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004240 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004241 bool Invalid = false;
4242 if (BeginLocInfo.first == EndLocInfo.first &&
4243 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4244 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4246 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004247 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004248 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004249 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004250
4251 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004252 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004253 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004254 Token Tok;
4255 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004256
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004257 reprocess:
4258 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4259 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004260 // don't see it while preprocessing these tokens later, but keep track
4261 // of all of the token locations inside this preprocessing directive so
4262 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004263 //
4264 // FIXME: Some simple tests here could identify macro definitions and
4265 // #undefs, to provide specific cursor kinds for those.
4266 std::vector<SourceLocation> Locations;
4267 do {
4268 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004269 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004270 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004271
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004272 using namespace cxcursor;
4273 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004274 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4275 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004276 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004277 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4278 Annotated[Locations[I].getRawEncoding()] = Cursor;
4279 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004280
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004281 if (Tok.isAtStartOfLine())
4282 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004283
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004284 continue;
4285 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004286
Douglas Gregor48072312010-03-18 15:23:44 +00004287 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004288 break;
4289 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004290 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004291
Douglas Gregor0396f462010-03-19 05:22:59 +00004292 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004293 // a specific cursor.
4294 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004295 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004296
4297 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004298 // FIXME: We use a ridiculous stack size here because the data-recursion
4299 // algorithm uses a large stack frame than the non-data recursive version,
4300 // and AnnotationTokensWorker currently transforms the data-recursion
4301 // algorithm back into a traditional recursion by explicitly calling
4302 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004303 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004304 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4305 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004306 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4307 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004308}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004309} // end: extern "C"
4310
4311//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004312// Operations for querying linkage of a cursor.
4313//===----------------------------------------------------------------------===//
4314
4315extern "C" {
4316CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004317 if (!clang_isDeclaration(cursor.kind))
4318 return CXLinkage_Invalid;
4319
Ted Kremenek16b42592010-03-03 06:36:57 +00004320 Decl *D = cxcursor::getCursorDecl(cursor);
4321 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4322 switch (ND->getLinkage()) {
4323 case NoLinkage: return CXLinkage_NoLinkage;
4324 case InternalLinkage: return CXLinkage_Internal;
4325 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4326 case ExternalLinkage: return CXLinkage_External;
4327 };
4328
4329 return CXLinkage_Invalid;
4330}
4331} // end: extern "C"
4332
4333//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004334// Operations for querying language of a cursor.
4335//===----------------------------------------------------------------------===//
4336
4337static CXLanguageKind getDeclLanguage(const Decl *D) {
4338 switch (D->getKind()) {
4339 default:
4340 break;
4341 case Decl::ImplicitParam:
4342 case Decl::ObjCAtDefsField:
4343 case Decl::ObjCCategory:
4344 case Decl::ObjCCategoryImpl:
4345 case Decl::ObjCClass:
4346 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004347 case Decl::ObjCForwardProtocol:
4348 case Decl::ObjCImplementation:
4349 case Decl::ObjCInterface:
4350 case Decl::ObjCIvar:
4351 case Decl::ObjCMethod:
4352 case Decl::ObjCProperty:
4353 case Decl::ObjCPropertyImpl:
4354 case Decl::ObjCProtocol:
4355 return CXLanguage_ObjC;
4356 case Decl::CXXConstructor:
4357 case Decl::CXXConversion:
4358 case Decl::CXXDestructor:
4359 case Decl::CXXMethod:
4360 case Decl::CXXRecord:
4361 case Decl::ClassTemplate:
4362 case Decl::ClassTemplatePartialSpecialization:
4363 case Decl::ClassTemplateSpecialization:
4364 case Decl::Friend:
4365 case Decl::FriendTemplate:
4366 case Decl::FunctionTemplate:
4367 case Decl::LinkageSpec:
4368 case Decl::Namespace:
4369 case Decl::NamespaceAlias:
4370 case Decl::NonTypeTemplateParm:
4371 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004372 case Decl::TemplateTemplateParm:
4373 case Decl::TemplateTypeParm:
4374 case Decl::UnresolvedUsingTypename:
4375 case Decl::UnresolvedUsingValue:
4376 case Decl::Using:
4377 case Decl::UsingDirective:
4378 case Decl::UsingShadow:
4379 return CXLanguage_CPlusPlus;
4380 }
4381
4382 return CXLanguage_C;
4383}
4384
4385extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004386
4387enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4388 if (clang_isDeclaration(cursor.kind))
4389 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4390 if (D->hasAttr<UnavailableAttr>() ||
4391 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4392 return CXAvailability_Available;
4393
4394 if (D->hasAttr<DeprecatedAttr>())
4395 return CXAvailability_Deprecated;
4396 }
4397
4398 return CXAvailability_Available;
4399}
4400
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004401CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4402 if (clang_isDeclaration(cursor.kind))
4403 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4404
4405 return CXLanguage_Invalid;
4406}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004407
4408CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4409 if (clang_isDeclaration(cursor.kind)) {
4410 if (Decl *D = getCursorDecl(cursor)) {
4411 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004412 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004413 }
4414 }
4415
4416 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4417 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004418 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004419 }
4420
4421 return clang_getNullCursor();
4422}
4423
4424CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4425 if (clang_isDeclaration(cursor.kind)) {
4426 if (Decl *D = getCursorDecl(cursor)) {
4427 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004428 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004429 }
4430 }
4431
4432 // FIXME: Note that we can't easily compute the lexical context of a
4433 // statement or expression, so we return nothing.
4434 return clang_getNullCursor();
4435}
4436
Douglas Gregor9f592342010-10-01 20:25:15 +00004437static void CollectOverriddenMethods(DeclContext *Ctx,
4438 ObjCMethodDecl *Method,
4439 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4440 if (!Ctx)
4441 return;
4442
4443 // If we have a class or category implementation, jump straight to the
4444 // interface.
4445 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4446 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4447
4448 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4449 if (!Container)
4450 return;
4451
4452 // Check whether we have a matching method at this level.
4453 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4454 Method->isInstanceMethod()))
4455 if (Method != Overridden) {
4456 // We found an override at this level; there is no need to look
4457 // into other protocols or categories.
4458 Methods.push_back(Overridden);
4459 return;
4460 }
4461
4462 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4463 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4464 PEnd = Protocol->protocol_end();
4465 P != PEnd; ++P)
4466 CollectOverriddenMethods(*P, Method, Methods);
4467 }
4468
4469 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4470 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4471 PEnd = Category->protocol_end();
4472 P != PEnd; ++P)
4473 CollectOverriddenMethods(*P, Method, Methods);
4474 }
4475
4476 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4477 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4478 PEnd = Interface->protocol_end();
4479 P != PEnd; ++P)
4480 CollectOverriddenMethods(*P, Method, Methods);
4481
4482 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4483 Category; Category = Category->getNextClassCategory())
4484 CollectOverriddenMethods(Category, Method, Methods);
4485
4486 // We only look into the superclass if we haven't found anything yet.
4487 if (Methods.empty())
4488 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4489 return CollectOverriddenMethods(Super, Method, Methods);
4490 }
4491}
4492
4493void clang_getOverriddenCursors(CXCursor cursor,
4494 CXCursor **overridden,
4495 unsigned *num_overridden) {
4496 if (overridden)
4497 *overridden = 0;
4498 if (num_overridden)
4499 *num_overridden = 0;
4500 if (!overridden || !num_overridden)
4501 return;
4502
4503 if (!clang_isDeclaration(cursor.kind))
4504 return;
4505
4506 Decl *D = getCursorDecl(cursor);
4507 if (!D)
4508 return;
4509
4510 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004511 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004512 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4513 *num_overridden = CXXMethod->size_overridden_methods();
4514 if (!*num_overridden)
4515 return;
4516
4517 *overridden = new CXCursor [*num_overridden];
4518 unsigned I = 0;
4519 for (CXXMethodDecl::method_iterator
4520 M = CXXMethod->begin_overridden_methods(),
4521 MEnd = CXXMethod->end_overridden_methods();
4522 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004523 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004524 return;
4525 }
4526
4527 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4528 if (!Method)
4529 return;
4530
4531 // Handle Objective-C methods.
4532 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4533 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4534
4535 if (Methods.empty())
4536 return;
4537
4538 *num_overridden = Methods.size();
4539 *overridden = new CXCursor [Methods.size()];
4540 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004541 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004542}
4543
4544void clang_disposeOverriddenCursors(CXCursor *overridden) {
4545 delete [] overridden;
4546}
4547
Douglas Gregorecdcb882010-10-20 22:00:55 +00004548CXFile clang_getIncludedFile(CXCursor cursor) {
4549 if (cursor.kind != CXCursor_InclusionDirective)
4550 return 0;
4551
4552 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4553 return (void *)ID->getFile();
4554}
4555
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004556} // end: extern "C"
4557
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004558
4559//===----------------------------------------------------------------------===//
4560// C++ AST instrospection.
4561//===----------------------------------------------------------------------===//
4562
4563extern "C" {
4564unsigned clang_CXXMethod_isStatic(CXCursor C) {
4565 if (!clang_isDeclaration(C.kind))
4566 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004567
4568 CXXMethodDecl *Method = 0;
4569 Decl *D = cxcursor::getCursorDecl(C);
4570 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4571 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4572 else
4573 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4574 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004575}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004576
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004577} // end: extern "C"
4578
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004579//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004580// Attribute introspection.
4581//===----------------------------------------------------------------------===//
4582
4583extern "C" {
4584CXType clang_getIBOutletCollectionType(CXCursor C) {
4585 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004586 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004587
4588 IBOutletCollectionAttr *A =
4589 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4590
Ted Kremeneka60ed472010-11-16 08:15:36 +00004591 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004592}
4593} // end: extern "C"
4594
4595//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004596// Misc. utility functions.
4597//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004598
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004599/// Default to using an 8 MB stack size on "safety" threads.
4600static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004601
4602namespace clang {
4603
4604bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004605 void (*Fn)(void*), void *UserData,
4606 unsigned Size) {
4607 if (!Size)
4608 Size = GetSafetyThreadStackSize();
4609 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004610 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4611 return CRC.RunSafely(Fn, UserData);
4612}
4613
4614unsigned GetSafetyThreadStackSize() {
4615 return SafetyStackThreadSize;
4616}
4617
4618void SetSafetyThreadStackSize(unsigned Value) {
4619 SafetyStackThreadSize = Value;
4620}
4621
4622}
4623
Ted Kremenek04bb7162010-01-22 22:44:15 +00004624extern "C" {
4625
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004626CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004627 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004628}
4629
4630} // end: extern "C"