blob: 6b094122f281e6efde47f907be7c989eea1927e2 [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 Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
37#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000038#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000039#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000040#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000042#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000043#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000044#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000045#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000046#include "llvm/System/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000047#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000048
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Ted Kremeneka60ed472010-11-16 08:15:36 +000053static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
54 if (!TU)
55 return 0;
56 CXTranslationUnit D = new CXTranslationUnitImpl();
57 D->TUData = TU;
58 D->StringPool = createCXStringPool();
59 return D;
60}
61
Douglas Gregor33e9abd2010-01-22 19:49:59 +000062/// \brief The result of comparing two source ranges.
63enum RangeComparisonResult {
64 /// \brief Either the ranges overlap or one of the ranges is invalid.
65 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000066
Douglas Gregor33e9abd2010-01-22 19:49:59 +000067 /// \brief The first range ends before the second range starts.
68 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000069
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070 /// \brief The first range starts after the second range ends.
71 RangeAfter
72};
73
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076static RangeComparisonResult RangeCompare(SourceManager &SM,
77 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 SourceRange R2) {
79 assert(R1.isValid() && "First range is invalid?");
80 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000081 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000082 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000085 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 return RangeAfter;
87 return RangeOverlap;
88}
89
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000090/// \brief Determine if a source location falls within, before, or after a
91/// a given source range.
92static RangeComparisonResult LocationCompare(SourceManager &SM,
93 SourceLocation L, SourceRange R) {
94 assert(R.isValid() && "First range is invalid?");
95 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000096 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
99 return RangeBefore;
100 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
101 return RangeAfter;
102 return RangeOverlap;
103}
104
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105/// \brief Translate a Clang source range into a CIndex source range.
106///
107/// Clang internally represents ranges where the end location points to the
108/// start of the token at the end. However, for external clients it is more
109/// useful to have a CXSourceRange be a proper half-open interval. This routine
110/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000111CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000113 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000115 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000117 if (EndLoc.isValid() && EndLoc.isMacroID())
118 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000119 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000120 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000121 EndLoc = EndLoc.getFileLocWithOffset(Length);
122 }
123
124 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
125 R.getBegin().getRawEncoding(),
126 EndLoc.getRawEncoding() };
127 return Result;
128}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000129
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
133
Steve Naroff89922f82009-08-31 00:59:03 +0000134namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135
136class VisitorJob {
137public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000138 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000139 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000140 DeclRefExprPartsKind, LabelRefVisitKind,
141 ExplicitTemplateArgsVisitKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000142protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000143 void *dataA;
144 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000145 CXCursor parent;
146 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000147 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
148 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000149public:
150 Kind getKind() const { return K; }
151 const CXCursor &getParent() const { return parent; }
152 static bool classof(VisitorJob *VJ) { return true; }
153};
154
155typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
156
Douglas Gregorb1373d02010-01-20 20:59:29 +0000157// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000158class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000159 public TypeLocVisitor<CursorVisitor, bool>,
160 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000161{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000162 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000163 CXTranslationUnit TU;
164 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000165
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000166 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000167 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000168
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000169 /// \brief The declaration that serves at the parent of any statement or
170 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000171 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000177 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000179 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
180 // to the visitor. Declarations with a PCH level greater than this value will
181 // be suppressed.
182 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000183
184 /// \brief When valid, a source range to which the cursor should restrict
185 /// its search.
186 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000187
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000188 // FIXME: Eventually remove. This part of a hack to support proper
189 // iteration over all Decls contained lexically within an ObjC container.
190 DeclContext::decl_iterator *DI_current;
191 DeclContext::decl_iterator DE_current;
192
Ted Kremenekd1ded662010-11-15 23:31:32 +0000193 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
194 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
195 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
196
Douglas Gregorb1373d02010-01-20 20:59:29 +0000197 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000198 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000199 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000200
201 /// \brief Determine whether this particular source range comes before, comes
202 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000203 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000204 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
206
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000207 class SetParentRAII {
208 CXCursor &Parent;
209 Decl *&StmtParent;
210 CXCursor OldParent;
211
212 public:
213 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
214 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
215 {
216 Parent = NewParent;
217 if (clang_isDeclaration(Parent.kind))
218 StmtParent = getCursorDecl(Parent);
219 }
220
221 ~SetParentRAII() {
222 Parent = OldParent;
223 if (clang_isDeclaration(Parent.kind))
224 StmtParent = getCursorDecl(Parent);
225 }
226 };
227
Steve Naroff89922f82009-08-31 00:59:03 +0000228public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000229 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
230 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000231 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000232 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000233 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
234 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000235 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
236 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000237 {
238 Parent.kind = CXCursor_NoDeclFound;
239 Parent.data[0] = 0;
240 Parent.data[1] = 0;
241 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000242 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000243 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000244
Ted Kremenekd1ded662010-11-15 23:31:32 +0000245 ~CursorVisitor() {
246 // Free the pre-allocated worklists for data-recursion.
247 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
248 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
249 delete *I;
250 }
251 }
252
Ted Kremeneka60ed472010-11-16 08:15:36 +0000253 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
254 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000255
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000256 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000257
258 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
259 getPreprocessedEntities();
260
Douglas Gregorb1373d02010-01-20 20:59:29 +0000261 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000262
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000263 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000264 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000265 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000266 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000267 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000268 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000269 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
270 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000271 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000272 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000273 bool VisitClassTemplatePartialSpecializationDecl(
274 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000275 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000276 bool VisitEnumConstantDecl(EnumConstantDecl *D);
277 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
278 bool VisitFunctionDecl(FunctionDecl *ND);
279 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000280 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000281 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000282 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000283 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000284 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000285 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
286 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
287 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
288 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000289 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
291 bool VisitObjCImplDecl(ObjCImplDecl *D);
292 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
293 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
295 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
296 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000297 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000298 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000299 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000300 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000301 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000302 bool VisitUsingDecl(UsingDecl *D);
303 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
304 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000305
Douglas Gregor01829d32010-08-31 14:41:23 +0000306 // Name visitor
307 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000308 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000309
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000310 // Template visitors
311 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000312 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000313 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
314
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000315 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000316 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000317 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000318 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000319 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
320 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000321 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000323 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000324 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
325 bool VisitPointerTypeLoc(PointerTypeLoc TL);
326 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
327 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
328 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
329 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000330 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000332 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000333 // FIXME: Implement visitors here when the unimplemented TypeLocs get
334 // implemented
335 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
336 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000337
Douglas Gregora59e3902010-01-21 23:27:09 +0000338 // Statement visitors
339 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000340
Douglas Gregor336fd812010-01-23 00:40:08 +0000341 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000342 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000343 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000344 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000345 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000346 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000347
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000348 // Data-recursive visitor functions.
349 bool IsInRegionOfInterest(CXCursor C);
350 bool RunVisitorWorkList(VisitorWorkList &WL);
351 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Benjamin Kramere645c722010-11-16 15:45:46 +0000352 LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000353};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000354
Ted Kremenekab188932010-01-05 19:32:54 +0000355} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000357static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000358static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
359
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000360
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000362 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000363}
364
Douglas Gregorb1373d02010-01-20 20:59:29 +0000365/// \brief Visit the given cursor and, if requested by the visitor,
366/// its children.
367///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368/// \param Cursor the cursor to visit.
369///
370/// \param CheckRegionOfInterest if true, then the caller already checked that
371/// this cursor is within the region of interest.
372///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373/// \returns true if the visitation should be aborted, false if it
374/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000375bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 if (clang_isInvalid(Cursor.kind))
377 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000378
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379 if (clang_isDeclaration(Cursor.kind)) {
380 Decl *D = getCursorDecl(Cursor);
381 assert(D && "Invalid declaration cursor");
382 if (D->getPCHLevel() > MaxPCHLevel)
383 return false;
384
385 if (D->isImplicit())
386 return false;
387 }
388
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000389 // If we have a range of interest, and this cursor doesn't intersect with it,
390 // we're done.
391 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000392 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000393 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000394 return false;
395 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000396
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397 switch (Visitor(Cursor, Parent, ClientData)) {
398 case CXChildVisit_Break:
399 return true;
400
401 case CXChildVisit_Continue:
402 return false;
403
404 case CXChildVisit_Recurse:
405 return VisitChildren(Cursor);
406 }
407
Douglas Gregorfd643772010-01-25 16:45:46 +0000408 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000409}
410
Douglas Gregor788f5a12010-03-20 00:41:21 +0000411std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
412CursorVisitor::getPreprocessedEntities() {
413 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000414 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000415
416 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000417 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000418
419 // There is no region of interest; we have to walk everything.
420 if (RegionOfInterest.isInvalid())
421 return std::make_pair(PPRec.begin(OnlyLocalDecls),
422 PPRec.end(OnlyLocalDecls));
423
424 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000425 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000426 std::pair<FileID, unsigned> Begin
427 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
428 std::pair<FileID, unsigned> End
429 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
430
431 // The region of interest spans files; we have to walk everything.
432 if (Begin.first != End.first)
433 return std::make_pair(PPRec.begin(OnlyLocalDecls),
434 PPRec.end(OnlyLocalDecls));
435
436 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000437 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000438 if (ByFileMap.empty()) {
439 // Build the mapping from files to sets of preprocessed entities.
440 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
441 EEnd = PPRec.end(OnlyLocalDecls);
442 E != EEnd; ++E) {
443 std::pair<FileID, unsigned> P
444 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
445 ByFileMap[P.first].push_back(*E);
446 }
447 }
448
449 return std::make_pair(ByFileMap[Begin.first].begin(),
450 ByFileMap[Begin.first].end());
451}
452
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000454///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455/// \returns true if the visitation should be aborted, false if it
456/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000458 if (clang_isReference(Cursor.kind)) {
459 // By definition, references have no children.
460 return false;
461 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000462
463 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000464 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000465 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467 if (clang_isDeclaration(Cursor.kind)) {
468 Decl *D = getCursorDecl(Cursor);
469 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000470 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472
Douglas Gregora59e3902010-01-21 23:27:09 +0000473 if (clang_isStatement(Cursor.kind))
474 return Visit(getCursorStmt(Cursor));
475 if (clang_isExpression(Cursor.kind))
476 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000477
Douglas Gregorb1373d02010-01-20 20:59:29 +0000478 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000479 CXTranslationUnit tu = getCursorTU(Cursor);
480 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000481 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
482 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000483 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
484 TLEnd = CXXUnit->top_level_end();
485 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000486 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000487 return true;
488 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000489 } else if (VisitDeclContext(
490 CXXUnit->getASTContext().getTranslationUnitDecl()))
491 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000492
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000494 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 // FIXME: Once we have the ability to deserialize a preprocessing record,
496 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000497 PreprocessingRecord::iterator E, EEnd;
498 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000499 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000500 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000502
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 continue;
504 }
505
506 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000507 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 return true;
509
510 continue;
511 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000512
513 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000514 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000515 return true;
516
517 continue;
518 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000519 }
520 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000521 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000523
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 return false;
526}
527
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000529 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
530 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000531
Ted Kremenek664cffd2010-07-22 11:30:19 +0000532 if (Stmt *Body = B->getBody())
533 return Visit(MakeCXCursor(Body, StmtParent, TU));
534
535 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000536}
537
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000538llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
539 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000540 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000541 if (Range.isInvalid())
542 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000543
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000544 switch (CompareRegionOfInterest(Range)) {
545 case RangeBefore:
546 // This declaration comes before the region of interest; skip it.
547 return llvm::Optional<bool>();
548
549 case RangeAfter:
550 // This declaration comes after the region of interest; we're done.
551 return false;
552
553 case RangeOverlap:
554 // This declaration overlaps the region of interest; visit it.
555 break;
556 }
557 }
558 return true;
559}
560
561bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
562 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
563
564 // FIXME: Eventually remove. This part of a hack to support proper
565 // iteration over all Decls contained lexically within an ObjC container.
566 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
567 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
568
569 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000570 Decl *D = *I;
571 if (D->getLexicalDeclContext() != DC)
572 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000573 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000574 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
575 if (!V.hasValue())
576 continue;
577 if (!V.getValue())
578 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000579 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000580 return true;
581 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000583}
584
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000585bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
586 llvm_unreachable("Translation units are visited directly by Visit()");
587 return false;
588}
589
590bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
591 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
592 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000594 return false;
595}
596
597bool CursorVisitor::VisitTagDecl(TagDecl *D) {
598 return VisitDeclContext(D);
599}
600
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000601bool CursorVisitor::VisitClassTemplateSpecializationDecl(
602 ClassTemplateSpecializationDecl *D) {
603 bool ShouldVisitBody = false;
604 switch (D->getSpecializationKind()) {
605 case TSK_Undeclared:
606 case TSK_ImplicitInstantiation:
607 // Nothing to visit
608 return false;
609
610 case TSK_ExplicitInstantiationDeclaration:
611 case TSK_ExplicitInstantiationDefinition:
612 break;
613
614 case TSK_ExplicitSpecialization:
615 ShouldVisitBody = true;
616 break;
617 }
618
619 // Visit the template arguments used in the specialization.
620 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
621 TypeLoc TL = SpecType->getTypeLoc();
622 if (TemplateSpecializationTypeLoc *TSTLoc
623 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
624 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
625 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
626 return true;
627 }
628 }
629
630 if (ShouldVisitBody && VisitCXXRecordDecl(D))
631 return true;
632
633 return false;
634}
635
Douglas Gregor74dbe642010-08-31 19:31:58 +0000636bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
637 ClassTemplatePartialSpecializationDecl *D) {
638 // FIXME: Visit the "outer" template parameter lists on the TagDecl
639 // before visiting these template parameters.
640 if (VisitTemplateParameters(D->getTemplateParameters()))
641 return true;
642
643 // Visit the partial specialization arguments.
644 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
645 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
646 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
647 return true;
648
649 return VisitCXXRecordDecl(D);
650}
651
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000652bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000653 // Visit the default argument.
654 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
655 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
656 if (Visit(DefArg->getTypeLoc()))
657 return true;
658
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000659 return false;
660}
661
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000662bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
663 if (Expr *Init = D->getInitExpr())
664 return Visit(MakeCXCursor(Init, StmtParent, TU));
665 return false;
666}
667
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000668bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
669 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
670 if (Visit(TSInfo->getTypeLoc()))
671 return true;
672
673 return false;
674}
675
Douglas Gregora67e03f2010-09-09 21:42:20 +0000676/// \brief Compare two base or member initializers based on their source order.
677static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
678 CXXBaseOrMemberInitializer const * const *X
679 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
680 CXXBaseOrMemberInitializer const * const *Y
681 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
682
683 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
684 return -1;
685 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
686 return 1;
687 else
688 return 0;
689}
690
Douglas Gregorb1373d02010-01-20 20:59:29 +0000691bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000692 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
693 // Visit the function declaration's syntactic components in the order
694 // written. This requires a bit of work.
695 TypeLoc TL = TSInfo->getTypeLoc();
696 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
697
698 // If we have a function declared directly (without the use of a typedef),
699 // visit just the return type. Otherwise, just visit the function's type
700 // now.
701 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
702 (!FTL && Visit(TL)))
703 return true;
704
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000705 // Visit the nested-name-specifier, if present.
706 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
707 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
708 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000709
710 // Visit the declaration name.
711 if (VisitDeclarationNameInfo(ND->getNameInfo()))
712 return true;
713
714 // FIXME: Visit explicitly-specified template arguments!
715
716 // Visit the function parameters, if we have a function type.
717 if (FTL && VisitFunctionTypeLoc(*FTL, true))
718 return true;
719
720 // FIXME: Attributes?
721 }
722
Douglas Gregora67e03f2010-09-09 21:42:20 +0000723 if (ND->isThisDeclarationADefinition()) {
724 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
725 // Find the initializers that were written in the source.
726 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
727 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
728 IEnd = Constructor->init_end();
729 I != IEnd; ++I) {
730 if (!(*I)->isWritten())
731 continue;
732
733 WrittenInits.push_back(*I);
734 }
735
736 // Sort the initializers in source order
737 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
738 &CompareCXXBaseOrMemberInitializers);
739
740 // Visit the initializers in source order
741 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
742 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
743 if (Init->isMemberInitializer()) {
744 if (Visit(MakeCursorMemberRef(Init->getMember(),
745 Init->getMemberLocation(), TU)))
746 return true;
747 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
748 if (Visit(BaseInfo->getTypeLoc()))
749 return true;
750 }
751
752 // Visit the initializer value.
753 if (Expr *Initializer = Init->getInit())
754 if (Visit(MakeCXCursor(Initializer, ND, TU)))
755 return true;
756 }
757 }
758
759 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
760 return true;
761 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000762
Douglas Gregorb1373d02010-01-20 20:59:29 +0000763 return false;
764}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000765
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000766bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
767 if (VisitDeclaratorDecl(D))
768 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770 if (Expr *BitWidth = D->getBitWidth())
771 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000772
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000773 return false;
774}
775
776bool CursorVisitor::VisitVarDecl(VarDecl *D) {
777 if (VisitDeclaratorDecl(D))
778 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780 if (Expr *Init = D->getInit())
781 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000783 return false;
784}
785
Douglas Gregor84b51d72010-09-01 20:16:53 +0000786bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
787 if (VisitDeclaratorDecl(D))
788 return true;
789
790 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
791 if (Expr *DefArg = D->getDefaultArgument())
792 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
793
794 return false;
795}
796
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000797bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
798 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
799 // before visiting these template parameters.
800 if (VisitTemplateParameters(D->getTemplateParameters()))
801 return true;
802
803 return VisitFunctionDecl(D->getTemplatedDecl());
804}
805
Douglas Gregor39d6f072010-08-31 19:02:00 +0000806bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
807 // FIXME: Visit the "outer" template parameter lists on the TagDecl
808 // before visiting these template parameters.
809 if (VisitTemplateParameters(D->getTemplateParameters()))
810 return true;
811
812 return VisitCXXRecordDecl(D->getTemplatedDecl());
813}
814
Douglas Gregor84b51d72010-09-01 20:16:53 +0000815bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
816 if (VisitTemplateParameters(D->getTemplateParameters()))
817 return true;
818
819 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
820 VisitTemplateArgumentLoc(D->getDefaultArgument()))
821 return true;
822
823 return false;
824}
825
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000826bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000827 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
828 if (Visit(TSInfo->getTypeLoc()))
829 return true;
830
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832 PEnd = ND->param_end();
833 P != PEnd; ++P) {
834 if (Visit(MakeCXCursor(*P, TU)))
835 return true;
836 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000837
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000838 if (ND->isThisDeclarationADefinition() &&
839 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
840 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 return false;
843}
844
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000845namespace {
846 struct ContainerDeclsSort {
847 SourceManager &SM;
848 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
849 bool operator()(Decl *A, Decl *B) {
850 SourceLocation L_A = A->getLocStart();
851 SourceLocation L_B = B->getLocStart();
852 assert(L_A.isValid() && L_B.isValid());
853 return SM.isBeforeInTranslationUnit(L_A, L_B);
854 }
855 };
856}
857
Douglas Gregora59e3902010-01-21 23:27:09 +0000858bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000859 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
860 // an @implementation can lexically contain Decls that are not properly
861 // nested in the AST. When we identify such cases, we need to retrofit
862 // this nesting here.
863 if (!DI_current)
864 return VisitDeclContext(D);
865
866 // Scan the Decls that immediately come after the container
867 // in the current DeclContext. If any fall within the
868 // container's lexical region, stash them into a vector
869 // for later processing.
870 llvm::SmallVector<Decl *, 24> DeclsInContainer;
871 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000872 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000873 if (EndLoc.isValid()) {
874 DeclContext::decl_iterator next = *DI_current;
875 while (++next != DE_current) {
876 Decl *D_next = *next;
877 if (!D_next)
878 break;
879 SourceLocation L = D_next->getLocStart();
880 if (!L.isValid())
881 break;
882 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
883 *DI_current = next;
884 DeclsInContainer.push_back(D_next);
885 continue;
886 }
887 break;
888 }
889 }
890
891 // The common case.
892 if (DeclsInContainer.empty())
893 return VisitDeclContext(D);
894
895 // Get all the Decls in the DeclContext, and sort them with the
896 // additional ones we've collected. Then visit them.
897 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
898 I!=E; ++I) {
899 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000900 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
901 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000902 continue;
903 DeclsInContainer.push_back(subDecl);
904 }
905
906 // Now sort the Decls so that they appear in lexical order.
907 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
908 ContainerDeclsSort(SM));
909
910 // Now visit the decls.
911 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
912 E = DeclsInContainer.end(); I != E; ++I) {
913 CXCursor Cursor = MakeCXCursor(*I, TU);
914 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
915 if (!V.hasValue())
916 continue;
917 if (!V.getValue())
918 return false;
919 if (Visit(Cursor, true))
920 return true;
921 }
922 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000923}
924
Douglas Gregorb1373d02010-01-20 20:59:29 +0000925bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000926 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
927 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000928 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000929
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000930 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
931 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
932 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000933 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000934 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000935
Douglas Gregora59e3902010-01-21 23:27:09 +0000936 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000937}
938
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000939bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
940 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
941 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
942 E = PID->protocol_end(); I != E; ++I, ++PL)
943 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
944 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000945
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000946 return VisitObjCContainerDecl(PID);
947}
948
Ted Kremenek23173d72010-05-18 21:09:07 +0000949bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000950 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000951 return true;
952
Ted Kremenek23173d72010-05-18 21:09:07 +0000953 // FIXME: This implements a workaround with @property declarations also being
954 // installed in the DeclContext for the @interface. Eventually this code
955 // should be removed.
956 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
957 if (!CDecl || !CDecl->IsClassExtension())
958 return false;
959
960 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
961 if (!ID)
962 return false;
963
964 IdentifierInfo *PropertyId = PD->getIdentifier();
965 ObjCPropertyDecl *prevDecl =
966 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
967
968 if (!prevDecl)
969 return false;
970
971 // Visit synthesized methods since they will be skipped when visiting
972 // the @interface.
973 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000974 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000975 if (Visit(MakeCXCursor(MD, TU)))
976 return true;
977
978 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000979 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000980 if (Visit(MakeCXCursor(MD, TU)))
981 return true;
982
983 return false;
984}
985
Douglas Gregorb1373d02010-01-20 20:59:29 +0000986bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000987 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988 if (D->getSuperClass() &&
989 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000991 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000992 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000994 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
995 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
996 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000997 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000998 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999
Douglas Gregora59e3902010-01-21 23:27:09 +00001000 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001001}
1002
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001003bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1004 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001005}
1006
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001007bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001008 // 'ID' could be null when dealing with invalid code.
1009 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1010 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001013 return VisitObjCImplDecl(D);
1014}
1015
1016bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1017#if 0
1018 // Issue callbacks for super class.
1019 // FIXME: No source location information!
1020 if (D->getSuperClass() &&
1021 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001023 TU)))
1024 return true;
1025#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001027 return VisitObjCImplDecl(D);
1028}
1029
1030bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1031 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1032 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1033 E = D->protocol_end();
1034 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001035 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001036 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037
1038 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001039}
1040
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001041bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1042 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1043 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1044 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001047}
1048
Douglas Gregora4ffd852010-11-17 01:03:52 +00001049bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1050 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1051 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1052
1053 return false;
1054}
1055
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001056bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1057 return VisitDeclContext(D);
1058}
1059
Douglas Gregor69319002010-08-31 23:48:11 +00001060bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001061 // Visit nested-name-specifier.
1062 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1063 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1064 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001065
1066 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1067 D->getTargetNameLoc(), TU));
1068}
1069
Douglas Gregor7e242562010-09-01 19:52:22 +00001070bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001071 // Visit nested-name-specifier.
1072 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1073 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1074 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001075
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001076 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1077 return true;
1078
Douglas Gregor7e242562010-09-01 19:52:22 +00001079 return VisitDeclarationNameInfo(D->getNameInfo());
1080}
1081
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001082bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001083 // Visit nested-name-specifier.
1084 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1085 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1086 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001087
1088 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1089 D->getIdentLocation(), TU));
1090}
1091
Douglas Gregor7e242562010-09-01 19:52:22 +00001092bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001093 // Visit nested-name-specifier.
1094 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1095 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1096 return true;
1097
Douglas Gregor7e242562010-09-01 19:52:22 +00001098 return VisitDeclarationNameInfo(D->getNameInfo());
1099}
1100
1101bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1102 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001103 // Visit nested-name-specifier.
1104 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1105 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1106 return true;
1107
Douglas Gregor7e242562010-09-01 19:52:22 +00001108 return false;
1109}
1110
Douglas Gregor01829d32010-08-31 14:41:23 +00001111bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1112 switch (Name.getName().getNameKind()) {
1113 case clang::DeclarationName::Identifier:
1114 case clang::DeclarationName::CXXLiteralOperatorName:
1115 case clang::DeclarationName::CXXOperatorName:
1116 case clang::DeclarationName::CXXUsingDirective:
1117 return false;
1118
1119 case clang::DeclarationName::CXXConstructorName:
1120 case clang::DeclarationName::CXXDestructorName:
1121 case clang::DeclarationName::CXXConversionFunctionName:
1122 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1123 return Visit(TSInfo->getTypeLoc());
1124 return false;
1125
1126 case clang::DeclarationName::ObjCZeroArgSelector:
1127 case clang::DeclarationName::ObjCOneArgSelector:
1128 case clang::DeclarationName::ObjCMultiArgSelector:
1129 // FIXME: Per-identifier location info?
1130 return false;
1131 }
1132
1133 return false;
1134}
1135
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001136bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1137 SourceRange Range) {
1138 // FIXME: This whole routine is a hack to work around the lack of proper
1139 // source information in nested-name-specifiers (PR5791). Since we do have
1140 // a beginning source location, we can visit the first component of the
1141 // nested-name-specifier, if it's a single-token component.
1142 if (!NNS)
1143 return false;
1144
1145 // Get the first component in the nested-name-specifier.
1146 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1147 NNS = Prefix;
1148
1149 switch (NNS->getKind()) {
1150 case NestedNameSpecifier::Namespace:
1151 // FIXME: The token at this source location might actually have been a
1152 // namespace alias, but we don't model that. Lame!
1153 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1154 TU));
1155
1156 case NestedNameSpecifier::TypeSpec: {
1157 // If the type has a form where we know that the beginning of the source
1158 // range matches up with a reference cursor. Visit the appropriate reference
1159 // cursor.
1160 Type *T = NNS->getAsType();
1161 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1162 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1163 if (const TagType *Tag = dyn_cast<TagType>(T))
1164 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1165 if (const TemplateSpecializationType *TST
1166 = dyn_cast<TemplateSpecializationType>(T))
1167 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1168 break;
1169 }
1170
1171 case NestedNameSpecifier::TypeSpecWithTemplate:
1172 case NestedNameSpecifier::Global:
1173 case NestedNameSpecifier::Identifier:
1174 break;
1175 }
1176
1177 return false;
1178}
1179
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001180bool CursorVisitor::VisitTemplateParameters(
1181 const TemplateParameterList *Params) {
1182 if (!Params)
1183 return false;
1184
1185 for (TemplateParameterList::const_iterator P = Params->begin(),
1186 PEnd = Params->end();
1187 P != PEnd; ++P) {
1188 if (Visit(MakeCXCursor(*P, TU)))
1189 return true;
1190 }
1191
1192 return false;
1193}
1194
Douglas Gregor0b36e612010-08-31 20:37:03 +00001195bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1196 switch (Name.getKind()) {
1197 case TemplateName::Template:
1198 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1199
1200 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001201 // Visit the overloaded template set.
1202 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1203 return true;
1204
Douglas Gregor0b36e612010-08-31 20:37:03 +00001205 return false;
1206
1207 case TemplateName::DependentTemplate:
1208 // FIXME: Visit nested-name-specifier.
1209 return false;
1210
1211 case TemplateName::QualifiedTemplate:
1212 // FIXME: Visit nested-name-specifier.
1213 return Visit(MakeCursorTemplateRef(
1214 Name.getAsQualifiedTemplateName()->getDecl(),
1215 Loc, TU));
1216 }
1217
1218 return false;
1219}
1220
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001221bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1222 switch (TAL.getArgument().getKind()) {
1223 case TemplateArgument::Null:
1224 case TemplateArgument::Integral:
1225 return false;
1226
1227 case TemplateArgument::Pack:
1228 // FIXME: Implement when variadic templates come along.
1229 return false;
1230
1231 case TemplateArgument::Type:
1232 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1233 return Visit(TSInfo->getTypeLoc());
1234 return false;
1235
1236 case TemplateArgument::Declaration:
1237 if (Expr *E = TAL.getSourceDeclExpression())
1238 return Visit(MakeCXCursor(E, StmtParent, TU));
1239 return false;
1240
1241 case TemplateArgument::Expression:
1242 if (Expr *E = TAL.getSourceExpression())
1243 return Visit(MakeCXCursor(E, StmtParent, TU));
1244 return false;
1245
1246 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001247 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1248 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001249 }
1250
1251 return false;
1252}
1253
Ted Kremeneka0536d82010-05-07 01:04:29 +00001254bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1255 return VisitDeclContext(D);
1256}
1257
Douglas Gregor01829d32010-08-31 14:41:23 +00001258bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1259 return Visit(TL.getUnqualifiedLoc());
1260}
1261
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001262bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001263 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001264
1265 // Some builtin types (such as Objective-C's "id", "sel", and
1266 // "Class") have associated declarations. Create cursors for those.
1267 QualType VisitType;
1268 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001269 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001271 case BuiltinType::Char_U:
1272 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273 case BuiltinType::Char16:
1274 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001275 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 case BuiltinType::UInt:
1277 case BuiltinType::ULong:
1278 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001279 case BuiltinType::UInt128:
1280 case BuiltinType::Char_S:
1281 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001282 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001283 case BuiltinType::Short:
1284 case BuiltinType::Int:
1285 case BuiltinType::Long:
1286 case BuiltinType::LongLong:
1287 case BuiltinType::Int128:
1288 case BuiltinType::Float:
1289 case BuiltinType::Double:
1290 case BuiltinType::LongDouble:
1291 case BuiltinType::NullPtr:
1292 case BuiltinType::Overload:
1293 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001294 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001295
1296 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001297 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001298
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001299 case BuiltinType::ObjCId:
1300 VisitType = Context.getObjCIdType();
1301 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001302
1303 case BuiltinType::ObjCClass:
1304 VisitType = Context.getObjCClassType();
1305 break;
1306
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001307 case BuiltinType::ObjCSel:
1308 VisitType = Context.getObjCSelType();
1309 break;
1310 }
1311
1312 if (!VisitType.isNull()) {
1313 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001314 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001315 TU));
1316 }
1317
1318 return false;
1319}
1320
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001321bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1322 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1323}
1324
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001325bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1326 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1327}
1328
1329bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1330 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1331}
1332
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001333bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001334 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001335 // no context information with which we can match up the depth/index in the
1336 // type to the appropriate
1337 return false;
1338}
1339
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1341 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1342 return true;
1343
John McCallc12c5bb2010-05-15 11:32:37 +00001344 return false;
1345}
1346
1347bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1348 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1349 return true;
1350
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001351 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1352 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1353 TU)))
1354 return true;
1355 }
1356
1357 return false;
1358}
1359
1360bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001361 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001362}
1363
1364bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1365 return Visit(TL.getPointeeLoc());
1366}
1367
1368bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1369 return Visit(TL.getPointeeLoc());
1370}
1371
1372bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1373 return Visit(TL.getPointeeLoc());
1374}
1375
1376bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378}
1379
1380bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001381 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001382}
1383
Douglas Gregor01829d32010-08-31 14:41:23 +00001384bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1385 bool SkipResultType) {
1386 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387 return true;
1388
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001389 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001390 if (Decl *D = TL.getArg(I))
1391 if (Visit(MakeCXCursor(D, TU)))
1392 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393
1394 return false;
1395}
1396
1397bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1398 if (Visit(TL.getElementLoc()))
1399 return true;
1400
1401 if (Expr *Size = TL.getSizeExpr())
1402 return Visit(MakeCXCursor(Size, StmtParent, TU));
1403
1404 return false;
1405}
1406
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001407bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1408 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001409 // Visit the template name.
1410 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1411 TL.getTemplateNameLoc()))
1412 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001413
1414 // Visit the template arguments.
1415 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1416 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1417 return true;
1418
1419 return false;
1420}
1421
Douglas Gregor2332c112010-01-21 20:48:56 +00001422bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1423 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1424}
1425
1426bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1427 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1428 return Visit(TSInfo->getTypeLoc());
1429
1430 return false;
1431}
1432
Douglas Gregora59e3902010-01-21 23:27:09 +00001433bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001434 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001435}
1436
Ted Kremenek3064ef92010-08-27 21:34:58 +00001437bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1438 if (D->isDefinition()) {
1439 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1440 E = D->bases_end(); I != E; ++I) {
1441 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1442 return true;
1443 }
1444 }
1445
1446 return VisitTagDecl(D);
1447}
1448
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001449bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001450 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001451 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1452 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001453
1454 // Visit the components of the offsetof expression.
1455 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1456 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1457 const OffsetOfNode &Node = E->getComponent(I);
1458 switch (Node.getKind()) {
1459 case OffsetOfNode::Array:
1460 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1461 StmtParent, TU)))
1462 return true;
1463 break;
1464
1465 case OffsetOfNode::Field:
1466 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1467 TU)))
1468 return true;
1469 break;
1470
1471 case OffsetOfNode::Identifier:
1472 case OffsetOfNode::Base:
1473 continue;
1474 }
1475 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001476
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001477 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001478}
1479
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001480bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1481 // Visit the designators.
1482 typedef DesignatedInitExpr::Designator Designator;
1483 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1484 DEnd = E->designators_end();
1485 D != DEnd; ++D) {
1486 if (D->isFieldDesignator()) {
1487 if (FieldDecl *Field = D->getField())
1488 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1489 return true;
1490
1491 continue;
1492 }
1493
1494 if (D->isArrayDesignator()) {
1495 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1496 return true;
1497
1498 continue;
1499 }
1500
1501 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1502 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1503 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1504 return true;
1505 }
1506
1507 // Visit the initializer value itself.
1508 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1509}
1510
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001511bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1512 // Visit base expression.
1513 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1514 return true;
1515
1516 // Visit the nested-name-specifier.
1517 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1518 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1519 return true;
1520
1521 // Visit the scope type that looks disturbingly like the nested-name-specifier
1522 // but isn't.
1523 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1524 if (Visit(TSInfo->getTypeLoc()))
1525 return true;
1526
1527 // Visit the name of the type being destroyed.
1528 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1529 if (Visit(TSInfo->getTypeLoc()))
1530 return true;
1531
1532 return false;
1533}
1534
Douglas Gregorbfebed22010-09-03 17:24:10 +00001535bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1536 DependentScopeDeclRefExpr *E) {
1537 // Visit the nested-name-specifier.
1538 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1539 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1540 return true;
1541
1542 // Visit the declaration name.
1543 if (VisitDeclarationNameInfo(E->getNameInfo()))
1544 return true;
1545
1546 // Visit the explicitly-specified template arguments.
1547 if (const ExplicitTemplateArgumentList *ArgList
1548 = E->getOptionalExplicitTemplateArgs()) {
1549 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1550 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1551 Arg != ArgEnd; ++Arg) {
1552 if (VisitTemplateArgumentLoc(*Arg))
1553 return true;
1554 }
1555 }
1556
1557 return false;
1558}
1559
Douglas Gregor25d63622010-09-03 17:35:34 +00001560bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1561 CXXDependentScopeMemberExpr *E) {
1562 // Visit the base expression, if there is one.
1563 if (!E->isImplicitAccess() &&
1564 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1565 return true;
1566
1567 // Visit the nested-name-specifier.
1568 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1569 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1570 return true;
1571
1572 // Visit the declaration name.
1573 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1574 return true;
1575
1576 // Visit the explicitly-specified template arguments.
1577 if (const ExplicitTemplateArgumentList *ArgList
1578 = E->getOptionalExplicitTemplateArgs()) {
1579 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1580 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1581 Arg != ArgEnd; ++Arg) {
1582 if (VisitTemplateArgumentLoc(*Arg))
1583 return true;
1584 }
1585 }
1586
1587 return false;
1588}
1589
Ted Kremenek09dfa372010-02-18 05:46:33 +00001590bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001591 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1592 i != e; ++i)
1593 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001594 return true;
1595
1596 return false;
1597}
1598
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001599//===----------------------------------------------------------------------===//
1600// Data-recursive visitor methods.
1601//===----------------------------------------------------------------------===//
1602
Ted Kremenek28a71942010-11-13 00:36:47 +00001603namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001604#define DEF_JOB(NAME, DATA, KIND)\
1605class NAME : public VisitorJob {\
1606public:\
1607 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1608 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1609 DATA *get() const { return static_cast<DATA*>(dataA); }\
1610};
1611
1612DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1613DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001614DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001615DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001616DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1617 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001618#undef DEF_JOB
1619
1620class DeclVisit : public VisitorJob {
1621public:
1622 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1623 VisitorJob(parent, VisitorJob::DeclVisitKind,
1624 d, isFirst ? (void*) 1 : (void*) 0) {}
1625 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001626 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001627 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001628 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001629 bool isFirst() const { return dataB ? true : false; }
1630};
Ted Kremenek035dc412010-11-13 00:36:50 +00001631class TypeLocVisit : public VisitorJob {
1632public:
1633 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1634 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1635 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1636
1637 static bool classof(const VisitorJob *VJ) {
1638 return VJ->getKind() == TypeLocVisitKind;
1639 }
1640
Ted Kremenek82f3c502010-11-15 22:23:26 +00001641 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001642 QualType T = QualType::getFromOpaquePtr(dataA);
1643 return TypeLoc(T, dataB);
1644 }
1645};
1646
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001647class LabelRefVisit : public VisitorJob {
1648public:
1649 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1650 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1651 (void*) labelLoc.getRawEncoding()) {}
1652
1653 static bool classof(const VisitorJob *VJ) {
1654 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1655 }
1656 LabelStmt *get() const { return static_cast<LabelStmt*>(dataA); }
1657 SourceLocation getLoc() const {
1658 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) dataB); }
1659};
1660
Ted Kremenek28a71942010-11-13 00:36:47 +00001661class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1662 VisitorWorkList &WL;
1663 CXCursor Parent;
1664public:
1665 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1666 : WL(wl), Parent(parent) {}
1667
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001668 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001669 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001670 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001671 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001672 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1673 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001674 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001675 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001676 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001677 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001678 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001679 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001680 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001681 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001682 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1683 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001684 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001685 void VisitIfStmt(IfStmt *If);
1686 void VisitInitListExpr(InitListExpr *IE);
1687 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001688 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001689 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1690 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001691 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001692 void VisitStmt(Stmt *S);
1693 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001694 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001695 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001696 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001697 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001698 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001699
1700private:
Ted Kremenek60608ec2010-11-17 00:50:47 +00001701 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenek28a71942010-11-13 00:36:47 +00001702 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001703 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void AddTypeLoc(TypeSourceInfo *TI);
1705 void EnqueueChildren(Stmt *S);
1706};
1707} // end anonyous namespace
1708
1709void EnqueueVisitor::AddStmt(Stmt *S) {
1710 if (S)
1711 WL.push_back(StmtVisit(S, Parent));
1712}
Ted Kremenek035dc412010-11-13 00:36:50 +00001713void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001714 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001715 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001716}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001717void EnqueueVisitor::
1718 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1719 if (A)
1720 WL.push_back(ExplicitTemplateArgsVisit(
1721 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1722}
Ted Kremenek28a71942010-11-13 00:36:47 +00001723void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1724 if (TI)
1725 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1726 }
1727void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001728 unsigned size = WL.size();
1729 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1730 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001731 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001732 }
1733 if (size == WL.size())
1734 return;
1735 // Now reverse the entries we just added. This will match the DFS
1736 // ordering performed by the worklist.
1737 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1738 std::reverse(I, E);
1739}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001740void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1741 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1742}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001743void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1744 AddDecl(B->getBlockDecl());
1745}
Ted Kremenek28a71942010-11-13 00:36:47 +00001746void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1747 EnqueueChildren(E);
1748 AddTypeLoc(E->getTypeSourceInfo());
1749}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001750void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1751 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1752 E = S->body_rend(); I != E; ++I) {
1753 AddStmt(*I);
1754 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001755}
1756void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1757 // Enqueue the initializer or constructor arguments.
1758 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1759 AddStmt(E->getConstructorArg(I-1));
1760 // Enqueue the array size, if any.
1761 AddStmt(E->getArraySize());
1762 // Enqueue the allocated type.
1763 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1764 // Enqueue the placement arguments.
1765 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1766 AddStmt(E->getPlacementArg(I-1));
1767}
Ted Kremenek28a71942010-11-13 00:36:47 +00001768void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001769 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1770 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001771 AddStmt(CE->getCallee());
1772 AddStmt(CE->getArg(0));
1773}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001774void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1775 AddTypeLoc(E->getTypeSourceInfo());
1776}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001777void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1778 EnqueueChildren(E);
1779 AddTypeLoc(E->getTypeSourceInfo());
1780}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001781void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1782 EnqueueChildren(E);
1783 if (E->isTypeOperand())
1784 AddTypeLoc(E->getTypeOperandSourceInfo());
1785}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001786
1787void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1788 *E) {
1789 EnqueueChildren(E);
1790 AddTypeLoc(E->getTypeSourceInfo());
1791}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001792void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1793 EnqueueChildren(E);
1794 if (E->isTypeOperand())
1795 AddTypeLoc(E->getTypeOperandSourceInfo());
1796}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001797void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001798 if (DR->hasExplicitTemplateArgs()) {
1799 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1800 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001801 WL.push_back(DeclRefExprParts(DR, Parent));
1802}
Ted Kremenek035dc412010-11-13 00:36:50 +00001803void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1804 unsigned size = WL.size();
1805 bool isFirst = true;
1806 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1807 D != DEnd; ++D) {
1808 AddDecl(*D, isFirst);
1809 isFirst = false;
1810 }
1811 if (size == WL.size())
1812 return;
1813 // Now reverse the entries we just added. This will match the DFS
1814 // ordering performed by the worklist.
1815 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1816 std::reverse(I, E);
1817}
Ted Kremenek28a71942010-11-13 00:36:47 +00001818void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1819 EnqueueChildren(E);
1820 AddTypeLoc(E->getTypeInfoAsWritten());
1821}
1822void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1823 AddStmt(FS->getBody());
1824 AddStmt(FS->getInc());
1825 AddStmt(FS->getCond());
1826 AddDecl(FS->getConditionVariable());
1827 AddStmt(FS->getInit());
1828}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001829void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1830 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1831}
Ted Kremenek28a71942010-11-13 00:36:47 +00001832void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1833 AddStmt(If->getElse());
1834 AddStmt(If->getThen());
1835 AddStmt(If->getCond());
1836 AddDecl(If->getConditionVariable());
1837}
1838void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1839 // We care about the syntactic form of the initializer list, only.
1840 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1841 IE = Syntactic;
1842 EnqueueChildren(IE);
1843}
1844void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001845 WL.push_back(MemberExprParts(M, Parent));
1846
1847 // If the base of the member access expression is an implicit 'this', don't
1848 // visit it.
1849 // FIXME: If we ever want to show these implicit accesses, this will be
1850 // unfortunate. However, clang_getCursor() relies on this behavior.
1851 if (CXXThisExpr *This
1852 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1853 if (This->isImplicit())
1854 return;
1855
Ted Kremenek28a71942010-11-13 00:36:47 +00001856 AddStmt(M->getBase());
1857}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001858void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1859 AddTypeLoc(E->getEncodedTypeSourceInfo());
1860}
Ted Kremenek28a71942010-11-13 00:36:47 +00001861void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1862 EnqueueChildren(M);
1863 AddTypeLoc(M->getClassReceiverTypeInfo());
1864}
1865void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001866 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001867 WL.push_back(OverloadExprParts(E, Parent));
1868}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001869void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1870 EnqueueChildren(E);
1871 if (E->isArgumentType())
1872 AddTypeLoc(E->getArgumentTypeInfo());
1873}
Ted Kremenek28a71942010-11-13 00:36:47 +00001874void EnqueueVisitor::VisitStmt(Stmt *S) {
1875 EnqueueChildren(S);
1876}
1877void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1878 AddStmt(S->getBody());
1879 AddStmt(S->getCond());
1880 AddDecl(S->getConditionVariable());
1881}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001882void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1883 AddTypeLoc(E->getArgTInfo2());
1884 AddTypeLoc(E->getArgTInfo1());
1885}
1886
Ted Kremenek28a71942010-11-13 00:36:47 +00001887void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1888 AddStmt(W->getBody());
1889 AddStmt(W->getCond());
1890 AddDecl(W->getConditionVariable());
1891}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001892void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1893 AddTypeLoc(E->getQueriedTypeSourceInfo());
1894}
Ted Kremenek28a71942010-11-13 00:36:47 +00001895void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1896 VisitOverloadExpr(U);
1897 if (!U->isImplicitAccess())
1898 AddStmt(U->getBase());
1899}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001900void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1901 AddStmt(E->getSubExpr());
1902 AddTypeLoc(E->getWrittenTypeInfo());
1903}
Ted Kremenek60458782010-11-12 21:34:16 +00001904
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001905void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001906 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001907}
1908
1909bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1910 if (RegionOfInterest.isValid()) {
1911 SourceRange Range = getRawCursorExtent(C);
1912 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1913 return false;
1914 }
1915 return true;
1916}
1917
1918bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1919 while (!WL.empty()) {
1920 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001921 VisitorJob LI = WL.back();
1922 WL.pop_back();
1923
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001924 // Set the Parent field, then back to its old value once we're done.
1925 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1926
1927 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001928 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001929 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001930 if (!D)
1931 continue;
1932
1933 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001934 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001935 return true;
1936
1937 continue;
1938 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001939 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1940 const ExplicitTemplateArgumentList *ArgList =
1941 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1942 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1943 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1944 Arg != ArgEnd; ++Arg) {
1945 if (VisitTemplateArgumentLoc(*Arg))
1946 return true;
1947 }
1948 continue;
1949 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001950 case VisitorJob::TypeLocVisitKind: {
1951 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001952 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001953 return true;
1954 continue;
1955 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001956 case VisitorJob::LabelRefVisitKind: {
1957 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1958 if (Visit(MakeCursorLabelRef(LS,
1959 cast<LabelRefVisit>(&LI)->getLoc(),
1960 TU)))
1961 return true;
1962 continue;
1963 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001964 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001965 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001966 if (!S)
1967 continue;
1968
Ted Kremenekf1107452010-11-12 18:26:56 +00001969 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001970 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1971
1972 switch (S->getStmtClass()) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001973 // Cases not yet handled by the data-recursion
1974 // algorithm.
1975 case Stmt::OffsetOfExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001976 case Stmt::DesignatedInitExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001977 case Stmt::CXXPseudoDestructorExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001978 case Stmt::DependentScopeDeclRefExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001979 case Stmt::CXXDependentScopeMemberExprClass:
1980 if (Visit(Cursor))
1981 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001982 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001983 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001984 if (!IsInRegionOfInterest(Cursor))
1985 continue;
1986 switch (Visitor(Cursor, Parent, ClientData)) {
1987 case CXChildVisit_Break:
1988 return true;
1989 case CXChildVisit_Continue:
1990 break;
1991 case CXChildVisit_Recurse:
1992 EnqueueWorkList(WL, S);
1993 break;
1994 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001995 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001996 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001997 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001998 }
1999 case VisitorJob::MemberExprPartsKind: {
2000 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002001 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002002
2003 // Visit the nested-name-specifier
2004 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2005 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2006 return true;
2007
2008 // Visit the declaration name.
2009 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2010 return true;
2011
2012 // Visit the explicitly-specified template arguments, if any.
2013 if (M->hasExplicitTemplateArgs()) {
2014 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2015 *ArgEnd = Arg + M->getNumTemplateArgs();
2016 Arg != ArgEnd; ++Arg) {
2017 if (VisitTemplateArgumentLoc(*Arg))
2018 return true;
2019 }
2020 }
2021 continue;
2022 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002023 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002024 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002025 // Visit nested-name-specifier, if present.
2026 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2027 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2028 return true;
2029 // Visit declaration name.
2030 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2031 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002032 continue;
2033 }
Ted Kremenek60458782010-11-12 21:34:16 +00002034 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002035 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002036 // Visit the nested-name-specifier.
2037 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2038 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2039 return true;
2040 // Visit the declaration name.
2041 if (VisitDeclarationNameInfo(O->getNameInfo()))
2042 return true;
2043 // Visit the overloaded declaration reference.
2044 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2045 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002046 continue;
2047 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002048 }
2049 }
2050 return false;
2051}
2052
2053bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002054 VisitorWorkList *WL = 0;
2055 if (!WorkListFreeList.empty()) {
2056 WL = WorkListFreeList.back();
2057 WL->clear();
2058 WorkListFreeList.pop_back();
2059 }
2060 else {
2061 WL = new VisitorWorkList();
2062 WorkListCache.push_back(WL);
2063 }
2064 EnqueueWorkList(*WL, S);
2065 bool result = RunVisitorWorkList(*WL);
2066 WorkListFreeList.push_back(WL);
2067 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002068}
2069
2070//===----------------------------------------------------------------------===//
2071// Misc. API hooks.
2072//===----------------------------------------------------------------------===//
2073
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002074static llvm::sys::Mutex EnableMultithreadingMutex;
2075static bool EnabledMultithreading;
2076
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002077extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002078CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2079 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002080 // Disable pretty stack trace functionality, which will otherwise be a very
2081 // poor citizen of the world and set up all sorts of signal handlers.
2082 llvm::DisablePrettyStackTrace = true;
2083
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002084 // We use crash recovery to make some of our APIs more reliable, implicitly
2085 // enable it.
2086 llvm::CrashRecoveryContext::Enable();
2087
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002088 // Enable support for multithreading in LLVM.
2089 {
2090 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2091 if (!EnabledMultithreading) {
2092 llvm::llvm_start_multithreaded();
2093 EnabledMultithreading = true;
2094 }
2095 }
2096
Douglas Gregora030b7c2010-01-22 20:35:53 +00002097 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002098 if (excludeDeclarationsFromPCH)
2099 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002100 if (displayDiagnostics)
2101 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002102 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002103}
2104
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002105void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002106 if (CIdx)
2107 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002108}
2109
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002110CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002111 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002112 if (!CIdx)
2113 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002114
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002115 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002116 FileSystemOptions FileSystemOpts;
2117 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002118
Douglas Gregor28019772010-04-05 23:52:57 +00002119 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002120 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002121 CXXIdx->getOnlyLocalDecls(),
2122 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002123 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002124}
2125
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002126unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002127 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002128 CXTranslationUnit_CacheCompletionResults |
2129 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002130}
2131
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002132CXTranslationUnit
2133clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2134 const char *source_filename,
2135 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002136 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002137 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002138 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002139 return clang_parseTranslationUnit(CIdx, source_filename,
2140 command_line_args, num_command_line_args,
2141 unsaved_files, num_unsaved_files,
2142 CXTranslationUnit_DetailedPreprocessingRecord);
2143}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002144
2145struct ParseTranslationUnitInfo {
2146 CXIndex CIdx;
2147 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002148 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002149 int num_command_line_args;
2150 struct CXUnsavedFile *unsaved_files;
2151 unsigned num_unsaved_files;
2152 unsigned options;
2153 CXTranslationUnit result;
2154};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002155static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002156 ParseTranslationUnitInfo *PTUI =
2157 static_cast<ParseTranslationUnitInfo*>(UserData);
2158 CXIndex CIdx = PTUI->CIdx;
2159 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002160 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002161 int num_command_line_args = PTUI->num_command_line_args;
2162 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2163 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2164 unsigned options = PTUI->options;
2165 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002166
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002167 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002168 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002169
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002170 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2171
Douglas Gregor44c181a2010-07-23 00:33:23 +00002172 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002173 bool CompleteTranslationUnit
2174 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002175 bool CacheCodeCompetionResults
2176 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002177 bool CXXPrecompilePreamble
2178 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2179 bool CXXChainedPCH
2180 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002181
Douglas Gregor5352ac02010-01-28 00:27:43 +00002182 // Configure the diagnostics.
2183 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002184 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2185 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002186
Douglas Gregor4db64a42010-01-23 00:14:00 +00002187 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2188 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002189 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002190 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002191 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002192 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2193 Buffer));
2194 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
Douglas Gregorb10daed2010-10-11 16:52:23 +00002196 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002197
Ted Kremenek139ba862009-10-22 00:03:57 +00002198 // The 'source_filename' argument is optional. If the caller does not
2199 // specify it then it is assumed that the source file is specified
2200 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002201 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002202 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002203
2204 // Since the Clang C library is primarily used by batch tools dealing with
2205 // (often very broken) source code, where spell-checking can have a
2206 // significant negative impact on performance (particularly when
2207 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002208 // Only do this if we haven't found a spell-checking-related argument.
2209 bool FoundSpellCheckingArgument = false;
2210 for (int I = 0; I != num_command_line_args; ++I) {
2211 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2212 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2213 FoundSpellCheckingArgument = true;
2214 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002215 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 }
2217 if (!FoundSpellCheckingArgument)
2218 Args.push_back("-fno-spell-checking");
2219
2220 Args.insert(Args.end(), command_line_args,
2221 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002222
Douglas Gregor44c181a2010-07-23 00:33:23 +00002223 // Do we need the detailed preprocessing record?
2224 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002225 Args.push_back("-Xclang");
2226 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002227 }
2228
Douglas Gregorb10daed2010-10-11 16:52:23 +00002229 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002230 llvm::OwningPtr<ASTUnit> Unit(
2231 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2232 Diags,
2233 CXXIdx->getClangResourcesPath(),
2234 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002235 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002236 RemappedFiles.data(),
2237 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002238 PrecompilePreamble,
2239 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002240 CacheCodeCompetionResults,
2241 CXXPrecompilePreamble,
2242 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002243
Douglas Gregorb10daed2010-10-11 16:52:23 +00002244 if (NumErrors != Diags->getNumErrors()) {
2245 // Make sure to check that 'Unit' is non-NULL.
2246 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2247 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2248 DEnd = Unit->stored_diag_end();
2249 D != DEnd; ++D) {
2250 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2251 CXString Msg = clang_formatDiagnostic(&Diag,
2252 clang_defaultDiagnosticDisplayOptions());
2253 fprintf(stderr, "%s\n", clang_getCString(Msg));
2254 clang_disposeString(Msg);
2255 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002256#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002257 // On Windows, force a flush, since there may be multiple copies of
2258 // stderr and stdout in the file system, all with different buffers
2259 // but writing to the same device.
2260 fflush(stderr);
2261#endif
2262 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002263 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002264
Ted Kremeneka60ed472010-11-16 08:15:36 +00002265 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002266}
2267CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2268 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002269 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002270 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002271 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002272 unsigned num_unsaved_files,
2273 unsigned options) {
2274 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002275 num_command_line_args, unsaved_files,
2276 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002277 llvm::CrashRecoveryContext CRC;
2278
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002279 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002280 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2281 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2282 fprintf(stderr, " 'command_line_args' : [");
2283 for (int i = 0; i != num_command_line_args; ++i) {
2284 if (i)
2285 fprintf(stderr, ", ");
2286 fprintf(stderr, "'%s'", command_line_args[i]);
2287 }
2288 fprintf(stderr, "],\n");
2289 fprintf(stderr, " 'unsaved_files' : [");
2290 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2291 if (i)
2292 fprintf(stderr, ", ");
2293 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2294 unsaved_files[i].Length);
2295 }
2296 fprintf(stderr, "],\n");
2297 fprintf(stderr, " 'options' : %d,\n", options);
2298 fprintf(stderr, "}\n");
2299
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002300 return 0;
2301 }
2302
2303 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002304}
2305
Douglas Gregor19998442010-08-13 15:35:05 +00002306unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2307 return CXSaveTranslationUnit_None;
2308}
2309
2310int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2311 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002312 if (!TU)
2313 return 1;
2314
Ted Kremeneka60ed472010-11-16 08:15:36 +00002315 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002316}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002317
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002318void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002319 if (CTUnit) {
2320 // If the translation unit has been marked as unsafe to free, just discard
2321 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002322 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002323 return;
2324
Ted Kremeneka60ed472010-11-16 08:15:36 +00002325 delete static_cast<ASTUnit *>(CTUnit->TUData);
2326 disposeCXStringPool(CTUnit->StringPool);
2327 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002328 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002329}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002330
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002331unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2332 return CXReparse_None;
2333}
2334
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002335struct ReparseTranslationUnitInfo {
2336 CXTranslationUnit TU;
2337 unsigned num_unsaved_files;
2338 struct CXUnsavedFile *unsaved_files;
2339 unsigned options;
2340 int result;
2341};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002342
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002343static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002344 ReparseTranslationUnitInfo *RTUI =
2345 static_cast<ReparseTranslationUnitInfo*>(UserData);
2346 CXTranslationUnit TU = RTUI->TU;
2347 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2348 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2349 unsigned options = RTUI->options;
2350 (void) options;
2351 RTUI->result = 1;
2352
Douglas Gregorabc563f2010-07-19 21:46:24 +00002353 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002354 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002355
Ted Kremeneka60ed472010-11-16 08:15:36 +00002356 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002357 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002358
2359 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2360 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2361 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2362 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002363 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002364 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2365 Buffer));
2366 }
2367
Douglas Gregor593b0c12010-09-23 18:47:53 +00002368 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2369 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002370}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002371
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002372int clang_reparseTranslationUnit(CXTranslationUnit TU,
2373 unsigned num_unsaved_files,
2374 struct CXUnsavedFile *unsaved_files,
2375 unsigned options) {
2376 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2377 options, 0 };
2378 llvm::CrashRecoveryContext CRC;
2379
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002380 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002381 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002382 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002383 return 1;
2384 }
2385
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002386
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002387 return RTUI.result;
2388}
2389
Douglas Gregordf95a132010-08-09 20:45:32 +00002390
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002391CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002392 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002393 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002394
Ted Kremeneka60ed472010-11-16 08:15:36 +00002395 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002396 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002397}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002398
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002399CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002400 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002401 return Result;
2402}
2403
Ted Kremenekfb480492010-01-13 21:46:36 +00002404} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002405
Ted Kremenekfb480492010-01-13 21:46:36 +00002406//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002407// CXSourceLocation and CXSourceRange Operations.
2408//===----------------------------------------------------------------------===//
2409
Douglas Gregorb9790342010-01-22 21:44:22 +00002410extern "C" {
2411CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002412 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002413 return Result;
2414}
2415
2416unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002417 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2418 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2419 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002420}
2421
2422CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2423 CXFile file,
2424 unsigned line,
2425 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002426 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002427 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002428
Ted Kremeneka60ed472010-11-16 08:15:36 +00002429 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002430 SourceLocation SLoc
2431 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002432 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002433 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002434 if (SLoc.isInvalid()) return clang_getNullLocation();
2435
2436 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2437}
2438
2439CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2440 CXFile file,
2441 unsigned offset) {
2442 if (!tu || !file)
2443 return clang_getNullLocation();
2444
Ted Kremeneka60ed472010-11-16 08:15:36 +00002445 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002446 SourceLocation Start
2447 = CXXUnit->getSourceManager().getLocation(
2448 static_cast<const FileEntry *>(file),
2449 1, 1);
2450 if (Start.isInvalid()) return clang_getNullLocation();
2451
2452 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2453
2454 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002455
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002456 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002457}
2458
Douglas Gregor5352ac02010-01-28 00:27:43 +00002459CXSourceRange clang_getNullRange() {
2460 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2461 return Result;
2462}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002463
Douglas Gregor5352ac02010-01-28 00:27:43 +00002464CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2465 if (begin.ptr_data[0] != end.ptr_data[0] ||
2466 begin.ptr_data[1] != end.ptr_data[1])
2467 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002468
2469 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002470 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002471 return Result;
2472}
2473
Douglas Gregor46766dc2010-01-26 19:19:08 +00002474void clang_getInstantiationLocation(CXSourceLocation location,
2475 CXFile *file,
2476 unsigned *line,
2477 unsigned *column,
2478 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002479 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2480
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002481 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002482 if (file)
2483 *file = 0;
2484 if (line)
2485 *line = 0;
2486 if (column)
2487 *column = 0;
2488 if (offset)
2489 *offset = 0;
2490 return;
2491 }
2492
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002493 const SourceManager &SM =
2494 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002495 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002496
2497 if (file)
2498 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2499 if (line)
2500 *line = SM.getInstantiationLineNumber(InstLoc);
2501 if (column)
2502 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002503 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002504 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002505}
2506
Douglas Gregora9b06d42010-11-09 06:24:54 +00002507void clang_getSpellingLocation(CXSourceLocation location,
2508 CXFile *file,
2509 unsigned *line,
2510 unsigned *column,
2511 unsigned *offset) {
2512 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2513
2514 if (!location.ptr_data[0] || Loc.isInvalid()) {
2515 if (file)
2516 *file = 0;
2517 if (line)
2518 *line = 0;
2519 if (column)
2520 *column = 0;
2521 if (offset)
2522 *offset = 0;
2523 return;
2524 }
2525
2526 const SourceManager &SM =
2527 *static_cast<const SourceManager*>(location.ptr_data[0]);
2528 SourceLocation SpellLoc = Loc;
2529 if (SpellLoc.isMacroID()) {
2530 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2531 if (SimpleSpellingLoc.isFileID() &&
2532 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2533 SpellLoc = SimpleSpellingLoc;
2534 else
2535 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2536 }
2537
2538 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2539 FileID FID = LocInfo.first;
2540 unsigned FileOffset = LocInfo.second;
2541
2542 if (file)
2543 *file = (void *)SM.getFileEntryForID(FID);
2544 if (line)
2545 *line = SM.getLineNumber(FID, FileOffset);
2546 if (column)
2547 *column = SM.getColumnNumber(FID, FileOffset);
2548 if (offset)
2549 *offset = FileOffset;
2550}
2551
Douglas Gregor1db19de2010-01-19 21:36:55 +00002552CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002553 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002554 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002555 return Result;
2556}
2557
2558CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002559 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002560 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002561 return Result;
2562}
2563
Douglas Gregorb9790342010-01-22 21:44:22 +00002564} // end: extern "C"
2565
Douglas Gregor1db19de2010-01-19 21:36:55 +00002566//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002567// CXFile Operations.
2568//===----------------------------------------------------------------------===//
2569
2570extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002571CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002572 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002573 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002574
Steve Naroff88145032009-10-27 14:35:18 +00002575 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002576 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002577}
2578
2579time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002580 if (!SFile)
2581 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582
Steve Naroff88145032009-10-27 14:35:18 +00002583 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2584 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002585}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002586
Douglas Gregorb9790342010-01-22 21:44:22 +00002587CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2588 if (!tu)
2589 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590
Ted Kremeneka60ed472010-11-16 08:15:36 +00002591 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
Douglas Gregorb9790342010-01-22 21:44:22 +00002593 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002594 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2595 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002596 return const_cast<FileEntry *>(File);
2597}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Ted Kremenekfb480492010-01-13 21:46:36 +00002599} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002600
Ted Kremenekfb480492010-01-13 21:46:36 +00002601//===----------------------------------------------------------------------===//
2602// CXCursor Operations.
2603//===----------------------------------------------------------------------===//
2604
Ted Kremenekfb480492010-01-13 21:46:36 +00002605static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002606 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2607 return getDeclFromExpr(CE->getSubExpr());
2608
Ted Kremenekfb480492010-01-13 21:46:36 +00002609 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2610 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002611 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2612 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002613 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2614 return ME->getMemberDecl();
2615 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2616 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002617 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2618 return PRE->getProperty();
2619
Ted Kremenekfb480492010-01-13 21:46:36 +00002620 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2621 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002622 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2623 if (!CE->isElidable())
2624 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002625 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2626 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002627
Douglas Gregordb1314e2010-10-01 21:11:22 +00002628 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2629 return PE->getProtocol();
2630
Ted Kremenekfb480492010-01-13 21:46:36 +00002631 return 0;
2632}
2633
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002634static SourceLocation getLocationFromExpr(Expr *E) {
2635 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2636 return /*FIXME:*/Msg->getLeftLoc();
2637 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2638 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002639 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2640 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002641 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2642 return Member->getMemberLoc();
2643 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2644 return Ivar->getLocation();
2645 return E->getLocStart();
2646}
2647
Ted Kremenekfb480492010-01-13 21:46:36 +00002648extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002649
2650unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002651 CXCursorVisitor visitor,
2652 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002653 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2654 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002655 return CursorVis.VisitChildren(parent);
2656}
2657
David Chisnall3387c652010-11-03 14:12:26 +00002658#ifndef __has_feature
2659#define __has_feature(x) 0
2660#endif
2661#if __has_feature(blocks)
2662typedef enum CXChildVisitResult
2663 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2664
2665static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2666 CXClientData client_data) {
2667 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2668 return block(cursor, parent);
2669}
2670#else
2671// If we are compiled with a compiler that doesn't have native blocks support,
2672// define and call the block manually, so the
2673typedef struct _CXChildVisitResult
2674{
2675 void *isa;
2676 int flags;
2677 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002678 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2679 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002680} *CXCursorVisitorBlock;
2681
2682static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2683 CXClientData client_data) {
2684 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2685 return block->invoke(block, cursor, parent);
2686}
2687#endif
2688
2689
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002690unsigned clang_visitChildrenWithBlock(CXCursor parent,
2691 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002692 return clang_visitChildren(parent, visitWithBlock, block);
2693}
2694
Douglas Gregor78205d42010-01-20 21:45:58 +00002695static CXString getDeclSpelling(Decl *D) {
2696 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002697 if (!ND) {
2698 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2699 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2700 return createCXString(Property->getIdentifier()->getName());
2701
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002702 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002703 }
2704
Douglas Gregor78205d42010-01-20 21:45:58 +00002705 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002706 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002707
Douglas Gregor78205d42010-01-20 21:45:58 +00002708 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2709 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2710 // and returns different names. NamedDecl returns the class name and
2711 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002712 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002713
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002714 if (isa<UsingDirectiveDecl>(D))
2715 return createCXString("");
2716
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002717 llvm::SmallString<1024> S;
2718 llvm::raw_svector_ostream os(S);
2719 ND->printName(os);
2720
2721 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002722}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002723
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002724CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002725 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002726 return clang_getTranslationUnitSpelling(
2727 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002728
Steve Narofff334b4e2009-09-02 18:26:48 +00002729 if (clang_isReference(C.kind)) {
2730 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002731 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002732 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002733 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002734 }
2735 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002736 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002737 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002738 }
2739 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002740 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002741 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002742 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002743 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002744 case CXCursor_CXXBaseSpecifier: {
2745 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2746 return createCXString(B->getType().getAsString());
2747 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002748 case CXCursor_TypeRef: {
2749 TypeDecl *Type = getCursorTypeRef(C).first;
2750 assert(Type && "Missing type decl");
2751
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002752 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2753 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002754 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002755 case CXCursor_TemplateRef: {
2756 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002757 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002758
2759 return createCXString(Template->getNameAsString());
2760 }
Douglas Gregor69319002010-08-31 23:48:11 +00002761
2762 case CXCursor_NamespaceRef: {
2763 NamedDecl *NS = getCursorNamespaceRef(C).first;
2764 assert(NS && "Missing namespace decl");
2765
2766 return createCXString(NS->getNameAsString());
2767 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002768
Douglas Gregora67e03f2010-09-09 21:42:20 +00002769 case CXCursor_MemberRef: {
2770 FieldDecl *Field = getCursorMemberRef(C).first;
2771 assert(Field && "Missing member decl");
2772
2773 return createCXString(Field->getNameAsString());
2774 }
2775
Douglas Gregor36897b02010-09-10 00:22:18 +00002776 case CXCursor_LabelRef: {
2777 LabelStmt *Label = getCursorLabelRef(C).first;
2778 assert(Label && "Missing label");
2779
2780 return createCXString(Label->getID()->getName());
2781 }
2782
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002783 case CXCursor_OverloadedDeclRef: {
2784 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2785 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2786 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2787 return createCXString(ND->getNameAsString());
2788 return createCXString("");
2789 }
2790 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2791 return createCXString(E->getName().getAsString());
2792 OverloadedTemplateStorage *Ovl
2793 = Storage.get<OverloadedTemplateStorage*>();
2794 if (Ovl->size() == 0)
2795 return createCXString("");
2796 return createCXString((*Ovl->begin())->getNameAsString());
2797 }
2798
Daniel Dunbaracca7252009-11-30 20:42:49 +00002799 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002800 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002801 }
2802 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002803
2804 if (clang_isExpression(C.kind)) {
2805 Decl *D = getDeclFromExpr(getCursorExpr(C));
2806 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002807 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002808 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002809 }
2810
Douglas Gregor36897b02010-09-10 00:22:18 +00002811 if (clang_isStatement(C.kind)) {
2812 Stmt *S = getCursorStmt(C);
2813 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2814 return createCXString(Label->getID()->getName());
2815
2816 return createCXString("");
2817 }
2818
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002819 if (C.kind == CXCursor_MacroInstantiation)
2820 return createCXString(getCursorMacroInstantiation(C)->getName()
2821 ->getNameStart());
2822
Douglas Gregor572feb22010-03-18 18:04:21 +00002823 if (C.kind == CXCursor_MacroDefinition)
2824 return createCXString(getCursorMacroDefinition(C)->getName()
2825 ->getNameStart());
2826
Douglas Gregorecdcb882010-10-20 22:00:55 +00002827 if (C.kind == CXCursor_InclusionDirective)
2828 return createCXString(getCursorInclusionDirective(C)->getFileName());
2829
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002830 if (clang_isDeclaration(C.kind))
2831 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002832
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002833 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002834}
2835
Douglas Gregor358559d2010-10-02 22:49:11 +00002836CXString clang_getCursorDisplayName(CXCursor C) {
2837 if (!clang_isDeclaration(C.kind))
2838 return clang_getCursorSpelling(C);
2839
2840 Decl *D = getCursorDecl(C);
2841 if (!D)
2842 return createCXString("");
2843
2844 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2845 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2846 D = FunTmpl->getTemplatedDecl();
2847
2848 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2849 llvm::SmallString<64> Str;
2850 llvm::raw_svector_ostream OS(Str);
2851 OS << Function->getNameAsString();
2852 if (Function->getPrimaryTemplate())
2853 OS << "<>";
2854 OS << "(";
2855 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2856 if (I)
2857 OS << ", ";
2858 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2859 }
2860
2861 if (Function->isVariadic()) {
2862 if (Function->getNumParams())
2863 OS << ", ";
2864 OS << "...";
2865 }
2866 OS << ")";
2867 return createCXString(OS.str());
2868 }
2869
2870 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2871 llvm::SmallString<64> Str;
2872 llvm::raw_svector_ostream OS(Str);
2873 OS << ClassTemplate->getNameAsString();
2874 OS << "<";
2875 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2876 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2877 if (I)
2878 OS << ", ";
2879
2880 NamedDecl *Param = Params->getParam(I);
2881 if (Param->getIdentifier()) {
2882 OS << Param->getIdentifier()->getName();
2883 continue;
2884 }
2885
2886 // There is no parameter name, which makes this tricky. Try to come up
2887 // with something useful that isn't too long.
2888 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2889 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2890 else if (NonTypeTemplateParmDecl *NTTP
2891 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2892 OS << NTTP->getType().getAsString(Policy);
2893 else
2894 OS << "template<...> class";
2895 }
2896
2897 OS << ">";
2898 return createCXString(OS.str());
2899 }
2900
2901 if (ClassTemplateSpecializationDecl *ClassSpec
2902 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2903 // If the type was explicitly written, use that.
2904 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2905 return createCXString(TSInfo->getType().getAsString(Policy));
2906
2907 llvm::SmallString<64> Str;
2908 llvm::raw_svector_ostream OS(Str);
2909 OS << ClassSpec->getNameAsString();
2910 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002911 ClassSpec->getTemplateArgs().data(),
2912 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002913 Policy);
2914 return createCXString(OS.str());
2915 }
2916
2917 return clang_getCursorSpelling(C);
2918}
2919
Ted Kremeneke68fff62010-02-17 00:41:32 +00002920CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002921 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002922 case CXCursor_FunctionDecl:
2923 return createCXString("FunctionDecl");
2924 case CXCursor_TypedefDecl:
2925 return createCXString("TypedefDecl");
2926 case CXCursor_EnumDecl:
2927 return createCXString("EnumDecl");
2928 case CXCursor_EnumConstantDecl:
2929 return createCXString("EnumConstantDecl");
2930 case CXCursor_StructDecl:
2931 return createCXString("StructDecl");
2932 case CXCursor_UnionDecl:
2933 return createCXString("UnionDecl");
2934 case CXCursor_ClassDecl:
2935 return createCXString("ClassDecl");
2936 case CXCursor_FieldDecl:
2937 return createCXString("FieldDecl");
2938 case CXCursor_VarDecl:
2939 return createCXString("VarDecl");
2940 case CXCursor_ParmDecl:
2941 return createCXString("ParmDecl");
2942 case CXCursor_ObjCInterfaceDecl:
2943 return createCXString("ObjCInterfaceDecl");
2944 case CXCursor_ObjCCategoryDecl:
2945 return createCXString("ObjCCategoryDecl");
2946 case CXCursor_ObjCProtocolDecl:
2947 return createCXString("ObjCProtocolDecl");
2948 case CXCursor_ObjCPropertyDecl:
2949 return createCXString("ObjCPropertyDecl");
2950 case CXCursor_ObjCIvarDecl:
2951 return createCXString("ObjCIvarDecl");
2952 case CXCursor_ObjCInstanceMethodDecl:
2953 return createCXString("ObjCInstanceMethodDecl");
2954 case CXCursor_ObjCClassMethodDecl:
2955 return createCXString("ObjCClassMethodDecl");
2956 case CXCursor_ObjCImplementationDecl:
2957 return createCXString("ObjCImplementationDecl");
2958 case CXCursor_ObjCCategoryImplDecl:
2959 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002960 case CXCursor_CXXMethod:
2961 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002962 case CXCursor_UnexposedDecl:
2963 return createCXString("UnexposedDecl");
2964 case CXCursor_ObjCSuperClassRef:
2965 return createCXString("ObjCSuperClassRef");
2966 case CXCursor_ObjCProtocolRef:
2967 return createCXString("ObjCProtocolRef");
2968 case CXCursor_ObjCClassRef:
2969 return createCXString("ObjCClassRef");
2970 case CXCursor_TypeRef:
2971 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002972 case CXCursor_TemplateRef:
2973 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002974 case CXCursor_NamespaceRef:
2975 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002976 case CXCursor_MemberRef:
2977 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002978 case CXCursor_LabelRef:
2979 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002980 case CXCursor_OverloadedDeclRef:
2981 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002982 case CXCursor_UnexposedExpr:
2983 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002984 case CXCursor_BlockExpr:
2985 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002986 case CXCursor_DeclRefExpr:
2987 return createCXString("DeclRefExpr");
2988 case CXCursor_MemberRefExpr:
2989 return createCXString("MemberRefExpr");
2990 case CXCursor_CallExpr:
2991 return createCXString("CallExpr");
2992 case CXCursor_ObjCMessageExpr:
2993 return createCXString("ObjCMessageExpr");
2994 case CXCursor_UnexposedStmt:
2995 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002996 case CXCursor_LabelStmt:
2997 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002998 case CXCursor_InvalidFile:
2999 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003000 case CXCursor_InvalidCode:
3001 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003002 case CXCursor_NoDeclFound:
3003 return createCXString("NoDeclFound");
3004 case CXCursor_NotImplemented:
3005 return createCXString("NotImplemented");
3006 case CXCursor_TranslationUnit:
3007 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003008 case CXCursor_UnexposedAttr:
3009 return createCXString("UnexposedAttr");
3010 case CXCursor_IBActionAttr:
3011 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003012 case CXCursor_IBOutletAttr:
3013 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003014 case CXCursor_IBOutletCollectionAttr:
3015 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003016 case CXCursor_PreprocessingDirective:
3017 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003018 case CXCursor_MacroDefinition:
3019 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003020 case CXCursor_MacroInstantiation:
3021 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003022 case CXCursor_InclusionDirective:
3023 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003024 case CXCursor_Namespace:
3025 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003026 case CXCursor_LinkageSpec:
3027 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003028 case CXCursor_CXXBaseSpecifier:
3029 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003030 case CXCursor_Constructor:
3031 return createCXString("CXXConstructor");
3032 case CXCursor_Destructor:
3033 return createCXString("CXXDestructor");
3034 case CXCursor_ConversionFunction:
3035 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003036 case CXCursor_TemplateTypeParameter:
3037 return createCXString("TemplateTypeParameter");
3038 case CXCursor_NonTypeTemplateParameter:
3039 return createCXString("NonTypeTemplateParameter");
3040 case CXCursor_TemplateTemplateParameter:
3041 return createCXString("TemplateTemplateParameter");
3042 case CXCursor_FunctionTemplate:
3043 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003044 case CXCursor_ClassTemplate:
3045 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003046 case CXCursor_ClassTemplatePartialSpecialization:
3047 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003048 case CXCursor_NamespaceAlias:
3049 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003050 case CXCursor_UsingDirective:
3051 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003052 case CXCursor_UsingDeclaration:
3053 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003054 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003055
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003056 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003057 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003058}
Steve Naroff89922f82009-08-31 00:59:03 +00003059
Ted Kremeneke68fff62010-02-17 00:41:32 +00003060enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3061 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003062 CXClientData client_data) {
3063 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003064
3065 // If our current best cursor is the construction of a temporary object,
3066 // don't replace that cursor with a type reference, because we want
3067 // clang_getCursor() to point at the constructor.
3068 if (clang_isExpression(BestCursor->kind) &&
3069 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3070 cursor.kind == CXCursor_TypeRef)
3071 return CXChildVisit_Recurse;
3072
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003073 *BestCursor = cursor;
3074 return CXChildVisit_Recurse;
3075}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003076
Douglas Gregorb9790342010-01-22 21:44:22 +00003077CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3078 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003079 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003080
Ted Kremeneka60ed472010-11-16 08:15:36 +00003081 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003082 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3083
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003084 // Translate the given source location to make it point at the beginning of
3085 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003086 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003087
3088 // Guard against an invalid SourceLocation, or we may assert in one
3089 // of the following calls.
3090 if (SLoc.isInvalid())
3091 return clang_getNullCursor();
3092
Douglas Gregor40749ee2010-11-03 00:35:38 +00003093 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003094 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3095 CXXUnit->getASTContext().getLangOptions());
3096
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003097 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3098 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003099 // FIXME: Would be great to have a "hint" cursor, then walk from that
3100 // hint cursor upward until we find a cursor whose source range encloses
3101 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003102 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3103 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003104 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003105 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003106 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003107
3108 if (Logging) {
3109 CXFile SearchFile;
3110 unsigned SearchLine, SearchColumn;
3111 CXFile ResultFile;
3112 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003113 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3114 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003115 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3116
3117 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3118 0);
3119 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3120 &ResultColumn, 0);
3121 SearchFileName = clang_getFileName(SearchFile);
3122 ResultFileName = clang_getFileName(ResultFile);
3123 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003124 USR = clang_getCursorUSR(Result);
3125 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003126 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3127 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003128 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3129 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003130 clang_disposeString(SearchFileName);
3131 clang_disposeString(ResultFileName);
3132 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003133 clang_disposeString(USR);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003134 }
3135
Ted Kremeneke68fff62010-02-17 00:41:32 +00003136 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003137}
3138
Ted Kremenek73885552009-11-17 19:28:59 +00003139CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003140 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003141}
3142
3143unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003144 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003145}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003146
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003147unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003148 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3149}
3150
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003151unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003152 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3153}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003154
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003155unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003156 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3157}
3158
Douglas Gregor97b98722010-01-19 23:20:36 +00003159unsigned clang_isExpression(enum CXCursorKind K) {
3160 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3161}
3162
3163unsigned clang_isStatement(enum CXCursorKind K) {
3164 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3165}
3166
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003167unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3168 return K == CXCursor_TranslationUnit;
3169}
3170
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003171unsigned clang_isPreprocessing(enum CXCursorKind K) {
3172 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3173}
3174
Ted Kremenekad6eff62010-03-08 21:17:29 +00003175unsigned clang_isUnexposed(enum CXCursorKind K) {
3176 switch (K) {
3177 case CXCursor_UnexposedDecl:
3178 case CXCursor_UnexposedExpr:
3179 case CXCursor_UnexposedStmt:
3180 case CXCursor_UnexposedAttr:
3181 return true;
3182 default:
3183 return false;
3184 }
3185}
3186
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003187CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003188 return C.kind;
3189}
3190
Douglas Gregor98258af2010-01-18 22:46:11 +00003191CXSourceLocation clang_getCursorLocation(CXCursor C) {
3192 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003193 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003194 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003195 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3196 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003197 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003198 }
3199
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003200 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003201 std::pair<ObjCProtocolDecl *, SourceLocation> P
3202 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003203 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003204 }
3205
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003206 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003207 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3208 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003209 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003210 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003211
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003212 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003213 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003214 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003215 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003216
3217 case CXCursor_TemplateRef: {
3218 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3219 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3220 }
3221
Douglas Gregor69319002010-08-31 23:48:11 +00003222 case CXCursor_NamespaceRef: {
3223 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3224 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3225 }
3226
Douglas Gregora67e03f2010-09-09 21:42:20 +00003227 case CXCursor_MemberRef: {
3228 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3229 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3230 }
3231
Ted Kremenek3064ef92010-08-27 21:34:58 +00003232 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003233 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3234 if (!BaseSpec)
3235 return clang_getNullLocation();
3236
3237 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3238 return cxloc::translateSourceLocation(getCursorContext(C),
3239 TSInfo->getTypeLoc().getBeginLoc());
3240
3241 return cxloc::translateSourceLocation(getCursorContext(C),
3242 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003243 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003244
Douglas Gregor36897b02010-09-10 00:22:18 +00003245 case CXCursor_LabelRef: {
3246 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3247 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3248 }
3249
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003250 case CXCursor_OverloadedDeclRef:
3251 return cxloc::translateSourceLocation(getCursorContext(C),
3252 getCursorOverloadedDeclRef(C).second);
3253
Douglas Gregorf46034a2010-01-18 23:41:10 +00003254 default:
3255 // FIXME: Need a way to enumerate all non-reference cases.
3256 llvm_unreachable("Missed a reference kind");
3257 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003258 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003259
3260 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003261 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003262 getLocationFromExpr(getCursorExpr(C)));
3263
Douglas Gregor36897b02010-09-10 00:22:18 +00003264 if (clang_isStatement(C.kind))
3265 return cxloc::translateSourceLocation(getCursorContext(C),
3266 getCursorStmt(C)->getLocStart());
3267
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003268 if (C.kind == CXCursor_PreprocessingDirective) {
3269 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3270 return cxloc::translateSourceLocation(getCursorContext(C), L);
3271 }
Douglas Gregor48072312010-03-18 15:23:44 +00003272
3273 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003274 SourceLocation L
3275 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003276 return cxloc::translateSourceLocation(getCursorContext(C), L);
3277 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003278
3279 if (C.kind == CXCursor_MacroDefinition) {
3280 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3281 return cxloc::translateSourceLocation(getCursorContext(C), L);
3282 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003283
3284 if (C.kind == CXCursor_InclusionDirective) {
3285 SourceLocation L
3286 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3287 return cxloc::translateSourceLocation(getCursorContext(C), L);
3288 }
3289
Ted Kremenek9a700d22010-05-12 06:16:13 +00003290 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003291 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003292
Douglas Gregorf46034a2010-01-18 23:41:10 +00003293 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003294 SourceLocation Loc = D->getLocation();
3295 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3296 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003297 // FIXME: Multiple variables declared in a single declaration
3298 // currently lack the information needed to correctly determine their
3299 // ranges when accounting for the type-specifier. We use context
3300 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3301 // and if so, whether it is the first decl.
3302 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3303 if (!cxcursor::isFirstInDeclGroup(C))
3304 Loc = VD->getLocation();
3305 }
3306
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003307 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003308}
Douglas Gregora7bde202010-01-19 00:34:46 +00003309
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003310} // end extern "C"
3311
3312static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003313 if (clang_isReference(C.kind)) {
3314 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003315 case CXCursor_ObjCSuperClassRef:
3316 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003317
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003318 case CXCursor_ObjCProtocolRef:
3319 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003320
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003321 case CXCursor_ObjCClassRef:
3322 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003323
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003324 case CXCursor_TypeRef:
3325 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003326
3327 case CXCursor_TemplateRef:
3328 return getCursorTemplateRef(C).second;
3329
Douglas Gregor69319002010-08-31 23:48:11 +00003330 case CXCursor_NamespaceRef:
3331 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003332
3333 case CXCursor_MemberRef:
3334 return getCursorMemberRef(C).second;
3335
Ted Kremenek3064ef92010-08-27 21:34:58 +00003336 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003337 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003338
Douglas Gregor36897b02010-09-10 00:22:18 +00003339 case CXCursor_LabelRef:
3340 return getCursorLabelRef(C).second;
3341
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003342 case CXCursor_OverloadedDeclRef:
3343 return getCursorOverloadedDeclRef(C).second;
3344
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003345 default:
3346 // FIXME: Need a way to enumerate all non-reference cases.
3347 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003348 }
3349 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003350
3351 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003352 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003353
3354 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003355 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003357 if (C.kind == CXCursor_PreprocessingDirective)
3358 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003359
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003360 if (C.kind == CXCursor_MacroInstantiation)
3361 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003362
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003363 if (C.kind == CXCursor_MacroDefinition)
3364 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003365
3366 if (C.kind == CXCursor_InclusionDirective)
3367 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3368
Ted Kremenek007a7c92010-11-01 23:26:51 +00003369 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3370 Decl *D = cxcursor::getCursorDecl(C);
3371 SourceRange R = D->getSourceRange();
3372 // FIXME: Multiple variables declared in a single declaration
3373 // currently lack the information needed to correctly determine their
3374 // ranges when accounting for the type-specifier. We use context
3375 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3376 // and if so, whether it is the first decl.
3377 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3378 if (!cxcursor::isFirstInDeclGroup(C))
3379 R.setBegin(VD->getLocation());
3380 }
3381 return R;
3382 }
Douglas Gregor66537982010-11-17 17:14:07 +00003383 return SourceRange();
3384}
3385
3386/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3387/// the decl-specifier-seq for declarations.
3388static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3389 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3390 Decl *D = cxcursor::getCursorDecl(C);
3391 SourceRange R = D->getSourceRange();
3392
3393 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3394 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3395 TypeLoc TL = TI->getTypeLoc();
3396 SourceLocation TLoc = TL.getSourceRange().getBegin();
3397 if (TLoc.isValid() && R.getBegin().isValid() &&
3398 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3399 R.setBegin(TLoc);
3400 }
3401
3402 // FIXME: Multiple variables declared in a single declaration
3403 // currently lack the information needed to correctly determine their
3404 // ranges when accounting for the type-specifier. We use context
3405 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3406 // and if so, whether it is the first decl.
3407 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3408 if (!cxcursor::isFirstInDeclGroup(C))
3409 R.setBegin(VD->getLocation());
3410 }
3411 }
3412
3413 return R;
3414 }
3415
3416 return getRawCursorExtent(C);
3417}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003418
3419extern "C" {
3420
3421CXSourceRange clang_getCursorExtent(CXCursor C) {
3422 SourceRange R = getRawCursorExtent(C);
3423 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003424 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003425
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003426 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003427}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003428
3429CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003430 if (clang_isInvalid(C.kind))
3431 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003432
Ted Kremeneka60ed472010-11-16 08:15:36 +00003433 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003434 if (clang_isDeclaration(C.kind)) {
3435 Decl *D = getCursorDecl(C);
3436 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003437 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003438 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003439 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003440 if (ObjCForwardProtocolDecl *Protocols
3441 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003442 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003443 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3444 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3445 return MakeCXCursor(Property, tu);
3446
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003447 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003448 }
3449
Douglas Gregor97b98722010-01-19 23:20:36 +00003450 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003451 Expr *E = getCursorExpr(C);
3452 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003453 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003454 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003455
3456 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003457 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003458
Douglas Gregor97b98722010-01-19 23:20:36 +00003459 return clang_getNullCursor();
3460 }
3461
Douglas Gregor36897b02010-09-10 00:22:18 +00003462 if (clang_isStatement(C.kind)) {
3463 Stmt *S = getCursorStmt(C);
3464 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003465 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003466
3467 return clang_getNullCursor();
3468 }
3469
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003470 if (C.kind == CXCursor_MacroInstantiation) {
3471 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003472 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003473 }
3474
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003475 if (!clang_isReference(C.kind))
3476 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003477
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003478 switch (C.kind) {
3479 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003480 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003481
3482 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003483 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003484
3485 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003486 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003487
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003488 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003489 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003490
3491 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003492 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003493
Douglas Gregor69319002010-08-31 23:48:11 +00003494 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003495 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003496
Douglas Gregora67e03f2010-09-09 21:42:20 +00003497 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003498 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003499
Ted Kremenek3064ef92010-08-27 21:34:58 +00003500 case CXCursor_CXXBaseSpecifier: {
3501 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3502 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003503 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003504 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003505
Douglas Gregor36897b02010-09-10 00:22:18 +00003506 case CXCursor_LabelRef:
3507 // FIXME: We end up faking the "parent" declaration here because we
3508 // don't want to make CXCursor larger.
3509 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003510 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3511 .getTranslationUnitDecl(),
3512 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003513
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003514 case CXCursor_OverloadedDeclRef:
3515 return C;
3516
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003517 default:
3518 // We would prefer to enumerate all non-reference cursor kinds here.
3519 llvm_unreachable("Unhandled reference cursor kind");
3520 break;
3521 }
3522 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003523
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003524 return clang_getNullCursor();
3525}
3526
Douglas Gregorb6998662010-01-19 19:34:47 +00003527CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003528 if (clang_isInvalid(C.kind))
3529 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003530
Ted Kremeneka60ed472010-11-16 08:15:36 +00003531 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003532
Douglas Gregorb6998662010-01-19 19:34:47 +00003533 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003534 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003535 C = clang_getCursorReferenced(C);
3536 WasReference = true;
3537 }
3538
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003539 if (C.kind == CXCursor_MacroInstantiation)
3540 return clang_getCursorReferenced(C);
3541
Douglas Gregorb6998662010-01-19 19:34:47 +00003542 if (!clang_isDeclaration(C.kind))
3543 return clang_getNullCursor();
3544
3545 Decl *D = getCursorDecl(C);
3546 if (!D)
3547 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003548
Douglas Gregorb6998662010-01-19 19:34:47 +00003549 switch (D->getKind()) {
3550 // Declaration kinds that don't really separate the notions of
3551 // declaration and definition.
3552 case Decl::Namespace:
3553 case Decl::Typedef:
3554 case Decl::TemplateTypeParm:
3555 case Decl::EnumConstant:
3556 case Decl::Field:
3557 case Decl::ObjCIvar:
3558 case Decl::ObjCAtDefsField:
3559 case Decl::ImplicitParam:
3560 case Decl::ParmVar:
3561 case Decl::NonTypeTemplateParm:
3562 case Decl::TemplateTemplateParm:
3563 case Decl::ObjCCategoryImpl:
3564 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003565 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003566 case Decl::LinkageSpec:
3567 case Decl::ObjCPropertyImpl:
3568 case Decl::FileScopeAsm:
3569 case Decl::StaticAssert:
3570 case Decl::Block:
3571 return C;
3572
3573 // Declaration kinds that don't make any sense here, but are
3574 // nonetheless harmless.
3575 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003576 break;
3577
3578 // Declaration kinds for which the definition is not resolvable.
3579 case Decl::UnresolvedUsingTypename:
3580 case Decl::UnresolvedUsingValue:
3581 break;
3582
3583 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003584 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003585 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003586
3587 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003588 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003589
3590 case Decl::Enum:
3591 case Decl::Record:
3592 case Decl::CXXRecord:
3593 case Decl::ClassTemplateSpecialization:
3594 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003595 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003596 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003597 return clang_getNullCursor();
3598
3599 case Decl::Function:
3600 case Decl::CXXMethod:
3601 case Decl::CXXConstructor:
3602 case Decl::CXXDestructor:
3603 case Decl::CXXConversion: {
3604 const FunctionDecl *Def = 0;
3605 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003606 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003607 return clang_getNullCursor();
3608 }
3609
3610 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003611 // Ask the variable if it has a definition.
3612 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003613 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003614 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003615 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003616
Douglas Gregorb6998662010-01-19 19:34:47 +00003617 case Decl::FunctionTemplate: {
3618 const FunctionDecl *Def = 0;
3619 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003620 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003621 return clang_getNullCursor();
3622 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003623
Douglas Gregorb6998662010-01-19 19:34:47 +00003624 case Decl::ClassTemplate: {
3625 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003626 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003627 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003628 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003629 return clang_getNullCursor();
3630 }
3631
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003632 case Decl::Using:
3633 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003634 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003635
3636 case Decl::UsingShadow:
3637 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003638 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003639 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003640
3641 case Decl::ObjCMethod: {
3642 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3643 if (Method->isThisDeclarationADefinition())
3644 return C;
3645
3646 // Dig out the method definition in the associated
3647 // @implementation, if we have it.
3648 // FIXME: The ASTs should make finding the definition easier.
3649 if (ObjCInterfaceDecl *Class
3650 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3651 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3652 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3653 Method->isInstanceMethod()))
3654 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003655 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003656
3657 return clang_getNullCursor();
3658 }
3659
3660 case Decl::ObjCCategory:
3661 if (ObjCCategoryImplDecl *Impl
3662 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003663 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003664 return clang_getNullCursor();
3665
3666 case Decl::ObjCProtocol:
3667 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3668 return C;
3669 return clang_getNullCursor();
3670
3671 case Decl::ObjCInterface:
3672 // There are two notions of a "definition" for an Objective-C
3673 // class: the interface and its implementation. When we resolved a
3674 // reference to an Objective-C class, produce the @interface as
3675 // the definition; when we were provided with the interface,
3676 // produce the @implementation as the definition.
3677 if (WasReference) {
3678 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3679 return C;
3680 } else if (ObjCImplementationDecl *Impl
3681 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003682 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003683 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003684
Douglas Gregorb6998662010-01-19 19:34:47 +00003685 case Decl::ObjCProperty:
3686 // FIXME: We don't really know where to find the
3687 // ObjCPropertyImplDecls that implement this property.
3688 return clang_getNullCursor();
3689
3690 case Decl::ObjCCompatibleAlias:
3691 if (ObjCInterfaceDecl *Class
3692 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3693 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003694 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003695
Douglas Gregorb6998662010-01-19 19:34:47 +00003696 return clang_getNullCursor();
3697
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003698 case Decl::ObjCForwardProtocol:
3699 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003700 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003701
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003702 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003703 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003704 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003705
3706 case Decl::Friend:
3707 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003708 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003709 return clang_getNullCursor();
3710
3711 case Decl::FriendTemplate:
3712 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003713 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003714 return clang_getNullCursor();
3715 }
3716
3717 return clang_getNullCursor();
3718}
3719
3720unsigned clang_isCursorDefinition(CXCursor C) {
3721 if (!clang_isDeclaration(C.kind))
3722 return 0;
3723
3724 return clang_getCursorDefinition(C) == C;
3725}
3726
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003727unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003728 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003729 return 0;
3730
3731 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3732 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3733 return E->getNumDecls();
3734
3735 if (OverloadedTemplateStorage *S
3736 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3737 return S->size();
3738
3739 Decl *D = Storage.get<Decl*>();
3740 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003741 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003742 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3743 return Classes->size();
3744 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3745 return Protocols->protocol_size();
3746
3747 return 0;
3748}
3749
3750CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003751 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003752 return clang_getNullCursor();
3753
3754 if (index >= clang_getNumOverloadedDecls(cursor))
3755 return clang_getNullCursor();
3756
Ted Kremeneka60ed472010-11-16 08:15:36 +00003757 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003758 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3759 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003760 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003761
3762 if (OverloadedTemplateStorage *S
3763 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003764 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003765
3766 Decl *D = Storage.get<Decl*>();
3767 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3768 // FIXME: This is, unfortunately, linear time.
3769 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3770 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003771 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003772 }
3773
3774 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003775 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003776
3777 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003778 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003779
3780 return clang_getNullCursor();
3781}
3782
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003783void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003784 const char **startBuf,
3785 const char **endBuf,
3786 unsigned *startLine,
3787 unsigned *startColumn,
3788 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003789 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003790 assert(getCursorDecl(C) && "CXCursor has null decl");
3791 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003792 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3793 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003794
Steve Naroff4ade6d62009-09-23 17:52:52 +00003795 SourceManager &SM = FD->getASTContext().getSourceManager();
3796 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3797 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3798 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3799 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3800 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3801 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3802}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003803
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003804void clang_enableStackTraces(void) {
3805 llvm::sys::PrintStackTraceOnErrorSignal();
3806}
3807
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003808void clang_executeOnThread(void (*fn)(void*), void *user_data,
3809 unsigned stack_size) {
3810 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3811}
3812
Ted Kremenekfb480492010-01-13 21:46:36 +00003813} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003814
Ted Kremenekfb480492010-01-13 21:46:36 +00003815//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003816// Token-based Operations.
3817//===----------------------------------------------------------------------===//
3818
3819/* CXToken layout:
3820 * int_data[0]: a CXTokenKind
3821 * int_data[1]: starting token location
3822 * int_data[2]: token length
3823 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003824 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003825 * otherwise unused.
3826 */
3827extern "C" {
3828
3829CXTokenKind clang_getTokenKind(CXToken CXTok) {
3830 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3831}
3832
3833CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3834 switch (clang_getTokenKind(CXTok)) {
3835 case CXToken_Identifier:
3836 case CXToken_Keyword:
3837 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003838 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3839 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003840
3841 case CXToken_Literal: {
3842 // We have stashed the starting pointer in the ptr_data field. Use it.
3843 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003844 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003845 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003847 case CXToken_Punctuation:
3848 case CXToken_Comment:
3849 break;
3850 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851
3852 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003853 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003854 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003856 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003857
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003858 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3859 std::pair<FileID, unsigned> LocInfo
3860 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003861 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003862 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003863 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3864 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003865 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003866
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003867 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003868}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003871 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003872 if (!CXXUnit)
3873 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003874
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003875 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3876 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3877}
3878
3879CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003880 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003881 if (!CXXUnit)
3882 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003883
3884 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003885 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3886}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003888void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3889 CXToken **Tokens, unsigned *NumTokens) {
3890 if (Tokens)
3891 *Tokens = 0;
3892 if (NumTokens)
3893 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003896 if (!CXXUnit || !Tokens || !NumTokens)
3897 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003898
Douglas Gregorbdf60622010-03-05 21:16:25 +00003899 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3900
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003901 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003902 if (R.isInvalid())
3903 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003904
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003905 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3906 std::pair<FileID, unsigned> BeginLocInfo
3907 = SourceMgr.getDecomposedLoc(R.getBegin());
3908 std::pair<FileID, unsigned> EndLocInfo
3909 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003910
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003911 // Cannot tokenize across files.
3912 if (BeginLocInfo.first != EndLocInfo.first)
3913 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003914
3915 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003916 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003917 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003918 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003919 if (Invalid)
3920 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003921
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003922 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3923 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003924 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003925 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003926
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003927 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003928 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003929 llvm::SmallVector<CXToken, 32> CXTokens;
3930 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003931 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003932 do {
3933 // Lex the next token
3934 Lex.LexFromRawLexer(Tok);
3935 if (Tok.is(tok::eof))
3936 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003937
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003938 // Initialize the CXToken.
3939 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003940
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003941 // - Common fields
3942 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3943 CXTok.int_data[2] = Tok.getLength();
3944 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003945
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003946 // - Kind-specific fields
3947 if (Tok.isLiteral()) {
3948 CXTok.int_data[0] = CXToken_Literal;
3949 CXTok.ptr_data = (void *)Tok.getLiteralData();
3950 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003951 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003952 std::pair<FileID, unsigned> LocInfo
3953 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003954 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003955 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003956 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3957 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003958 return;
3959
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003960 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003961 IdentifierInfo *II
3962 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003963
David Chisnall096428b2010-10-13 21:44:48 +00003964 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003965 CXTok.int_data[0] = CXToken_Keyword;
3966 }
3967 else {
3968 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3969 CXToken_Identifier
3970 : CXToken_Keyword;
3971 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003972 CXTok.ptr_data = II;
3973 } else if (Tok.is(tok::comment)) {
3974 CXTok.int_data[0] = CXToken_Comment;
3975 CXTok.ptr_data = 0;
3976 } else {
3977 CXTok.int_data[0] = CXToken_Punctuation;
3978 CXTok.ptr_data = 0;
3979 }
3980 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003981 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003982 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003983
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003984 if (CXTokens.empty())
3985 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003986
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003987 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3988 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3989 *NumTokens = CXTokens.size();
3990}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003991
Ted Kremenek6db61092010-05-05 00:55:15 +00003992void clang_disposeTokens(CXTranslationUnit TU,
3993 CXToken *Tokens, unsigned NumTokens) {
3994 free(Tokens);
3995}
3996
3997} // end: extern "C"
3998
3999//===----------------------------------------------------------------------===//
4000// Token annotation APIs.
4001//===----------------------------------------------------------------------===//
4002
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004003typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4005 CXCursor parent,
4006 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004007namespace {
4008class AnnotateTokensWorker {
4009 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004010 CXToken *Tokens;
4011 CXCursor *Cursors;
4012 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004013 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004014 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004015 CursorVisitor AnnotateVis;
4016 SourceManager &SrcMgr;
4017
4018 bool MoreTokens() const { return TokIdx < NumTokens; }
4019 unsigned NextToken() const { return TokIdx; }
4020 void AdvanceToken() { ++TokIdx; }
4021 SourceLocation GetTokenLoc(unsigned tokI) {
4022 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4023 }
4024
Ted Kremenek6db61092010-05-05 00:55:15 +00004025public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004026 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004027 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004028 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004029 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004030 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004031 AnnotateVis(tu,
4032 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004033 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004034 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004035
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004036 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004037 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004038 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004039 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004040 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004041 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004042};
4043}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004044
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004045void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4046 // Walk the AST within the region of interest, annotating tokens
4047 // along the way.
4048 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004049
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004050 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4051 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004052 if (Pos != Annotated.end() &&
4053 (clang_isInvalid(Cursors[I].kind) ||
4054 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004055 Cursors[I] = Pos->second;
4056 }
4057
4058 // Finish up annotating any tokens left.
4059 if (!MoreTokens())
4060 return;
4061
4062 const CXCursor &C = clang_getNullCursor();
4063 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4064 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4065 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004066 }
4067}
4068
Ted Kremenek6db61092010-05-05 00:55:15 +00004069enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004070AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004071 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004072 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004073 if (cursorRange.isInvalid())
4074 return CXChildVisit_Recurse;
4075
Douglas Gregor4419b672010-10-21 06:10:04 +00004076 if (clang_isPreprocessing(cursor.kind)) {
4077 // For macro instantiations, just note where the beginning of the macro
4078 // instantiation occurs.
4079 if (cursor.kind == CXCursor_MacroInstantiation) {
4080 Annotated[Loc.int_data] = cursor;
4081 return CXChildVisit_Recurse;
4082 }
4083
Douglas Gregor4419b672010-10-21 06:10:04 +00004084 // Items in the preprocessing record are kept separate from items in
4085 // declarations, so we keep a separate token index.
4086 unsigned SavedTokIdx = TokIdx;
4087 TokIdx = PreprocessingTokIdx;
4088
4089 // Skip tokens up until we catch up to the beginning of the preprocessing
4090 // entry.
4091 while (MoreTokens()) {
4092 const unsigned I = NextToken();
4093 SourceLocation TokLoc = GetTokenLoc(I);
4094 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4095 case RangeBefore:
4096 AdvanceToken();
4097 continue;
4098 case RangeAfter:
4099 case RangeOverlap:
4100 break;
4101 }
4102 break;
4103 }
4104
4105 // Look at all of the tokens within this range.
4106 while (MoreTokens()) {
4107 const unsigned I = NextToken();
4108 SourceLocation TokLoc = GetTokenLoc(I);
4109 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4110 case RangeBefore:
4111 assert(0 && "Infeasible");
4112 case RangeAfter:
4113 break;
4114 case RangeOverlap:
4115 Cursors[I] = cursor;
4116 AdvanceToken();
4117 continue;
4118 }
4119 break;
4120 }
4121
4122 // Save the preprocessing token index; restore the non-preprocessing
4123 // token index.
4124 PreprocessingTokIdx = TokIdx;
4125 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004126 return CXChildVisit_Recurse;
4127 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004128
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004129 if (cursorRange.isInvalid())
4130 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004131
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004132 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4133
Ted Kremeneka333c662010-05-12 05:29:33 +00004134 // Adjust the annotated range based specific declarations.
4135 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4136 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004137 Decl *D = cxcursor::getCursorDecl(cursor);
4138 // Don't visit synthesized ObjC methods, since they have no syntatic
4139 // representation in the source.
4140 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4141 if (MD->isSynthesized())
4142 return CXChildVisit_Continue;
4143 }
4144 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004145 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4146 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004147 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004148 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004149 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004150 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004151 }
4152 }
4153 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004154
Ted Kremenek3f404602010-08-14 01:14:06 +00004155 // If the location of the cursor occurs within a macro instantiation, record
4156 // the spelling location of the cursor in our annotation map. We can then
4157 // paper over the token labelings during a post-processing step to try and
4158 // get cursor mappings for tokens that are the *arguments* of a macro
4159 // instantiation.
4160 if (L.isMacroID()) {
4161 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4162 // Only invalidate the old annotation if it isn't part of a preprocessing
4163 // directive. Here we assume that the default construction of CXCursor
4164 // results in CXCursor.kind being an initialized value (i.e., 0). If
4165 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004166
Ted Kremenek3f404602010-08-14 01:14:06 +00004167 CXCursor &oldC = Annotated[rawEncoding];
4168 if (!clang_isPreprocessing(oldC.kind))
4169 oldC = cursor;
4170 }
4171
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004172 const enum CXCursorKind K = clang_getCursorKind(parent);
4173 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004174 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4175 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004176
4177 while (MoreTokens()) {
4178 const unsigned I = NextToken();
4179 SourceLocation TokLoc = GetTokenLoc(I);
4180 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4181 case RangeBefore:
4182 Cursors[I] = updateC;
4183 AdvanceToken();
4184 continue;
4185 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004186 case RangeOverlap:
4187 break;
4188 }
4189 break;
4190 }
4191
4192 // Visit children to get their cursor information.
4193 const unsigned BeforeChildren = NextToken();
4194 VisitChildren(cursor);
4195 const unsigned AfterChildren = NextToken();
4196
4197 // Adjust 'Last' to the last token within the extent of the cursor.
4198 while (MoreTokens()) {
4199 const unsigned I = NextToken();
4200 SourceLocation TokLoc = GetTokenLoc(I);
4201 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4202 case RangeBefore:
4203 assert(0 && "Infeasible");
4204 case RangeAfter:
4205 break;
4206 case RangeOverlap:
4207 Cursors[I] = updateC;
4208 AdvanceToken();
4209 continue;
4210 }
4211 break;
4212 }
4213 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004214
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004215 // Scan the tokens that are at the beginning of the cursor, but are not
4216 // capture by the child cursors.
4217
4218 // For AST elements within macros, rely on a post-annotate pass to
4219 // to correctly annotate the tokens with cursors. Otherwise we can
4220 // get confusing results of having tokens that map to cursors that really
4221 // are expanded by an instantiation.
4222 if (L.isMacroID())
4223 cursor = clang_getNullCursor();
4224
4225 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4226 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4227 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004228
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229 Cursors[I] = cursor;
4230 }
4231 // Scan the tokens that are at the end of the cursor, but are not captured
4232 // but the child cursors.
4233 for (unsigned I = AfterChildren; I != Last; ++I)
4234 Cursors[I] = cursor;
4235
4236 TokIdx = Last;
4237 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004238}
4239
Ted Kremenek6db61092010-05-05 00:55:15 +00004240static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4241 CXCursor parent,
4242 CXClientData client_data) {
4243 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4244}
4245
Ted Kremenekab979612010-11-11 08:05:23 +00004246// This gets run a separate thread to avoid stack blowout.
4247static void runAnnotateTokensWorker(void *UserData) {
4248 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4249}
4250
Ted Kremenek6db61092010-05-05 00:55:15 +00004251extern "C" {
4252
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004253void clang_annotateTokens(CXTranslationUnit TU,
4254 CXToken *Tokens, unsigned NumTokens,
4255 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004256
4257 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004258 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004259
Douglas Gregor4419b672010-10-21 06:10:04 +00004260 // Any token we don't specifically annotate will have a NULL cursor.
4261 CXCursor C = clang_getNullCursor();
4262 for (unsigned I = 0; I != NumTokens; ++I)
4263 Cursors[I] = C;
4264
Ted Kremeneka60ed472010-11-16 08:15:36 +00004265 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004266 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004267 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004268
Douglas Gregorbdf60622010-03-05 21:16:25 +00004269 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004270
Douglas Gregor0396f462010-03-19 05:22:59 +00004271 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004272 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004273 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4274 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004275 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4276 clang_getTokenLocation(TU,
4277 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004278
Douglas Gregor0396f462010-03-19 05:22:59 +00004279 // A mapping from the source locations found when re-lexing or traversing the
4280 // region of interest to the corresponding cursors.
4281 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004282
4283 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004284 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004285 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4286 std::pair<FileID, unsigned> BeginLocInfo
4287 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4288 std::pair<FileID, unsigned> EndLocInfo
4289 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004290
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004291 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004292 bool Invalid = false;
4293 if (BeginLocInfo.first == EndLocInfo.first &&
4294 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4295 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004296 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4297 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004298 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004299 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004300 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004301
4302 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004303 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004304 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004305 Token Tok;
4306 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004307
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004308 reprocess:
4309 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4310 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004311 // don't see it while preprocessing these tokens later, but keep track
4312 // of all of the token locations inside this preprocessing directive so
4313 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004314 //
4315 // FIXME: Some simple tests here could identify macro definitions and
4316 // #undefs, to provide specific cursor kinds for those.
4317 std::vector<SourceLocation> Locations;
4318 do {
4319 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004320 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004321 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004322
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004323 using namespace cxcursor;
4324 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004325 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4326 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004327 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004328 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4329 Annotated[Locations[I].getRawEncoding()] = Cursor;
4330 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004331
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004332 if (Tok.isAtStartOfLine())
4333 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004334
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004335 continue;
4336 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004337
Douglas Gregor48072312010-03-18 15:23:44 +00004338 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004339 break;
4340 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004341 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004342
Douglas Gregor0396f462010-03-19 05:22:59 +00004343 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004344 // a specific cursor.
4345 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004346 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004347
4348 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004349 // FIXME: We use a ridiculous stack size here because the data-recursion
4350 // algorithm uses a large stack frame than the non-data recursive version,
4351 // and AnnotationTokensWorker currently transforms the data-recursion
4352 // algorithm back into a traditional recursion by explicitly calling
4353 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004354 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004355 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4356 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004357 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4358 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004359}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004360} // end: extern "C"
4361
4362//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004363// Operations for querying linkage of a cursor.
4364//===----------------------------------------------------------------------===//
4365
4366extern "C" {
4367CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004368 if (!clang_isDeclaration(cursor.kind))
4369 return CXLinkage_Invalid;
4370
Ted Kremenek16b42592010-03-03 06:36:57 +00004371 Decl *D = cxcursor::getCursorDecl(cursor);
4372 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4373 switch (ND->getLinkage()) {
4374 case NoLinkage: return CXLinkage_NoLinkage;
4375 case InternalLinkage: return CXLinkage_Internal;
4376 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4377 case ExternalLinkage: return CXLinkage_External;
4378 };
4379
4380 return CXLinkage_Invalid;
4381}
4382} // end: extern "C"
4383
4384//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004385// Operations for querying language of a cursor.
4386//===----------------------------------------------------------------------===//
4387
4388static CXLanguageKind getDeclLanguage(const Decl *D) {
4389 switch (D->getKind()) {
4390 default:
4391 break;
4392 case Decl::ImplicitParam:
4393 case Decl::ObjCAtDefsField:
4394 case Decl::ObjCCategory:
4395 case Decl::ObjCCategoryImpl:
4396 case Decl::ObjCClass:
4397 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004398 case Decl::ObjCForwardProtocol:
4399 case Decl::ObjCImplementation:
4400 case Decl::ObjCInterface:
4401 case Decl::ObjCIvar:
4402 case Decl::ObjCMethod:
4403 case Decl::ObjCProperty:
4404 case Decl::ObjCPropertyImpl:
4405 case Decl::ObjCProtocol:
4406 return CXLanguage_ObjC;
4407 case Decl::CXXConstructor:
4408 case Decl::CXXConversion:
4409 case Decl::CXXDestructor:
4410 case Decl::CXXMethod:
4411 case Decl::CXXRecord:
4412 case Decl::ClassTemplate:
4413 case Decl::ClassTemplatePartialSpecialization:
4414 case Decl::ClassTemplateSpecialization:
4415 case Decl::Friend:
4416 case Decl::FriendTemplate:
4417 case Decl::FunctionTemplate:
4418 case Decl::LinkageSpec:
4419 case Decl::Namespace:
4420 case Decl::NamespaceAlias:
4421 case Decl::NonTypeTemplateParm:
4422 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004423 case Decl::TemplateTemplateParm:
4424 case Decl::TemplateTypeParm:
4425 case Decl::UnresolvedUsingTypename:
4426 case Decl::UnresolvedUsingValue:
4427 case Decl::Using:
4428 case Decl::UsingDirective:
4429 case Decl::UsingShadow:
4430 return CXLanguage_CPlusPlus;
4431 }
4432
4433 return CXLanguage_C;
4434}
4435
4436extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004437
4438enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4439 if (clang_isDeclaration(cursor.kind))
4440 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4441 if (D->hasAttr<UnavailableAttr>() ||
4442 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4443 return CXAvailability_Available;
4444
4445 if (D->hasAttr<DeprecatedAttr>())
4446 return CXAvailability_Deprecated;
4447 }
4448
4449 return CXAvailability_Available;
4450}
4451
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004452CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4453 if (clang_isDeclaration(cursor.kind))
4454 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4455
4456 return CXLanguage_Invalid;
4457}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004458
4459CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4460 if (clang_isDeclaration(cursor.kind)) {
4461 if (Decl *D = getCursorDecl(cursor)) {
4462 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004463 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004464 }
4465 }
4466
4467 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4468 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004469 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004470 }
4471
4472 return clang_getNullCursor();
4473}
4474
4475CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4476 if (clang_isDeclaration(cursor.kind)) {
4477 if (Decl *D = getCursorDecl(cursor)) {
4478 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004479 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004480 }
4481 }
4482
4483 // FIXME: Note that we can't easily compute the lexical context of a
4484 // statement or expression, so we return nothing.
4485 return clang_getNullCursor();
4486}
4487
Douglas Gregor9f592342010-10-01 20:25:15 +00004488static void CollectOverriddenMethods(DeclContext *Ctx,
4489 ObjCMethodDecl *Method,
4490 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4491 if (!Ctx)
4492 return;
4493
4494 // If we have a class or category implementation, jump straight to the
4495 // interface.
4496 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4497 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4498
4499 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4500 if (!Container)
4501 return;
4502
4503 // Check whether we have a matching method at this level.
4504 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4505 Method->isInstanceMethod()))
4506 if (Method != Overridden) {
4507 // We found an override at this level; there is no need to look
4508 // into other protocols or categories.
4509 Methods.push_back(Overridden);
4510 return;
4511 }
4512
4513 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4514 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4515 PEnd = Protocol->protocol_end();
4516 P != PEnd; ++P)
4517 CollectOverriddenMethods(*P, Method, Methods);
4518 }
4519
4520 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4521 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4522 PEnd = Category->protocol_end();
4523 P != PEnd; ++P)
4524 CollectOverriddenMethods(*P, Method, Methods);
4525 }
4526
4527 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4528 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4529 PEnd = Interface->protocol_end();
4530 P != PEnd; ++P)
4531 CollectOverriddenMethods(*P, Method, Methods);
4532
4533 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4534 Category; Category = Category->getNextClassCategory())
4535 CollectOverriddenMethods(Category, Method, Methods);
4536
4537 // We only look into the superclass if we haven't found anything yet.
4538 if (Methods.empty())
4539 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4540 return CollectOverriddenMethods(Super, Method, Methods);
4541 }
4542}
4543
4544void clang_getOverriddenCursors(CXCursor cursor,
4545 CXCursor **overridden,
4546 unsigned *num_overridden) {
4547 if (overridden)
4548 *overridden = 0;
4549 if (num_overridden)
4550 *num_overridden = 0;
4551 if (!overridden || !num_overridden)
4552 return;
4553
4554 if (!clang_isDeclaration(cursor.kind))
4555 return;
4556
4557 Decl *D = getCursorDecl(cursor);
4558 if (!D)
4559 return;
4560
4561 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004562 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004563 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4564 *num_overridden = CXXMethod->size_overridden_methods();
4565 if (!*num_overridden)
4566 return;
4567
4568 *overridden = new CXCursor [*num_overridden];
4569 unsigned I = 0;
4570 for (CXXMethodDecl::method_iterator
4571 M = CXXMethod->begin_overridden_methods(),
4572 MEnd = CXXMethod->end_overridden_methods();
4573 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004574 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004575 return;
4576 }
4577
4578 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4579 if (!Method)
4580 return;
4581
4582 // Handle Objective-C methods.
4583 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4584 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4585
4586 if (Methods.empty())
4587 return;
4588
4589 *num_overridden = Methods.size();
4590 *overridden = new CXCursor [Methods.size()];
4591 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004592 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004593}
4594
4595void clang_disposeOverriddenCursors(CXCursor *overridden) {
4596 delete [] overridden;
4597}
4598
Douglas Gregorecdcb882010-10-20 22:00:55 +00004599CXFile clang_getIncludedFile(CXCursor cursor) {
4600 if (cursor.kind != CXCursor_InclusionDirective)
4601 return 0;
4602
4603 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4604 return (void *)ID->getFile();
4605}
4606
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004607} // end: extern "C"
4608
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004609
4610//===----------------------------------------------------------------------===//
4611// C++ AST instrospection.
4612//===----------------------------------------------------------------------===//
4613
4614extern "C" {
4615unsigned clang_CXXMethod_isStatic(CXCursor C) {
4616 if (!clang_isDeclaration(C.kind))
4617 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004618
4619 CXXMethodDecl *Method = 0;
4620 Decl *D = cxcursor::getCursorDecl(C);
4621 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4622 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4623 else
4624 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4625 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004626}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004627
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004628} // end: extern "C"
4629
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004630//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004631// Attribute introspection.
4632//===----------------------------------------------------------------------===//
4633
4634extern "C" {
4635CXType clang_getIBOutletCollectionType(CXCursor C) {
4636 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004637 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004638
4639 IBOutletCollectionAttr *A =
4640 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4641
Ted Kremeneka60ed472010-11-16 08:15:36 +00004642 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004643}
4644} // end: extern "C"
4645
4646//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004647// Misc. utility functions.
4648//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004649
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004650/// Default to using an 8 MB stack size on "safety" threads.
4651static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004652
4653namespace clang {
4654
4655bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004656 void (*Fn)(void*), void *UserData,
4657 unsigned Size) {
4658 if (!Size)
4659 Size = GetSafetyThreadStackSize();
4660 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004661 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4662 return CRC.RunSafely(Fn, UserData);
4663}
4664
4665unsigned GetSafetyThreadStackSize() {
4666 return SafetyStackThreadSize;
4667}
4668
4669void SetSafetyThreadStackSize(unsigned Value) {
4670 SafetyStackThreadSize = Value;
4671}
4672
4673}
4674
Ted Kremenek04bb7162010-01-22 22:44:15 +00004675extern "C" {
4676
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004677CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004678 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004679}
4680
4681} // end: extern "C"