blob: c57a489d7df294e079d53e202ae19f16b06455ea [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"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000043#include "llvm/Support/Mutex.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/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,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000141 ExplicitTemplateArgsVisitKind,
142 NestedNameSpecifierVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000143 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000144 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000145protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000146 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147 CXCursor parent;
148 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
150 : parent(C), K(k) {
151 data[0] = d1;
152 data[1] = d2;
153 data[2] = d3;
154 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000155public:
156 Kind getKind() const { return K; }
157 const CXCursor &getParent() const { return parent; }
158 static bool classof(VisitorJob *VJ) { return true; }
159};
160
161typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
162
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000164class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000165 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000168 CXTranslationUnit TU;
169 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The declaration that serves at the parent of any statement or
175 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000176 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000178 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000179 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000184 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
185 // to the visitor. Declarations with a PCH level greater than this value will
186 // be suppressed.
187 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188
189 /// \brief When valid, a source range to which the cursor should restrict
190 /// its search.
191 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000193 // FIXME: Eventually remove. This part of a hack to support proper
194 // iteration over all Decls contained lexically within an ObjC container.
195 DeclContext::decl_iterator *DI_current;
196 DeclContext::decl_iterator DE_current;
197
Ted Kremenekd1ded662010-11-15 23:31:32 +0000198 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
199 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
200 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000204
205 /// \brief Determine whether this particular source range comes before, comes
206 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000208 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
210
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000211 class SetParentRAII {
212 CXCursor &Parent;
213 Decl *&StmtParent;
214 CXCursor OldParent;
215
216 public:
217 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
218 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
219 {
220 Parent = NewParent;
221 if (clang_isDeclaration(Parent.kind))
222 StmtParent = getCursorDecl(Parent);
223 }
224
225 ~SetParentRAII() {
226 Parent = OldParent;
227 if (clang_isDeclaration(Parent.kind))
228 StmtParent = getCursorDecl(Parent);
229 }
230 };
231
Steve Naroff89922f82009-08-31 00:59:03 +0000232public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000233 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
234 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000237 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
238 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000239 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
240 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 {
242 Parent.kind = CXCursor_NoDeclFound;
243 Parent.data[0] = 0;
244 Parent.data[1] = 0;
245 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000246 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000247 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000248
Ted Kremenekd1ded662010-11-15 23:31:32 +0000249 ~CursorVisitor() {
250 // Free the pre-allocated worklists for data-recursion.
251 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
252 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
253 delete *I;
254 }
255 }
256
Ted Kremeneka60ed472010-11-16 08:15:36 +0000257 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
258 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000259
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000260 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000261
262 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
263 getPreprocessedEntities();
264
Douglas Gregorb1373d02010-01-20 20:59:29 +0000265 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000266
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000268 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000269 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000270 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000271 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000273 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
274 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000276 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000277 bool VisitClassTemplatePartialSpecializationDecl(
278 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000279 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000280 bool VisitEnumConstantDecl(EnumConstantDecl *D);
281 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
282 bool VisitFunctionDecl(FunctionDecl *ND);
283 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000284 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000285 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000287 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000288 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
290 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
291 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
292 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000293 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
295 bool VisitObjCImplDecl(ObjCImplDecl *D);
296 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
297 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
299 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
300 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000301 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000302 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000303 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000304 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000305 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000306 bool VisitUsingDecl(UsingDecl *D);
307 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
308 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000309
Douglas Gregor01829d32010-08-31 14:41:23 +0000310 // Name visitor
311 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000312 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000313
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000314 // Template visitors
315 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000316 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000317 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
318
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000319 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000320 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000322 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
324 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000325 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000326 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000327 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000329 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitPointerTypeLoc(PointerTypeLoc TL);
331 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
332 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
333 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
334 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000335 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000337 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000338 // FIXME: Implement visitors here when the unimplemented TypeLocs get
339 // implemented
340 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000341 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000342 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000343
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000344 // Data-recursive visitor functions.
345 bool IsInRegionOfInterest(CXCursor C);
346 bool RunVisitorWorkList(VisitorWorkList &WL);
347 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000348 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000349};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000350
Ted Kremenekab188932010-01-05 19:32:54 +0000351} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000352
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000353static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000354static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
355
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000356
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000358 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359}
360
Douglas Gregorb1373d02010-01-20 20:59:29 +0000361/// \brief Visit the given cursor and, if requested by the visitor,
362/// its children.
363///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000364/// \param Cursor the cursor to visit.
365///
366/// \param CheckRegionOfInterest if true, then the caller already checked that
367/// this cursor is within the region of interest.
368///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369/// \returns true if the visitation should be aborted, false if it
370/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 if (clang_isInvalid(Cursor.kind))
373 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000374
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 if (clang_isDeclaration(Cursor.kind)) {
376 Decl *D = getCursorDecl(Cursor);
377 assert(D && "Invalid declaration cursor");
378 if (D->getPCHLevel() > MaxPCHLevel)
379 return false;
380
381 if (D->isImplicit())
382 return false;
383 }
384
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385 // If we have a range of interest, and this cursor doesn't intersect with it,
386 // we're done.
387 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000388 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000389 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390 return false;
391 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000392
Douglas Gregorb1373d02010-01-20 20:59:29 +0000393 switch (Visitor(Cursor, Parent, ClientData)) {
394 case CXChildVisit_Break:
395 return true;
396
397 case CXChildVisit_Continue:
398 return false;
399
400 case CXChildVisit_Recurse:
401 return VisitChildren(Cursor);
402 }
403
Douglas Gregorfd643772010-01-25 16:45:46 +0000404 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405}
406
Douglas Gregor788f5a12010-03-20 00:41:21 +0000407std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
408CursorVisitor::getPreprocessedEntities() {
409 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000410 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000411
412 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000413 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
414
415 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
416 // If we would only look at local declarations but we have a region of
417 // interest, check whether that region of interest is in the main file.
418 // If not, we should traverse all declarations.
419 // FIXME: My kingdom for a proper binary search approach to finding
420 // cursors!
421 std::pair<FileID, unsigned> Location
422 = AU->getSourceManager().getDecomposedInstantiationLoc(
423 RegionOfInterest.getBegin());
424 if (Location.first != AU->getSourceManager().getMainFileID())
425 OnlyLocalDecls = false;
426 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000427
Douglas Gregor89d99802010-11-30 06:16:57 +0000428 PreprocessingRecord::iterator StartEntity, EndEntity;
429 if (OnlyLocalDecls) {
430 StartEntity = AU->pp_entity_begin();
431 EndEntity = AU->pp_entity_end();
432 } else {
433 StartEntity = PPRec.begin();
434 EndEntity = PPRec.end();
435 }
436
Douglas Gregor788f5a12010-03-20 00:41:21 +0000437 // There is no region of interest; we have to walk everything.
438 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000439 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000440
441 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000442 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000443 std::pair<FileID, unsigned> Begin
444 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
445 std::pair<FileID, unsigned> End
446 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
447
448 // The region of interest spans files; we have to walk everything.
449 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000450 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000451
452 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000453 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000454 if (ByFileMap.empty()) {
455 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000456 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000457 std::pair<FileID, unsigned> P
458 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000459
Douglas Gregor788f5a12010-03-20 00:41:21 +0000460 ByFileMap[P.first].push_back(*E);
461 }
462 }
463
464 return std::make_pair(ByFileMap[Begin.first].begin(),
465 ByFileMap[Begin.first].end());
466}
467
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000469///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470/// \returns true if the visitation should be aborted, false if it
471/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000473 if (clang_isReference(Cursor.kind)) {
474 // By definition, references have no children.
475 return false;
476 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000477
478 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000479 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000480 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482 if (clang_isDeclaration(Cursor.kind)) {
483 Decl *D = getCursorDecl(Cursor);
484 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000485 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000487
Douglas Gregora59e3902010-01-21 23:27:09 +0000488 if (clang_isStatement(Cursor.kind))
489 return Visit(getCursorStmt(Cursor));
490 if (clang_isExpression(Cursor.kind))
491 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000492
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000494 CXTranslationUnit tu = getCursorTU(Cursor);
495 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000496 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
497 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000498 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
499 TLEnd = CXXUnit->top_level_end();
500 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000501 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000502 return true;
503 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 } else if (VisitDeclContext(
505 CXXUnit->getASTContext().getTranslationUnitDecl()))
506 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000507
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000509 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 // FIXME: Once we have the ability to deserialize a preprocessing record,
511 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000512 PreprocessingRecord::iterator E, EEnd;
513 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000514 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000515 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000516 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000517
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 continue;
519 }
520
521 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000522 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000523 return true;
524
525 continue;
526 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000527
528 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000529 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000530 return true;
531
532 continue;
533 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000534 }
535 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000536 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000537 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000538
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 return false;
541}
542
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000543bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000544 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
545 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000546
Ted Kremenek664cffd2010-07-22 11:30:19 +0000547 if (Stmt *Body = B->getBody())
548 return Visit(MakeCXCursor(Body, StmtParent, TU));
549
550 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000551}
552
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000553llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
554 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000555 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000556 if (Range.isInvalid())
557 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000558
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000559 switch (CompareRegionOfInterest(Range)) {
560 case RangeBefore:
561 // This declaration comes before the region of interest; skip it.
562 return llvm::Optional<bool>();
563
564 case RangeAfter:
565 // This declaration comes after the region of interest; we're done.
566 return false;
567
568 case RangeOverlap:
569 // This declaration overlaps the region of interest; visit it.
570 break;
571 }
572 }
573 return true;
574}
575
576bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
577 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
578
579 // FIXME: Eventually remove. This part of a hack to support proper
580 // iteration over all Decls contained lexically within an ObjC container.
581 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
582 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
583
584 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000585 Decl *D = *I;
586 if (D->getLexicalDeclContext() != DC)
587 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000588 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000589 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
590 if (!V.hasValue())
591 continue;
592 if (!V.getValue())
593 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000594 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595 return true;
596 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000598}
599
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000600bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
601 llvm_unreachable("Translation units are visited directly by Visit()");
602 return false;
603}
604
605bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
606 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
607 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609 return false;
610}
611
612bool CursorVisitor::VisitTagDecl(TagDecl *D) {
613 return VisitDeclContext(D);
614}
615
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000616bool CursorVisitor::VisitClassTemplateSpecializationDecl(
617 ClassTemplateSpecializationDecl *D) {
618 bool ShouldVisitBody = false;
619 switch (D->getSpecializationKind()) {
620 case TSK_Undeclared:
621 case TSK_ImplicitInstantiation:
622 // Nothing to visit
623 return false;
624
625 case TSK_ExplicitInstantiationDeclaration:
626 case TSK_ExplicitInstantiationDefinition:
627 break;
628
629 case TSK_ExplicitSpecialization:
630 ShouldVisitBody = true;
631 break;
632 }
633
634 // Visit the template arguments used in the specialization.
635 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
636 TypeLoc TL = SpecType->getTypeLoc();
637 if (TemplateSpecializationTypeLoc *TSTLoc
638 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
639 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
640 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
641 return true;
642 }
643 }
644
645 if (ShouldVisitBody && VisitCXXRecordDecl(D))
646 return true;
647
648 return false;
649}
650
Douglas Gregor74dbe642010-08-31 19:31:58 +0000651bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
652 ClassTemplatePartialSpecializationDecl *D) {
653 // FIXME: Visit the "outer" template parameter lists on the TagDecl
654 // before visiting these template parameters.
655 if (VisitTemplateParameters(D->getTemplateParameters()))
656 return true;
657
658 // Visit the partial specialization arguments.
659 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
660 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
661 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
662 return true;
663
664 return VisitCXXRecordDecl(D);
665}
666
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000667bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000668 // Visit the default argument.
669 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
670 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
671 if (Visit(DefArg->getTypeLoc()))
672 return true;
673
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000674 return false;
675}
676
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000677bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
678 if (Expr *Init = D->getInitExpr())
679 return Visit(MakeCXCursor(Init, StmtParent, TU));
680 return false;
681}
682
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000683bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
684 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
685 if (Visit(TSInfo->getTypeLoc()))
686 return true;
687
688 return false;
689}
690
Douglas Gregora67e03f2010-09-09 21:42:20 +0000691/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000692static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
693 CXXCtorInitializer const * const *X
694 = static_cast<CXXCtorInitializer const * const *>(Xp);
695 CXXCtorInitializer const * const *Y
696 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000697
698 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
699 return -1;
700 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
701 return 1;
702 else
703 return 0;
704}
705
Douglas Gregorb1373d02010-01-20 20:59:29 +0000706bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000707 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
708 // Visit the function declaration's syntactic components in the order
709 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000710 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000711 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
712
713 // If we have a function declared directly (without the use of a typedef),
714 // visit just the return type. Otherwise, just visit the function's type
715 // now.
716 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
717 (!FTL && Visit(TL)))
718 return true;
719
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000720 // Visit the nested-name-specifier, if present.
721 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
722 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
723 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000724
725 // Visit the declaration name.
726 if (VisitDeclarationNameInfo(ND->getNameInfo()))
727 return true;
728
729 // FIXME: Visit explicitly-specified template arguments!
730
731 // Visit the function parameters, if we have a function type.
732 if (FTL && VisitFunctionTypeLoc(*FTL, true))
733 return true;
734
735 // FIXME: Attributes?
736 }
737
Douglas Gregora67e03f2010-09-09 21:42:20 +0000738 if (ND->isThisDeclarationADefinition()) {
739 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
740 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000741 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000742 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
743 IEnd = Constructor->init_end();
744 I != IEnd; ++I) {
745 if (!(*I)->isWritten())
746 continue;
747
748 WrittenInits.push_back(*I);
749 }
750
751 // Sort the initializers in source order
752 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000753 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000754
755 // Visit the initializers in source order
756 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000757 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000758 if (Init->isAnyMemberInitializer()) {
759 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000760 Init->getMemberLocation(), TU)))
761 return true;
762 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
763 if (Visit(BaseInfo->getTypeLoc()))
764 return true;
765 }
766
767 // Visit the initializer value.
768 if (Expr *Initializer = Init->getInit())
769 if (Visit(MakeCXCursor(Initializer, ND, TU)))
770 return true;
771 }
772 }
773
774 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
775 return true;
776 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregorb1373d02010-01-20 20:59:29 +0000778 return false;
779}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
782 if (VisitDeclaratorDecl(D))
783 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785 if (Expr *BitWidth = D->getBitWidth())
786 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788 return false;
789}
790
791bool CursorVisitor::VisitVarDecl(VarDecl *D) {
792 if (VisitDeclaratorDecl(D))
793 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 if (Expr *Init = D->getInit())
796 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798 return false;
799}
800
Douglas Gregor84b51d72010-09-01 20:16:53 +0000801bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
802 if (VisitDeclaratorDecl(D))
803 return true;
804
805 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
806 if (Expr *DefArg = D->getDefaultArgument())
807 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
808
809 return false;
810}
811
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000812bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
813 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
814 // before visiting these template parameters.
815 if (VisitTemplateParameters(D->getTemplateParameters()))
816 return true;
817
818 return VisitFunctionDecl(D->getTemplatedDecl());
819}
820
Douglas Gregor39d6f072010-08-31 19:02:00 +0000821bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
822 // FIXME: Visit the "outer" template parameter lists on the TagDecl
823 // before visiting these template parameters.
824 if (VisitTemplateParameters(D->getTemplateParameters()))
825 return true;
826
827 return VisitCXXRecordDecl(D->getTemplatedDecl());
828}
829
Douglas Gregor84b51d72010-09-01 20:16:53 +0000830bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
831 if (VisitTemplateParameters(D->getTemplateParameters()))
832 return true;
833
834 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
835 VisitTemplateArgumentLoc(D->getDefaultArgument()))
836 return true;
837
838 return false;
839}
840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000842 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
843 if (Visit(TSInfo->getTypeLoc()))
844 return true;
845
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000846 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000847 PEnd = ND->param_end();
848 P != PEnd; ++P) {
849 if (Visit(MakeCXCursor(*P, TU)))
850 return true;
851 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853 if (ND->isThisDeclarationADefinition() &&
854 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
855 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 return false;
858}
859
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000860namespace {
861 struct ContainerDeclsSort {
862 SourceManager &SM;
863 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
864 bool operator()(Decl *A, Decl *B) {
865 SourceLocation L_A = A->getLocStart();
866 SourceLocation L_B = B->getLocStart();
867 assert(L_A.isValid() && L_B.isValid());
868 return SM.isBeforeInTranslationUnit(L_A, L_B);
869 }
870 };
871}
872
Douglas Gregora59e3902010-01-21 23:27:09 +0000873bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000874 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
875 // an @implementation can lexically contain Decls that are not properly
876 // nested in the AST. When we identify such cases, we need to retrofit
877 // this nesting here.
878 if (!DI_current)
879 return VisitDeclContext(D);
880
881 // Scan the Decls that immediately come after the container
882 // in the current DeclContext. If any fall within the
883 // container's lexical region, stash them into a vector
884 // for later processing.
885 llvm::SmallVector<Decl *, 24> DeclsInContainer;
886 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000887 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000888 if (EndLoc.isValid()) {
889 DeclContext::decl_iterator next = *DI_current;
890 while (++next != DE_current) {
891 Decl *D_next = *next;
892 if (!D_next)
893 break;
894 SourceLocation L = D_next->getLocStart();
895 if (!L.isValid())
896 break;
897 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
898 *DI_current = next;
899 DeclsInContainer.push_back(D_next);
900 continue;
901 }
902 break;
903 }
904 }
905
906 // The common case.
907 if (DeclsInContainer.empty())
908 return VisitDeclContext(D);
909
910 // Get all the Decls in the DeclContext, and sort them with the
911 // additional ones we've collected. Then visit them.
912 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
913 I!=E; ++I) {
914 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000915 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
916 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000917 continue;
918 DeclsInContainer.push_back(subDecl);
919 }
920
921 // Now sort the Decls so that they appear in lexical order.
922 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
923 ContainerDeclsSort(SM));
924
925 // Now visit the decls.
926 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
927 E = DeclsInContainer.end(); I != E; ++I) {
928 CXCursor Cursor = MakeCXCursor(*I, TU);
929 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
930 if (!V.hasValue())
931 continue;
932 if (!V.getValue())
933 return false;
934 if (Visit(Cursor, true))
935 return true;
936 }
937 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000938}
939
Douglas Gregorb1373d02010-01-20 20:59:29 +0000940bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000941 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
942 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000943 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000944
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000945 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
946 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
947 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000948 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregora59e3902010-01-21 23:27:09 +0000951 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000952}
953
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000954bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
955 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
956 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
957 E = PID->protocol_end(); I != E; ++I, ++PL)
958 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
959 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000960
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000961 return VisitObjCContainerDecl(PID);
962}
963
Ted Kremenek23173d72010-05-18 21:09:07 +0000964bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000965 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000966 return true;
967
Ted Kremenek23173d72010-05-18 21:09:07 +0000968 // FIXME: This implements a workaround with @property declarations also being
969 // installed in the DeclContext for the @interface. Eventually this code
970 // should be removed.
971 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
972 if (!CDecl || !CDecl->IsClassExtension())
973 return false;
974
975 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
976 if (!ID)
977 return false;
978
979 IdentifierInfo *PropertyId = PD->getIdentifier();
980 ObjCPropertyDecl *prevDecl =
981 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
982
983 if (!prevDecl)
984 return false;
985
986 // Visit synthesized methods since they will be skipped when visiting
987 // the @interface.
988 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000989 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000990 if (Visit(MakeCXCursor(MD, TU)))
991 return true;
992
993 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000994 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000995 if (Visit(MakeCXCursor(MD, TU)))
996 return true;
997
998 return false;
999}
1000
Douglas Gregorb1373d02010-01-20 20:59:29 +00001001bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001002 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003 if (D->getSuperClass() &&
1004 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001005 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001006 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001007 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001008
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001009 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1010 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1011 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001012 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregora59e3902010-01-21 23:27:09 +00001015 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001016}
1017
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1019 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001023 // 'ID' could be null when dealing with invalid code.
1024 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1025 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1026 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028 return VisitObjCImplDecl(D);
1029}
1030
1031bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1032#if 0
1033 // Issue callbacks for super class.
1034 // FIXME: No source location information!
1035 if (D->getSuperClass() &&
1036 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001038 TU)))
1039 return true;
1040#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042 return VisitObjCImplDecl(D);
1043}
1044
1045bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1046 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1047 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1048 E = D->protocol_end();
1049 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001050 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001051 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
1053 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001054}
1055
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001056bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1057 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1058 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1059 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001062}
1063
Douglas Gregora4ffd852010-11-17 01:03:52 +00001064bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1065 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1066 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1067
1068 return false;
1069}
1070
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001071bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1072 return VisitDeclContext(D);
1073}
1074
Douglas Gregor69319002010-08-31 23:48:11 +00001075bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001076 // Visit nested-name-specifier.
1077 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1078 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1079 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001080
1081 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1082 D->getTargetNameLoc(), TU));
1083}
1084
Douglas Gregor7e242562010-09-01 19:52:22 +00001085bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 // Visit nested-name-specifier.
1087 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1088 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1089 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001090
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001091 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1092 return true;
1093
Douglas Gregor7e242562010-09-01 19:52:22 +00001094 return VisitDeclarationNameInfo(D->getNameInfo());
1095}
1096
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001097bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001098 // Visit nested-name-specifier.
1099 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1100 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1101 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001102
1103 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1104 D->getIdentLocation(), TU));
1105}
1106
Douglas Gregor7e242562010-09-01 19:52:22 +00001107bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001108 // Visit nested-name-specifier.
1109 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1110 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1111 return true;
1112
Douglas Gregor7e242562010-09-01 19:52:22 +00001113 return VisitDeclarationNameInfo(D->getNameInfo());
1114}
1115
1116bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1117 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118 // Visit nested-name-specifier.
1119 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1120 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1121 return true;
1122
Douglas Gregor7e242562010-09-01 19:52:22 +00001123 return false;
1124}
1125
Douglas Gregor01829d32010-08-31 14:41:23 +00001126bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1127 switch (Name.getName().getNameKind()) {
1128 case clang::DeclarationName::Identifier:
1129 case clang::DeclarationName::CXXLiteralOperatorName:
1130 case clang::DeclarationName::CXXOperatorName:
1131 case clang::DeclarationName::CXXUsingDirective:
1132 return false;
1133
1134 case clang::DeclarationName::CXXConstructorName:
1135 case clang::DeclarationName::CXXDestructorName:
1136 case clang::DeclarationName::CXXConversionFunctionName:
1137 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1138 return Visit(TSInfo->getTypeLoc());
1139 return false;
1140
1141 case clang::DeclarationName::ObjCZeroArgSelector:
1142 case clang::DeclarationName::ObjCOneArgSelector:
1143 case clang::DeclarationName::ObjCMultiArgSelector:
1144 // FIXME: Per-identifier location info?
1145 return false;
1146 }
1147
1148 return false;
1149}
1150
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001151bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1152 SourceRange Range) {
1153 // FIXME: This whole routine is a hack to work around the lack of proper
1154 // source information in nested-name-specifiers (PR5791). Since we do have
1155 // a beginning source location, we can visit the first component of the
1156 // nested-name-specifier, if it's a single-token component.
1157 if (!NNS)
1158 return false;
1159
1160 // Get the first component in the nested-name-specifier.
1161 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1162 NNS = Prefix;
1163
1164 switch (NNS->getKind()) {
1165 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001166 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1167 TU));
1168
Douglas Gregor14aba762011-02-24 02:36:08 +00001169 case NestedNameSpecifier::NamespaceAlias:
1170 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1171 Range.getBegin(), TU));
1172
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001173 case NestedNameSpecifier::TypeSpec: {
1174 // If the type has a form where we know that the beginning of the source
1175 // range matches up with a reference cursor. Visit the appropriate reference
1176 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001177 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001178 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1179 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1180 if (const TagType *Tag = dyn_cast<TagType>(T))
1181 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1182 if (const TemplateSpecializationType *TST
1183 = dyn_cast<TemplateSpecializationType>(T))
1184 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1185 break;
1186 }
1187
1188 case NestedNameSpecifier::TypeSpecWithTemplate:
1189 case NestedNameSpecifier::Global:
1190 case NestedNameSpecifier::Identifier:
1191 break;
1192 }
1193
1194 return false;
1195}
1196
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001197bool CursorVisitor::VisitTemplateParameters(
1198 const TemplateParameterList *Params) {
1199 if (!Params)
1200 return false;
1201
1202 for (TemplateParameterList::const_iterator P = Params->begin(),
1203 PEnd = Params->end();
1204 P != PEnd; ++P) {
1205 if (Visit(MakeCXCursor(*P, TU)))
1206 return true;
1207 }
1208
1209 return false;
1210}
1211
Douglas Gregor0b36e612010-08-31 20:37:03 +00001212bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1213 switch (Name.getKind()) {
1214 case TemplateName::Template:
1215 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1216
1217 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001218 // Visit the overloaded template set.
1219 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1220 return true;
1221
Douglas Gregor0b36e612010-08-31 20:37:03 +00001222 return false;
1223
1224 case TemplateName::DependentTemplate:
1225 // FIXME: Visit nested-name-specifier.
1226 return false;
1227
1228 case TemplateName::QualifiedTemplate:
1229 // FIXME: Visit nested-name-specifier.
1230 return Visit(MakeCursorTemplateRef(
1231 Name.getAsQualifiedTemplateName()->getDecl(),
1232 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001233
1234 case TemplateName::SubstTemplateTemplateParmPack:
1235 return Visit(MakeCursorTemplateRef(
1236 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1237 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001238 }
1239
1240 return false;
1241}
1242
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001243bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1244 switch (TAL.getArgument().getKind()) {
1245 case TemplateArgument::Null:
1246 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001247 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001248 return false;
1249
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001250 case TemplateArgument::Type:
1251 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1252 return Visit(TSInfo->getTypeLoc());
1253 return false;
1254
1255 case TemplateArgument::Declaration:
1256 if (Expr *E = TAL.getSourceDeclExpression())
1257 return Visit(MakeCXCursor(E, StmtParent, TU));
1258 return false;
1259
1260 case TemplateArgument::Expression:
1261 if (Expr *E = TAL.getSourceExpression())
1262 return Visit(MakeCXCursor(E, StmtParent, TU));
1263 return false;
1264
1265 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001266 case TemplateArgument::TemplateExpansion:
1267 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001268 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001269 }
1270
1271 return false;
1272}
1273
Ted Kremeneka0536d82010-05-07 01:04:29 +00001274bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1275 return VisitDeclContext(D);
1276}
1277
Douglas Gregor01829d32010-08-31 14:41:23 +00001278bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1279 return Visit(TL.getUnqualifiedLoc());
1280}
1281
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001282bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001283 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001284
1285 // Some builtin types (such as Objective-C's "id", "sel", and
1286 // "Class") have associated declarations. Create cursors for those.
1287 QualType VisitType;
1288 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001289 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001290 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001291 case BuiltinType::Char_U:
1292 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001293 case BuiltinType::Char16:
1294 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001295 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001296 case BuiltinType::UInt:
1297 case BuiltinType::ULong:
1298 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001299 case BuiltinType::UInt128:
1300 case BuiltinType::Char_S:
1301 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001302 case BuiltinType::WChar_U:
1303 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001304 case BuiltinType::Short:
1305 case BuiltinType::Int:
1306 case BuiltinType::Long:
1307 case BuiltinType::LongLong:
1308 case BuiltinType::Int128:
1309 case BuiltinType::Float:
1310 case BuiltinType::Double:
1311 case BuiltinType::LongDouble:
1312 case BuiltinType::NullPtr:
1313 case BuiltinType::Overload:
1314 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001315 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001316
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001317 case BuiltinType::ObjCId:
1318 VisitType = Context.getObjCIdType();
1319 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001320
1321 case BuiltinType::ObjCClass:
1322 VisitType = Context.getObjCClassType();
1323 break;
1324
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001325 case BuiltinType::ObjCSel:
1326 VisitType = Context.getObjCSelType();
1327 break;
1328 }
1329
1330 if (!VisitType.isNull()) {
1331 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001332 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333 TU));
1334 }
1335
1336 return false;
1337}
1338
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001339bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1340 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1341}
1342
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001343bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1344 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1345}
1346
1347bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1348 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1349}
1350
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001351bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001352 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001353 // no context information with which we can match up the depth/index in the
1354 // type to the appropriate
1355 return false;
1356}
1357
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001358bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1359 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1360 return true;
1361
John McCallc12c5bb2010-05-15 11:32:37 +00001362 return false;
1363}
1364
1365bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1366 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1367 return true;
1368
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001369 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1370 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1371 TU)))
1372 return true;
1373 }
1374
1375 return false;
1376}
1377
1378bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001379 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380}
1381
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001382bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1383 return Visit(TL.getInnerLoc());
1384}
1385
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1387 return Visit(TL.getPointeeLoc());
1388}
1389
1390bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1391 return Visit(TL.getPointeeLoc());
1392}
1393
1394bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1395 return Visit(TL.getPointeeLoc());
1396}
1397
1398bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001399 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001400}
1401
1402bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001403 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001404}
1405
Douglas Gregor01829d32010-08-31 14:41:23 +00001406bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1407 bool SkipResultType) {
1408 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409 return true;
1410
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001411 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001412 if (Decl *D = TL.getArg(I))
1413 if (Visit(MakeCXCursor(D, TU)))
1414 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001415
1416 return false;
1417}
1418
1419bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1420 if (Visit(TL.getElementLoc()))
1421 return true;
1422
1423 if (Expr *Size = TL.getSizeExpr())
1424 return Visit(MakeCXCursor(Size, StmtParent, TU));
1425
1426 return false;
1427}
1428
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001429bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1430 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001431 // Visit the template name.
1432 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1433 TL.getTemplateNameLoc()))
1434 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001435
1436 // Visit the template arguments.
1437 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1438 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1439 return true;
1440
1441 return false;
1442}
1443
Douglas Gregor2332c112010-01-21 20:48:56 +00001444bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1445 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1446}
1447
1448bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1449 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1450 return Visit(TSInfo->getTypeLoc());
1451
1452 return false;
1453}
1454
Douglas Gregor7536dd52010-12-20 02:24:11 +00001455bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1456 return Visit(TL.getPatternLoc());
1457}
1458
Ted Kremenek3064ef92010-08-27 21:34:58 +00001459bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1460 if (D->isDefinition()) {
1461 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1462 E = D->bases_end(); I != E; ++I) {
1463 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1464 return true;
1465 }
1466 }
1467
1468 return VisitTagDecl(D);
1469}
1470
Ted Kremenek09dfa372010-02-18 05:46:33 +00001471bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001472 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1473 i != e; ++i)
1474 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001475 return true;
1476
1477 return false;
1478}
1479
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001480//===----------------------------------------------------------------------===//
1481// Data-recursive visitor methods.
1482//===----------------------------------------------------------------------===//
1483
Ted Kremenek28a71942010-11-13 00:36:47 +00001484namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001485#define DEF_JOB(NAME, DATA, KIND)\
1486class NAME : public VisitorJob {\
1487public:\
1488 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1489 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001490 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001491};
1492
1493DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1494DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001495DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001496DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001497DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1498 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001499DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001500#undef DEF_JOB
1501
1502class DeclVisit : public VisitorJob {
1503public:
1504 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1505 VisitorJob(parent, VisitorJob::DeclVisitKind,
1506 d, isFirst ? (void*) 1 : (void*) 0) {}
1507 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001508 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001509 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001510 Decl *get() const { return static_cast<Decl*>(data[0]); }
1511 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001512};
Ted Kremenek035dc412010-11-13 00:36:50 +00001513class TypeLocVisit : public VisitorJob {
1514public:
1515 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1516 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1517 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1518
1519 static bool classof(const VisitorJob *VJ) {
1520 return VJ->getKind() == TypeLocVisitKind;
1521 }
1522
Ted Kremenek82f3c502010-11-15 22:23:26 +00001523 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001524 QualType T = QualType::getFromOpaquePtr(data[0]);
1525 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001526 }
1527};
1528
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001529class LabelRefVisit : public VisitorJob {
1530public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001531 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1532 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001533 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001534
1535 static bool classof(const VisitorJob *VJ) {
1536 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1537 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001538 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001539 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001540 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001541};
1542class NestedNameSpecifierVisit : public VisitorJob {
1543public:
1544 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1545 CXCursor parent)
1546 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001547 NS, R.getBegin().getPtrEncoding(),
1548 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001549 static bool classof(const VisitorJob *VJ) {
1550 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1551 }
1552 NestedNameSpecifier *get() const {
1553 return static_cast<NestedNameSpecifier*>(data[0]);
1554 }
1555 SourceRange getSourceRange() const {
1556 SourceLocation A =
1557 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1558 SourceLocation B =
1559 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1560 return SourceRange(A, B);
1561 }
1562};
1563class DeclarationNameInfoVisit : public VisitorJob {
1564public:
1565 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1566 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1567 static bool classof(const VisitorJob *VJ) {
1568 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1569 }
1570 DeclarationNameInfo get() const {
1571 Stmt *S = static_cast<Stmt*>(data[0]);
1572 switch (S->getStmtClass()) {
1573 default:
1574 llvm_unreachable("Unhandled Stmt");
1575 case Stmt::CXXDependentScopeMemberExprClass:
1576 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1577 case Stmt::DependentScopeDeclRefExprClass:
1578 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1579 }
1580 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001581};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001582class MemberRefVisit : public VisitorJob {
1583public:
1584 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1585 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001586 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001587 static bool classof(const VisitorJob *VJ) {
1588 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1589 }
1590 FieldDecl *get() const {
1591 return static_cast<FieldDecl*>(data[0]);
1592 }
1593 SourceLocation getLoc() const {
1594 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1595 }
1596};
Ted Kremenek28a71942010-11-13 00:36:47 +00001597class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1598 VisitorWorkList &WL;
1599 CXCursor Parent;
1600public:
1601 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1602 : WL(wl), Parent(parent) {}
1603
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001604 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001605 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001606 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001607 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001608 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001609 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001610 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001611 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001612 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001613 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001614 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001615 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001616 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001617 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001618 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001619 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001620 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001621 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001622 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1623 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001624 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001625 void VisitIfStmt(IfStmt *If);
1626 void VisitInitListExpr(InitListExpr *IE);
1627 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001628 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001629 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001630 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1631 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001632 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001633 void VisitStmt(Stmt *S);
1634 void VisitSwitchStmt(SwitchStmt *S);
1635 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001636 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001637 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001638 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001639 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001640 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001641
Ted Kremenek28a71942010-11-13 00:36:47 +00001642private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001643 void AddDeclarationNameInfo(Stmt *S);
1644 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001645 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001646 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001647 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001648 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001649 void AddTypeLoc(TypeSourceInfo *TI);
1650 void EnqueueChildren(Stmt *S);
1651};
1652} // end anonyous namespace
1653
Ted Kremenekf64d8032010-11-18 00:02:32 +00001654void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1655 // 'S' should always be non-null, since it comes from the
1656 // statement we are visiting.
1657 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1658}
1659void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1660 SourceRange R) {
1661 if (N)
1662 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1663}
Ted Kremenek28a71942010-11-13 00:36:47 +00001664void EnqueueVisitor::AddStmt(Stmt *S) {
1665 if (S)
1666 WL.push_back(StmtVisit(S, Parent));
1667}
Ted Kremenek035dc412010-11-13 00:36:50 +00001668void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001669 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001670 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001671}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001672void EnqueueVisitor::
1673 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1674 if (A)
1675 WL.push_back(ExplicitTemplateArgsVisit(
1676 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1677}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001678void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1679 if (D)
1680 WL.push_back(MemberRefVisit(D, L, Parent));
1681}
Ted Kremenek28a71942010-11-13 00:36:47 +00001682void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1683 if (TI)
1684 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1685 }
1686void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001687 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001688 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001689 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001690 }
1691 if (size == WL.size())
1692 return;
1693 // Now reverse the entries we just added. This will match the DFS
1694 // ordering performed by the worklist.
1695 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1696 std::reverse(I, E);
1697}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001698void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1699 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1700}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001701void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1702 AddDecl(B->getBlockDecl());
1703}
Ted Kremenek28a71942010-11-13 00:36:47 +00001704void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1705 EnqueueChildren(E);
1706 AddTypeLoc(E->getTypeSourceInfo());
1707}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001708void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1709 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1710 E = S->body_rend(); I != E; ++I) {
1711 AddStmt(*I);
1712 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001713}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001714void EnqueueVisitor::
1715VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1716 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1717 AddDeclarationNameInfo(E);
1718 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1719 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1720 if (!E->isImplicitAccess())
1721 AddStmt(E->getBase());
1722}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001723void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1724 // Enqueue the initializer or constructor arguments.
1725 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1726 AddStmt(E->getConstructorArg(I-1));
1727 // Enqueue the array size, if any.
1728 AddStmt(E->getArraySize());
1729 // Enqueue the allocated type.
1730 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1731 // Enqueue the placement arguments.
1732 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1733 AddStmt(E->getPlacementArg(I-1));
1734}
Ted Kremenek28a71942010-11-13 00:36:47 +00001735void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001736 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1737 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001738 AddStmt(CE->getCallee());
1739 AddStmt(CE->getArg(0));
1740}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001741void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1742 // Visit the name of the type being destroyed.
1743 AddTypeLoc(E->getDestroyedTypeInfo());
1744 // Visit the scope type that looks disturbingly like the nested-name-specifier
1745 // but isn't.
1746 AddTypeLoc(E->getScopeTypeInfo());
1747 // Visit the nested-name-specifier.
1748 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1749 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1750 // Visit base expression.
1751 AddStmt(E->getBase());
1752}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001753void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1754 AddTypeLoc(E->getTypeSourceInfo());
1755}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001756void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1757 EnqueueChildren(E);
1758 AddTypeLoc(E->getTypeSourceInfo());
1759}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001760void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1761 EnqueueChildren(E);
1762 if (E->isTypeOperand())
1763 AddTypeLoc(E->getTypeOperandSourceInfo());
1764}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001765
1766void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1767 *E) {
1768 EnqueueChildren(E);
1769 AddTypeLoc(E->getTypeSourceInfo());
1770}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001771void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1772 EnqueueChildren(E);
1773 if (E->isTypeOperand())
1774 AddTypeLoc(E->getTypeOperandSourceInfo());
1775}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001776void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001777 if (DR->hasExplicitTemplateArgs()) {
1778 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1779 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001780 WL.push_back(DeclRefExprParts(DR, Parent));
1781}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001782void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1783 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1784 AddDeclarationNameInfo(E);
1785 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1786 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1787}
Ted Kremenek035dc412010-11-13 00:36:50 +00001788void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1789 unsigned size = WL.size();
1790 bool isFirst = true;
1791 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1792 D != DEnd; ++D) {
1793 AddDecl(*D, isFirst);
1794 isFirst = false;
1795 }
1796 if (size == WL.size())
1797 return;
1798 // Now reverse the entries we just added. This will match the DFS
1799 // ordering performed by the worklist.
1800 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1801 std::reverse(I, E);
1802}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001803void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1804 AddStmt(E->getInit());
1805 typedef DesignatedInitExpr::Designator Designator;
1806 for (DesignatedInitExpr::reverse_designators_iterator
1807 D = E->designators_rbegin(), DEnd = E->designators_rend();
1808 D != DEnd; ++D) {
1809 if (D->isFieldDesignator()) {
1810 if (FieldDecl *Field = D->getField())
1811 AddMemberRef(Field, D->getFieldLoc());
1812 continue;
1813 }
1814 if (D->isArrayDesignator()) {
1815 AddStmt(E->getArrayIndex(*D));
1816 continue;
1817 }
1818 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1819 AddStmt(E->getArrayRangeEnd(*D));
1820 AddStmt(E->getArrayRangeStart(*D));
1821 }
1822}
Ted Kremenek28a71942010-11-13 00:36:47 +00001823void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1824 EnqueueChildren(E);
1825 AddTypeLoc(E->getTypeInfoAsWritten());
1826}
1827void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1828 AddStmt(FS->getBody());
1829 AddStmt(FS->getInc());
1830 AddStmt(FS->getCond());
1831 AddDecl(FS->getConditionVariable());
1832 AddStmt(FS->getInit());
1833}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001834void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1835 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1836}
Ted Kremenek28a71942010-11-13 00:36:47 +00001837void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1838 AddStmt(If->getElse());
1839 AddStmt(If->getThen());
1840 AddStmt(If->getCond());
1841 AddDecl(If->getConditionVariable());
1842}
1843void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1844 // We care about the syntactic form of the initializer list, only.
1845 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1846 IE = Syntactic;
1847 EnqueueChildren(IE);
1848}
1849void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001850 WL.push_back(MemberExprParts(M, Parent));
1851
1852 // If the base of the member access expression is an implicit 'this', don't
1853 // visit it.
1854 // FIXME: If we ever want to show these implicit accesses, this will be
1855 // unfortunate. However, clang_getCursor() relies on this behavior.
1856 if (CXXThisExpr *This
1857 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1858 if (This->isImplicit())
1859 return;
1860
Ted Kremenek28a71942010-11-13 00:36:47 +00001861 AddStmt(M->getBase());
1862}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001863void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1864 AddTypeLoc(E->getEncodedTypeSourceInfo());
1865}
Ted Kremenek28a71942010-11-13 00:36:47 +00001866void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1867 EnqueueChildren(M);
1868 AddTypeLoc(M->getClassReceiverTypeInfo());
1869}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001870void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1871 // Visit the components of the offsetof expression.
1872 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1873 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1874 const OffsetOfNode &Node = E->getComponent(I-1);
1875 switch (Node.getKind()) {
1876 case OffsetOfNode::Array:
1877 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1878 break;
1879 case OffsetOfNode::Field:
1880 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1881 break;
1882 case OffsetOfNode::Identifier:
1883 case OffsetOfNode::Base:
1884 continue;
1885 }
1886 }
1887 // Visit the type into which we're computing the offset.
1888 AddTypeLoc(E->getTypeSourceInfo());
1889}
Ted Kremenek28a71942010-11-13 00:36:47 +00001890void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001891 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001892 WL.push_back(OverloadExprParts(E, Parent));
1893}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001894void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1895 EnqueueChildren(E);
1896 if (E->isArgumentType())
1897 AddTypeLoc(E->getArgumentTypeInfo());
1898}
Ted Kremenek28a71942010-11-13 00:36:47 +00001899void EnqueueVisitor::VisitStmt(Stmt *S) {
1900 EnqueueChildren(S);
1901}
1902void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1903 AddStmt(S->getBody());
1904 AddStmt(S->getCond());
1905 AddDecl(S->getConditionVariable());
1906}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001907
Ted Kremenek28a71942010-11-13 00:36:47 +00001908void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1909 AddStmt(W->getBody());
1910 AddStmt(W->getCond());
1911 AddDecl(W->getConditionVariable());
1912}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001913void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1914 AddTypeLoc(E->getQueriedTypeSourceInfo());
1915}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001916
1917void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00001918 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00001919 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00001920}
1921
Ted Kremenek28a71942010-11-13 00:36:47 +00001922void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1923 VisitOverloadExpr(U);
1924 if (!U->isImplicitAccess())
1925 AddStmt(U->getBase());
1926}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001927void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1928 AddStmt(E->getSubExpr());
1929 AddTypeLoc(E->getWrittenTypeInfo());
1930}
Douglas Gregor94d96292011-01-19 20:34:17 +00001931void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1932 WL.push_back(SizeOfPackExprParts(E, Parent));
1933}
Ted Kremenek60458782010-11-12 21:34:16 +00001934
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001935void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001936 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001937}
1938
1939bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1940 if (RegionOfInterest.isValid()) {
1941 SourceRange Range = getRawCursorExtent(C);
1942 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1943 return false;
1944 }
1945 return true;
1946}
1947
1948bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1949 while (!WL.empty()) {
1950 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001951 VisitorJob LI = WL.back();
1952 WL.pop_back();
1953
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001954 // Set the Parent field, then back to its old value once we're done.
1955 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1956
1957 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001958 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001959 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001960 if (!D)
1961 continue;
1962
1963 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001964 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001965 return true;
1966
1967 continue;
1968 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001969 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1970 const ExplicitTemplateArgumentList *ArgList =
1971 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1972 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1973 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1974 Arg != ArgEnd; ++Arg) {
1975 if (VisitTemplateArgumentLoc(*Arg))
1976 return true;
1977 }
1978 continue;
1979 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001980 case VisitorJob::TypeLocVisitKind: {
1981 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001982 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001983 return true;
1984 continue;
1985 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001986 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001987 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00001988 if (LabelStmt *stmt = LS->getStmt()) {
1989 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
1990 TU))) {
1991 return true;
1992 }
1993 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001994 continue;
1995 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001996 case VisitorJob::NestedNameSpecifierVisitKind: {
1997 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
1998 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
1999 return true;
2000 continue;
2001 }
2002 case VisitorJob::DeclarationNameInfoVisitKind: {
2003 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2004 ->get()))
2005 return true;
2006 continue;
2007 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002008 case VisitorJob::MemberRefVisitKind: {
2009 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2010 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2011 return true;
2012 continue;
2013 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002014 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002015 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002016 if (!S)
2017 continue;
2018
Ted Kremenekf1107452010-11-12 18:26:56 +00002019 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002020 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002021 if (!IsInRegionOfInterest(Cursor))
2022 continue;
2023 switch (Visitor(Cursor, Parent, ClientData)) {
2024 case CXChildVisit_Break: return true;
2025 case CXChildVisit_Continue: break;
2026 case CXChildVisit_Recurse:
2027 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002028 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002029 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002030 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002031 }
2032 case VisitorJob::MemberExprPartsKind: {
2033 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002034 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002035
2036 // Visit the nested-name-specifier
2037 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2038 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2039 return true;
2040
2041 // Visit the declaration name.
2042 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2043 return true;
2044
2045 // Visit the explicitly-specified template arguments, if any.
2046 if (M->hasExplicitTemplateArgs()) {
2047 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2048 *ArgEnd = Arg + M->getNumTemplateArgs();
2049 Arg != ArgEnd; ++Arg) {
2050 if (VisitTemplateArgumentLoc(*Arg))
2051 return true;
2052 }
2053 }
2054 continue;
2055 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002056 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002057 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002058 // Visit nested-name-specifier, if present.
2059 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2060 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2061 return true;
2062 // Visit declaration name.
2063 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2064 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002065 continue;
2066 }
Ted Kremenek60458782010-11-12 21:34:16 +00002067 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002068 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002069 // Visit the nested-name-specifier.
2070 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2071 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2072 return true;
2073 // Visit the declaration name.
2074 if (VisitDeclarationNameInfo(O->getNameInfo()))
2075 return true;
2076 // Visit the overloaded declaration reference.
2077 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2078 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002079 continue;
2080 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002081 case VisitorJob::SizeOfPackExprPartsKind: {
2082 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2083 NamedDecl *Pack = E->getPack();
2084 if (isa<TemplateTypeParmDecl>(Pack)) {
2085 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2086 E->getPackLoc(), TU)))
2087 return true;
2088
2089 continue;
2090 }
2091
2092 if (isa<TemplateTemplateParmDecl>(Pack)) {
2093 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2094 E->getPackLoc(), TU)))
2095 return true;
2096
2097 continue;
2098 }
2099
2100 // Non-type template parameter packs and function parameter packs are
2101 // treated like DeclRefExpr cursors.
2102 continue;
2103 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002104 }
2105 }
2106 return false;
2107}
2108
Ted Kremenekcdba6592010-11-18 00:42:18 +00002109bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002110 VisitorWorkList *WL = 0;
2111 if (!WorkListFreeList.empty()) {
2112 WL = WorkListFreeList.back();
2113 WL->clear();
2114 WorkListFreeList.pop_back();
2115 }
2116 else {
2117 WL = new VisitorWorkList();
2118 WorkListCache.push_back(WL);
2119 }
2120 EnqueueWorkList(*WL, S);
2121 bool result = RunVisitorWorkList(*WL);
2122 WorkListFreeList.push_back(WL);
2123 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002124}
2125
2126//===----------------------------------------------------------------------===//
2127// Misc. API hooks.
2128//===----------------------------------------------------------------------===//
2129
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002130static llvm::sys::Mutex EnableMultithreadingMutex;
2131static bool EnabledMultithreading;
2132
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002133extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002134CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2135 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002136 // Disable pretty stack trace functionality, which will otherwise be a very
2137 // poor citizen of the world and set up all sorts of signal handlers.
2138 llvm::DisablePrettyStackTrace = true;
2139
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002140 // We use crash recovery to make some of our APIs more reliable, implicitly
2141 // enable it.
2142 llvm::CrashRecoveryContext::Enable();
2143
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002144 // Enable support for multithreading in LLVM.
2145 {
2146 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2147 if (!EnabledMultithreading) {
2148 llvm::llvm_start_multithreaded();
2149 EnabledMultithreading = true;
2150 }
2151 }
2152
Douglas Gregora030b7c2010-01-22 20:35:53 +00002153 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002154 if (excludeDeclarationsFromPCH)
2155 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002156 if (displayDiagnostics)
2157 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002158 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002159}
2160
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002161void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002162 if (CIdx)
2163 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002164}
2165
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002166CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002167 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002168 if (!CIdx)
2169 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002170
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002171 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002172 FileSystemOptions FileSystemOpts;
2173 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002174
Douglas Gregor28019772010-04-05 23:52:57 +00002175 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002176 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002177 CXXIdx->getOnlyLocalDecls(),
2178 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002179 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002180}
2181
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002182unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002183 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002184 CXTranslationUnit_CacheCompletionResults |
2185 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002186}
2187
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002188CXTranslationUnit
2189clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2190 const char *source_filename,
2191 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002192 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002193 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002194 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002195 return clang_parseTranslationUnit(CIdx, source_filename,
2196 command_line_args, num_command_line_args,
2197 unsaved_files, num_unsaved_files,
2198 CXTranslationUnit_DetailedPreprocessingRecord);
2199}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002200
2201struct ParseTranslationUnitInfo {
2202 CXIndex CIdx;
2203 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002204 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002205 int num_command_line_args;
2206 struct CXUnsavedFile *unsaved_files;
2207 unsigned num_unsaved_files;
2208 unsigned options;
2209 CXTranslationUnit result;
2210};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002211static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002212 ParseTranslationUnitInfo *PTUI =
2213 static_cast<ParseTranslationUnitInfo*>(UserData);
2214 CXIndex CIdx = PTUI->CIdx;
2215 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002216 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002217 int num_command_line_args = PTUI->num_command_line_args;
2218 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2219 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2220 unsigned options = PTUI->options;
2221 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002222
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002223 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002224 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002225
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002226 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2227
Douglas Gregor44c181a2010-07-23 00:33:23 +00002228 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002229 bool CompleteTranslationUnit
2230 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002231 bool CacheCodeCompetionResults
2232 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002233 bool CXXPrecompilePreamble
2234 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2235 bool CXXChainedPCH
2236 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002237
Douglas Gregor5352ac02010-01-28 00:27:43 +00002238 // Configure the diagnostics.
2239 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002240 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002241 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2242 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002243
Douglas Gregor4db64a42010-01-23 00:14:00 +00002244 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2245 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002246 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002247 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002248 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002249 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2250 Buffer));
2251 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002252
Douglas Gregorb10daed2010-10-11 16:52:23 +00002253 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002254
Ted Kremenek139ba862009-10-22 00:03:57 +00002255 // The 'source_filename' argument is optional. If the caller does not
2256 // specify it then it is assumed that the source file is specified
2257 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002258 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002259 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002260
2261 // Since the Clang C library is primarily used by batch tools dealing with
2262 // (often very broken) source code, where spell-checking can have a
2263 // significant negative impact on performance (particularly when
2264 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002265 // Only do this if we haven't found a spell-checking-related argument.
2266 bool FoundSpellCheckingArgument = false;
2267 for (int I = 0; I != num_command_line_args; ++I) {
2268 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2269 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2270 FoundSpellCheckingArgument = true;
2271 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002272 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002273 }
2274 if (!FoundSpellCheckingArgument)
2275 Args.push_back("-fno-spell-checking");
2276
2277 Args.insert(Args.end(), command_line_args,
2278 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002279
Douglas Gregor44c181a2010-07-23 00:33:23 +00002280 // Do we need the detailed preprocessing record?
2281 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002282 Args.push_back("-Xclang");
2283 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002284 }
2285
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002286 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002287 llvm::OwningPtr<ASTUnit> Unit(
2288 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2289 Diags,
2290 CXXIdx->getClangResourcesPath(),
2291 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002292 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002293 RemappedFiles.data(),
2294 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002295 PrecompilePreamble,
2296 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002297 CacheCodeCompetionResults,
2298 CXXPrecompilePreamble,
2299 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002300
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002301 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002302 // Make sure to check that 'Unit' is non-NULL.
2303 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2304 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2305 DEnd = Unit->stored_diag_end();
2306 D != DEnd; ++D) {
2307 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2308 CXString Msg = clang_formatDiagnostic(&Diag,
2309 clang_defaultDiagnosticDisplayOptions());
2310 fprintf(stderr, "%s\n", clang_getCString(Msg));
2311 clang_disposeString(Msg);
2312 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002313#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002314 // On Windows, force a flush, since there may be multiple copies of
2315 // stderr and stdout in the file system, all with different buffers
2316 // but writing to the same device.
2317 fflush(stderr);
2318#endif
2319 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002320 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002321
Ted Kremeneka60ed472010-11-16 08:15:36 +00002322 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002323}
2324CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2325 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002326 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002327 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002328 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002329 unsigned num_unsaved_files,
2330 unsigned options) {
2331 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002332 num_command_line_args, unsaved_files,
2333 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002334 llvm::CrashRecoveryContext CRC;
2335
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002336 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002337 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2338 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2339 fprintf(stderr, " 'command_line_args' : [");
2340 for (int i = 0; i != num_command_line_args; ++i) {
2341 if (i)
2342 fprintf(stderr, ", ");
2343 fprintf(stderr, "'%s'", command_line_args[i]);
2344 }
2345 fprintf(stderr, "],\n");
2346 fprintf(stderr, " 'unsaved_files' : [");
2347 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2348 if (i)
2349 fprintf(stderr, ", ");
2350 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2351 unsaved_files[i].Length);
2352 }
2353 fprintf(stderr, "],\n");
2354 fprintf(stderr, " 'options' : %d,\n", options);
2355 fprintf(stderr, "}\n");
2356
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002357 return 0;
2358 }
2359
2360 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002361}
2362
Douglas Gregor19998442010-08-13 15:35:05 +00002363unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2364 return CXSaveTranslationUnit_None;
2365}
2366
2367int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2368 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002369 if (!TU)
2370 return 1;
2371
Ted Kremeneka60ed472010-11-16 08:15:36 +00002372 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002373}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002374
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002375void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002376 if (CTUnit) {
2377 // If the translation unit has been marked as unsafe to free, just discard
2378 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002379 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002380 return;
2381
Ted Kremeneka60ed472010-11-16 08:15:36 +00002382 delete static_cast<ASTUnit *>(CTUnit->TUData);
2383 disposeCXStringPool(CTUnit->StringPool);
2384 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002385 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002386}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002387
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002388unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2389 return CXReparse_None;
2390}
2391
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002392struct ReparseTranslationUnitInfo {
2393 CXTranslationUnit TU;
2394 unsigned num_unsaved_files;
2395 struct CXUnsavedFile *unsaved_files;
2396 unsigned options;
2397 int result;
2398};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002399
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002400static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002401 ReparseTranslationUnitInfo *RTUI =
2402 static_cast<ReparseTranslationUnitInfo*>(UserData);
2403 CXTranslationUnit TU = RTUI->TU;
2404 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2405 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2406 unsigned options = RTUI->options;
2407 (void) options;
2408 RTUI->result = 1;
2409
Douglas Gregorabc563f2010-07-19 21:46:24 +00002410 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002411 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002412
Ted Kremeneka60ed472010-11-16 08:15:36 +00002413 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002414 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002415
2416 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2417 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2418 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2419 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002420 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002421 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2422 Buffer));
2423 }
2424
Douglas Gregor593b0c12010-09-23 18:47:53 +00002425 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2426 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002427}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002428
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002429int clang_reparseTranslationUnit(CXTranslationUnit TU,
2430 unsigned num_unsaved_files,
2431 struct CXUnsavedFile *unsaved_files,
2432 unsigned options) {
2433 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2434 options, 0 };
2435 llvm::CrashRecoveryContext CRC;
2436
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002437 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002438 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002439 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002440 return 1;
2441 }
2442
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002443
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002444 return RTUI.result;
2445}
2446
Douglas Gregordf95a132010-08-09 20:45:32 +00002447
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002448CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002449 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002450 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002451
Ted Kremeneka60ed472010-11-16 08:15:36 +00002452 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002453 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002454}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002455
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002456CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002457 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002458 return Result;
2459}
2460
Ted Kremenekfb480492010-01-13 21:46:36 +00002461} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002462
Ted Kremenekfb480492010-01-13 21:46:36 +00002463//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002464// CXSourceLocation and CXSourceRange Operations.
2465//===----------------------------------------------------------------------===//
2466
Douglas Gregorb9790342010-01-22 21:44:22 +00002467extern "C" {
2468CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002469 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002470 return Result;
2471}
2472
2473unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002474 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2475 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2476 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002477}
2478
2479CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2480 CXFile file,
2481 unsigned line,
2482 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002483 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002484 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002485
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002486 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002487 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002488 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002489 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002490 = CXXUnit->getSourceManager().getLocation(File, line, column);
2491 if (SLoc.isInvalid()) {
2492 if (Logging)
2493 llvm::errs() << "clang_getLocation(\"" << File->getName()
2494 << "\", " << line << ", " << column << ") = invalid\n";
2495 return clang_getNullLocation();
2496 }
2497
2498 if (Logging)
2499 llvm::errs() << "clang_getLocation(\"" << File->getName()
2500 << "\", " << line << ", " << column << ") = "
2501 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002502
2503 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2504}
2505
2506CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2507 CXFile file,
2508 unsigned offset) {
2509 if (!tu || !file)
2510 return clang_getNullLocation();
2511
Ted Kremeneka60ed472010-11-16 08:15:36 +00002512 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002513 SourceLocation Start
2514 = CXXUnit->getSourceManager().getLocation(
2515 static_cast<const FileEntry *>(file),
2516 1, 1);
2517 if (Start.isInvalid()) return clang_getNullLocation();
2518
2519 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2520
2521 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002522
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002523 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002524}
2525
Douglas Gregor5352ac02010-01-28 00:27:43 +00002526CXSourceRange clang_getNullRange() {
2527 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2528 return Result;
2529}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002530
Douglas Gregor5352ac02010-01-28 00:27:43 +00002531CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2532 if (begin.ptr_data[0] != end.ptr_data[0] ||
2533 begin.ptr_data[1] != end.ptr_data[1])
2534 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002535
2536 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002537 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002538 return Result;
2539}
2540
Douglas Gregor46766dc2010-01-26 19:19:08 +00002541void clang_getInstantiationLocation(CXSourceLocation location,
2542 CXFile *file,
2543 unsigned *line,
2544 unsigned *column,
2545 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002546 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2547
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002548 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002549 if (file)
2550 *file = 0;
2551 if (line)
2552 *line = 0;
2553 if (column)
2554 *column = 0;
2555 if (offset)
2556 *offset = 0;
2557 return;
2558 }
2559
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002560 const SourceManager &SM =
2561 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002562 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002563
2564 if (file)
2565 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2566 if (line)
2567 *line = SM.getInstantiationLineNumber(InstLoc);
2568 if (column)
2569 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002570 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002571 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002572}
2573
Douglas Gregora9b06d42010-11-09 06:24:54 +00002574void clang_getSpellingLocation(CXSourceLocation location,
2575 CXFile *file,
2576 unsigned *line,
2577 unsigned *column,
2578 unsigned *offset) {
2579 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2580
2581 if (!location.ptr_data[0] || Loc.isInvalid()) {
2582 if (file)
2583 *file = 0;
2584 if (line)
2585 *line = 0;
2586 if (column)
2587 *column = 0;
2588 if (offset)
2589 *offset = 0;
2590 return;
2591 }
2592
2593 const SourceManager &SM =
2594 *static_cast<const SourceManager*>(location.ptr_data[0]);
2595 SourceLocation SpellLoc = Loc;
2596 if (SpellLoc.isMacroID()) {
2597 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2598 if (SimpleSpellingLoc.isFileID() &&
2599 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2600 SpellLoc = SimpleSpellingLoc;
2601 else
2602 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2603 }
2604
2605 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2606 FileID FID = LocInfo.first;
2607 unsigned FileOffset = LocInfo.second;
2608
2609 if (file)
2610 *file = (void *)SM.getFileEntryForID(FID);
2611 if (line)
2612 *line = SM.getLineNumber(FID, FileOffset);
2613 if (column)
2614 *column = SM.getColumnNumber(FID, FileOffset);
2615 if (offset)
2616 *offset = FileOffset;
2617}
2618
Douglas Gregor1db19de2010-01-19 21:36:55 +00002619CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002620 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002621 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002622 return Result;
2623}
2624
2625CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002626 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002627 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002628 return Result;
2629}
2630
Douglas Gregorb9790342010-01-22 21:44:22 +00002631} // end: extern "C"
2632
Douglas Gregor1db19de2010-01-19 21:36:55 +00002633//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002634// CXFile Operations.
2635//===----------------------------------------------------------------------===//
2636
2637extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002638CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002639 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002640 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002641
Steve Naroff88145032009-10-27 14:35:18 +00002642 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002643 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002644}
2645
2646time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002647 if (!SFile)
2648 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002649
Steve Naroff88145032009-10-27 14:35:18 +00002650 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2651 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002652}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002653
Douglas Gregorb9790342010-01-22 21:44:22 +00002654CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2655 if (!tu)
2656 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002657
Ted Kremeneka60ed472010-11-16 08:15:36 +00002658 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002659
Douglas Gregorb9790342010-01-22 21:44:22 +00002660 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002661 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002662}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002663
Ted Kremenekfb480492010-01-13 21:46:36 +00002664} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002665
Ted Kremenekfb480492010-01-13 21:46:36 +00002666//===----------------------------------------------------------------------===//
2667// CXCursor Operations.
2668//===----------------------------------------------------------------------===//
2669
Ted Kremenekfb480492010-01-13 21:46:36 +00002670static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002671 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2672 return getDeclFromExpr(CE->getSubExpr());
2673
Ted Kremenekfb480492010-01-13 21:46:36 +00002674 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2675 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002676 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2677 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002678 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2679 return ME->getMemberDecl();
2680 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2681 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002682 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002683 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002684
Ted Kremenekfb480492010-01-13 21:46:36 +00002685 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2686 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002687 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2688 if (!CE->isElidable())
2689 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002690 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2691 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002692
Douglas Gregordb1314e2010-10-01 21:11:22 +00002693 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2694 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002695 if (SubstNonTypeTemplateParmPackExpr *NTTP
2696 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2697 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002698 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2699 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2700 isa<ParmVarDecl>(SizeOfPack->getPack()))
2701 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002702
Ted Kremenekfb480492010-01-13 21:46:36 +00002703 return 0;
2704}
2705
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002706static SourceLocation getLocationFromExpr(Expr *E) {
2707 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2708 return /*FIXME:*/Msg->getLeftLoc();
2709 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2710 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002711 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2712 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002713 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2714 return Member->getMemberLoc();
2715 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2716 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002717 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2718 return SizeOfPack->getPackLoc();
2719
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002720 return E->getLocStart();
2721}
2722
Ted Kremenekfb480492010-01-13 21:46:36 +00002723extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002724
2725unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002726 CXCursorVisitor visitor,
2727 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002728 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2729 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002730 return CursorVis.VisitChildren(parent);
2731}
2732
David Chisnall3387c652010-11-03 14:12:26 +00002733#ifndef __has_feature
2734#define __has_feature(x) 0
2735#endif
2736#if __has_feature(blocks)
2737typedef enum CXChildVisitResult
2738 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2739
2740static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2741 CXClientData client_data) {
2742 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2743 return block(cursor, parent);
2744}
2745#else
2746// If we are compiled with a compiler that doesn't have native blocks support,
2747// define and call the block manually, so the
2748typedef struct _CXChildVisitResult
2749{
2750 void *isa;
2751 int flags;
2752 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002753 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2754 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002755} *CXCursorVisitorBlock;
2756
2757static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2758 CXClientData client_data) {
2759 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2760 return block->invoke(block, cursor, parent);
2761}
2762#endif
2763
2764
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002765unsigned clang_visitChildrenWithBlock(CXCursor parent,
2766 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002767 return clang_visitChildren(parent, visitWithBlock, block);
2768}
2769
Douglas Gregor78205d42010-01-20 21:45:58 +00002770static CXString getDeclSpelling(Decl *D) {
2771 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002772 if (!ND) {
2773 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2774 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2775 return createCXString(Property->getIdentifier()->getName());
2776
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002777 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002778 }
2779
Douglas Gregor78205d42010-01-20 21:45:58 +00002780 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002781 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002782
Douglas Gregor78205d42010-01-20 21:45:58 +00002783 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2784 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2785 // and returns different names. NamedDecl returns the class name and
2786 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002787 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002788
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002789 if (isa<UsingDirectiveDecl>(D))
2790 return createCXString("");
2791
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002792 llvm::SmallString<1024> S;
2793 llvm::raw_svector_ostream os(S);
2794 ND->printName(os);
2795
2796 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002797}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002798
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002799CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002800 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002801 return clang_getTranslationUnitSpelling(
2802 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002803
Steve Narofff334b4e2009-09-02 18:26:48 +00002804 if (clang_isReference(C.kind)) {
2805 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002806 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002807 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002808 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002809 }
2810 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002811 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002812 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002813 }
2814 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002815 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002816 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002817 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002818 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002819 case CXCursor_CXXBaseSpecifier: {
2820 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2821 return createCXString(B->getType().getAsString());
2822 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002823 case CXCursor_TypeRef: {
2824 TypeDecl *Type = getCursorTypeRef(C).first;
2825 assert(Type && "Missing type decl");
2826
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002827 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2828 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002829 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002830 case CXCursor_TemplateRef: {
2831 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002832 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002833
2834 return createCXString(Template->getNameAsString());
2835 }
Douglas Gregor69319002010-08-31 23:48:11 +00002836
2837 case CXCursor_NamespaceRef: {
2838 NamedDecl *NS = getCursorNamespaceRef(C).first;
2839 assert(NS && "Missing namespace decl");
2840
2841 return createCXString(NS->getNameAsString());
2842 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002843
Douglas Gregora67e03f2010-09-09 21:42:20 +00002844 case CXCursor_MemberRef: {
2845 FieldDecl *Field = getCursorMemberRef(C).first;
2846 assert(Field && "Missing member decl");
2847
2848 return createCXString(Field->getNameAsString());
2849 }
2850
Douglas Gregor36897b02010-09-10 00:22:18 +00002851 case CXCursor_LabelRef: {
2852 LabelStmt *Label = getCursorLabelRef(C).first;
2853 assert(Label && "Missing label");
2854
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002855 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002856 }
2857
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002858 case CXCursor_OverloadedDeclRef: {
2859 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2860 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2861 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2862 return createCXString(ND->getNameAsString());
2863 return createCXString("");
2864 }
2865 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2866 return createCXString(E->getName().getAsString());
2867 OverloadedTemplateStorage *Ovl
2868 = Storage.get<OverloadedTemplateStorage*>();
2869 if (Ovl->size() == 0)
2870 return createCXString("");
2871 return createCXString((*Ovl->begin())->getNameAsString());
2872 }
2873
Daniel Dunbaracca7252009-11-30 20:42:49 +00002874 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002875 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002876 }
2877 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002878
2879 if (clang_isExpression(C.kind)) {
2880 Decl *D = getDeclFromExpr(getCursorExpr(C));
2881 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002882 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002883 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002884 }
2885
Douglas Gregor36897b02010-09-10 00:22:18 +00002886 if (clang_isStatement(C.kind)) {
2887 Stmt *S = getCursorStmt(C);
2888 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002889 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002890
2891 return createCXString("");
2892 }
2893
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002894 if (C.kind == CXCursor_MacroInstantiation)
2895 return createCXString(getCursorMacroInstantiation(C)->getName()
2896 ->getNameStart());
2897
Douglas Gregor572feb22010-03-18 18:04:21 +00002898 if (C.kind == CXCursor_MacroDefinition)
2899 return createCXString(getCursorMacroDefinition(C)->getName()
2900 ->getNameStart());
2901
Douglas Gregorecdcb882010-10-20 22:00:55 +00002902 if (C.kind == CXCursor_InclusionDirective)
2903 return createCXString(getCursorInclusionDirective(C)->getFileName());
2904
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002905 if (clang_isDeclaration(C.kind))
2906 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002907
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002908 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002909}
2910
Douglas Gregor358559d2010-10-02 22:49:11 +00002911CXString clang_getCursorDisplayName(CXCursor C) {
2912 if (!clang_isDeclaration(C.kind))
2913 return clang_getCursorSpelling(C);
2914
2915 Decl *D = getCursorDecl(C);
2916 if (!D)
2917 return createCXString("");
2918
2919 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2920 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2921 D = FunTmpl->getTemplatedDecl();
2922
2923 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2924 llvm::SmallString<64> Str;
2925 llvm::raw_svector_ostream OS(Str);
2926 OS << Function->getNameAsString();
2927 if (Function->getPrimaryTemplate())
2928 OS << "<>";
2929 OS << "(";
2930 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2931 if (I)
2932 OS << ", ";
2933 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2934 }
2935
2936 if (Function->isVariadic()) {
2937 if (Function->getNumParams())
2938 OS << ", ";
2939 OS << "...";
2940 }
2941 OS << ")";
2942 return createCXString(OS.str());
2943 }
2944
2945 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2946 llvm::SmallString<64> Str;
2947 llvm::raw_svector_ostream OS(Str);
2948 OS << ClassTemplate->getNameAsString();
2949 OS << "<";
2950 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2951 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2952 if (I)
2953 OS << ", ";
2954
2955 NamedDecl *Param = Params->getParam(I);
2956 if (Param->getIdentifier()) {
2957 OS << Param->getIdentifier()->getName();
2958 continue;
2959 }
2960
2961 // There is no parameter name, which makes this tricky. Try to come up
2962 // with something useful that isn't too long.
2963 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2964 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2965 else if (NonTypeTemplateParmDecl *NTTP
2966 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2967 OS << NTTP->getType().getAsString(Policy);
2968 else
2969 OS << "template<...> class";
2970 }
2971
2972 OS << ">";
2973 return createCXString(OS.str());
2974 }
2975
2976 if (ClassTemplateSpecializationDecl *ClassSpec
2977 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2978 // If the type was explicitly written, use that.
2979 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2980 return createCXString(TSInfo->getType().getAsString(Policy));
2981
2982 llvm::SmallString<64> Str;
2983 llvm::raw_svector_ostream OS(Str);
2984 OS << ClassSpec->getNameAsString();
2985 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002986 ClassSpec->getTemplateArgs().data(),
2987 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002988 Policy);
2989 return createCXString(OS.str());
2990 }
2991
2992 return clang_getCursorSpelling(C);
2993}
2994
Ted Kremeneke68fff62010-02-17 00:41:32 +00002995CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002996 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002997 case CXCursor_FunctionDecl:
2998 return createCXString("FunctionDecl");
2999 case CXCursor_TypedefDecl:
3000 return createCXString("TypedefDecl");
3001 case CXCursor_EnumDecl:
3002 return createCXString("EnumDecl");
3003 case CXCursor_EnumConstantDecl:
3004 return createCXString("EnumConstantDecl");
3005 case CXCursor_StructDecl:
3006 return createCXString("StructDecl");
3007 case CXCursor_UnionDecl:
3008 return createCXString("UnionDecl");
3009 case CXCursor_ClassDecl:
3010 return createCXString("ClassDecl");
3011 case CXCursor_FieldDecl:
3012 return createCXString("FieldDecl");
3013 case CXCursor_VarDecl:
3014 return createCXString("VarDecl");
3015 case CXCursor_ParmDecl:
3016 return createCXString("ParmDecl");
3017 case CXCursor_ObjCInterfaceDecl:
3018 return createCXString("ObjCInterfaceDecl");
3019 case CXCursor_ObjCCategoryDecl:
3020 return createCXString("ObjCCategoryDecl");
3021 case CXCursor_ObjCProtocolDecl:
3022 return createCXString("ObjCProtocolDecl");
3023 case CXCursor_ObjCPropertyDecl:
3024 return createCXString("ObjCPropertyDecl");
3025 case CXCursor_ObjCIvarDecl:
3026 return createCXString("ObjCIvarDecl");
3027 case CXCursor_ObjCInstanceMethodDecl:
3028 return createCXString("ObjCInstanceMethodDecl");
3029 case CXCursor_ObjCClassMethodDecl:
3030 return createCXString("ObjCClassMethodDecl");
3031 case CXCursor_ObjCImplementationDecl:
3032 return createCXString("ObjCImplementationDecl");
3033 case CXCursor_ObjCCategoryImplDecl:
3034 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003035 case CXCursor_CXXMethod:
3036 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003037 case CXCursor_UnexposedDecl:
3038 return createCXString("UnexposedDecl");
3039 case CXCursor_ObjCSuperClassRef:
3040 return createCXString("ObjCSuperClassRef");
3041 case CXCursor_ObjCProtocolRef:
3042 return createCXString("ObjCProtocolRef");
3043 case CXCursor_ObjCClassRef:
3044 return createCXString("ObjCClassRef");
3045 case CXCursor_TypeRef:
3046 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003047 case CXCursor_TemplateRef:
3048 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003049 case CXCursor_NamespaceRef:
3050 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003051 case CXCursor_MemberRef:
3052 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003053 case CXCursor_LabelRef:
3054 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003055 case CXCursor_OverloadedDeclRef:
3056 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003057 case CXCursor_UnexposedExpr:
3058 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003059 case CXCursor_BlockExpr:
3060 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003061 case CXCursor_DeclRefExpr:
3062 return createCXString("DeclRefExpr");
3063 case CXCursor_MemberRefExpr:
3064 return createCXString("MemberRefExpr");
3065 case CXCursor_CallExpr:
3066 return createCXString("CallExpr");
3067 case CXCursor_ObjCMessageExpr:
3068 return createCXString("ObjCMessageExpr");
3069 case CXCursor_UnexposedStmt:
3070 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003071 case CXCursor_LabelStmt:
3072 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003073 case CXCursor_InvalidFile:
3074 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003075 case CXCursor_InvalidCode:
3076 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003077 case CXCursor_NoDeclFound:
3078 return createCXString("NoDeclFound");
3079 case CXCursor_NotImplemented:
3080 return createCXString("NotImplemented");
3081 case CXCursor_TranslationUnit:
3082 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003083 case CXCursor_UnexposedAttr:
3084 return createCXString("UnexposedAttr");
3085 case CXCursor_IBActionAttr:
3086 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003087 case CXCursor_IBOutletAttr:
3088 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003089 case CXCursor_IBOutletCollectionAttr:
3090 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003091 case CXCursor_PreprocessingDirective:
3092 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003093 case CXCursor_MacroDefinition:
3094 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003095 case CXCursor_MacroInstantiation:
3096 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003097 case CXCursor_InclusionDirective:
3098 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003099 case CXCursor_Namespace:
3100 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003101 case CXCursor_LinkageSpec:
3102 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003103 case CXCursor_CXXBaseSpecifier:
3104 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003105 case CXCursor_Constructor:
3106 return createCXString("CXXConstructor");
3107 case CXCursor_Destructor:
3108 return createCXString("CXXDestructor");
3109 case CXCursor_ConversionFunction:
3110 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003111 case CXCursor_TemplateTypeParameter:
3112 return createCXString("TemplateTypeParameter");
3113 case CXCursor_NonTypeTemplateParameter:
3114 return createCXString("NonTypeTemplateParameter");
3115 case CXCursor_TemplateTemplateParameter:
3116 return createCXString("TemplateTemplateParameter");
3117 case CXCursor_FunctionTemplate:
3118 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003119 case CXCursor_ClassTemplate:
3120 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003121 case CXCursor_ClassTemplatePartialSpecialization:
3122 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003123 case CXCursor_NamespaceAlias:
3124 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003125 case CXCursor_UsingDirective:
3126 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003127 case CXCursor_UsingDeclaration:
3128 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003129 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003130
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003131 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003132 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003133}
Steve Naroff89922f82009-08-31 00:59:03 +00003134
Ted Kremeneke68fff62010-02-17 00:41:32 +00003135enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3136 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003137 CXClientData client_data) {
3138 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003139
3140 // If our current best cursor is the construction of a temporary object,
3141 // don't replace that cursor with a type reference, because we want
3142 // clang_getCursor() to point at the constructor.
3143 if (clang_isExpression(BestCursor->kind) &&
3144 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3145 cursor.kind == CXCursor_TypeRef)
3146 return CXChildVisit_Recurse;
3147
Douglas Gregor85fe1562010-12-10 07:23:11 +00003148 // Don't override a preprocessing cursor with another preprocessing
3149 // cursor; we want the outermost preprocessing cursor.
3150 if (clang_isPreprocessing(cursor.kind) &&
3151 clang_isPreprocessing(BestCursor->kind))
3152 return CXChildVisit_Recurse;
3153
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003154 *BestCursor = cursor;
3155 return CXChildVisit_Recurse;
3156}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003157
Douglas Gregorb9790342010-01-22 21:44:22 +00003158CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3159 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003160 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003161
Ted Kremeneka60ed472010-11-16 08:15:36 +00003162 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003163 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3164
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003165 // Translate the given source location to make it point at the beginning of
3166 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003167 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003168
3169 // Guard against an invalid SourceLocation, or we may assert in one
3170 // of the following calls.
3171 if (SLoc.isInvalid())
3172 return clang_getNullCursor();
3173
Douglas Gregor40749ee2010-11-03 00:35:38 +00003174 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003175 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3176 CXXUnit->getASTContext().getLangOptions());
3177
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003178 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3179 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003180 // FIXME: Would be great to have a "hint" cursor, then walk from that
3181 // hint cursor upward until we find a cursor whose source range encloses
3182 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003183 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3184 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003185 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003186 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003187 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003188
3189 if (Logging) {
3190 CXFile SearchFile;
3191 unsigned SearchLine, SearchColumn;
3192 CXFile ResultFile;
3193 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003194 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3195 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003196 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3197
3198 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3199 0);
3200 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3201 &ResultColumn, 0);
3202 SearchFileName = clang_getFileName(SearchFile);
3203 ResultFileName = clang_getFileName(ResultFile);
3204 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003205 USR = clang_getCursorUSR(Result);
3206 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003207 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3208 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003209 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3210 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003211 clang_disposeString(SearchFileName);
3212 clang_disposeString(ResultFileName);
3213 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003214 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003215
3216 CXCursor Definition = clang_getCursorDefinition(Result);
3217 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3218 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3219 CXString DefinitionKindSpelling
3220 = clang_getCursorKindSpelling(Definition.kind);
3221 CXFile DefinitionFile;
3222 unsigned DefinitionLine, DefinitionColumn;
3223 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3224 &DefinitionLine, &DefinitionColumn, 0);
3225 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3226 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3227 clang_getCString(DefinitionKindSpelling),
3228 clang_getCString(DefinitionFileName),
3229 DefinitionLine, DefinitionColumn);
3230 clang_disposeString(DefinitionFileName);
3231 clang_disposeString(DefinitionKindSpelling);
3232 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003233 }
3234
Ted Kremeneke68fff62010-02-17 00:41:32 +00003235 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003236}
3237
Ted Kremenek73885552009-11-17 19:28:59 +00003238CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003239 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003240}
3241
3242unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003243 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003244}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003245
Douglas Gregor9ce55842010-11-20 00:09:34 +00003246unsigned clang_hashCursor(CXCursor C) {
3247 unsigned Index = 0;
3248 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3249 Index = 1;
3250
3251 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3252 std::make_pair(C.kind, C.data[Index]));
3253}
3254
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003255unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003256 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3257}
3258
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003259unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003260 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3261}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003262
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003263unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003264 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3265}
3266
Douglas Gregor97b98722010-01-19 23:20:36 +00003267unsigned clang_isExpression(enum CXCursorKind K) {
3268 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3269}
3270
3271unsigned clang_isStatement(enum CXCursorKind K) {
3272 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3273}
3274
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003275unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3276 return K == CXCursor_TranslationUnit;
3277}
3278
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003279unsigned clang_isPreprocessing(enum CXCursorKind K) {
3280 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3281}
3282
Ted Kremenekad6eff62010-03-08 21:17:29 +00003283unsigned clang_isUnexposed(enum CXCursorKind K) {
3284 switch (K) {
3285 case CXCursor_UnexposedDecl:
3286 case CXCursor_UnexposedExpr:
3287 case CXCursor_UnexposedStmt:
3288 case CXCursor_UnexposedAttr:
3289 return true;
3290 default:
3291 return false;
3292 }
3293}
3294
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003295CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003296 return C.kind;
3297}
3298
Douglas Gregor98258af2010-01-18 22:46:11 +00003299CXSourceLocation clang_getCursorLocation(CXCursor C) {
3300 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003301 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003302 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003303 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3304 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003305 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003306 }
3307
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003308 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003309 std::pair<ObjCProtocolDecl *, SourceLocation> P
3310 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003311 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003312 }
3313
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003314 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003315 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3316 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003317 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003318 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003319
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003320 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003321 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003322 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003323 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003324
3325 case CXCursor_TemplateRef: {
3326 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3327 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3328 }
3329
Douglas Gregor69319002010-08-31 23:48:11 +00003330 case CXCursor_NamespaceRef: {
3331 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3332 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3333 }
3334
Douglas Gregora67e03f2010-09-09 21:42:20 +00003335 case CXCursor_MemberRef: {
3336 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3337 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3338 }
3339
Ted Kremenek3064ef92010-08-27 21:34:58 +00003340 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003341 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3342 if (!BaseSpec)
3343 return clang_getNullLocation();
3344
3345 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3346 return cxloc::translateSourceLocation(getCursorContext(C),
3347 TSInfo->getTypeLoc().getBeginLoc());
3348
3349 return cxloc::translateSourceLocation(getCursorContext(C),
3350 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003351 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003352
Douglas Gregor36897b02010-09-10 00:22:18 +00003353 case CXCursor_LabelRef: {
3354 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3355 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3356 }
3357
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003358 case CXCursor_OverloadedDeclRef:
3359 return cxloc::translateSourceLocation(getCursorContext(C),
3360 getCursorOverloadedDeclRef(C).second);
3361
Douglas Gregorf46034a2010-01-18 23:41:10 +00003362 default:
3363 // FIXME: Need a way to enumerate all non-reference cases.
3364 llvm_unreachable("Missed a reference kind");
3365 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003366 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003367
3368 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003369 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003370 getLocationFromExpr(getCursorExpr(C)));
3371
Douglas Gregor36897b02010-09-10 00:22:18 +00003372 if (clang_isStatement(C.kind))
3373 return cxloc::translateSourceLocation(getCursorContext(C),
3374 getCursorStmt(C)->getLocStart());
3375
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003376 if (C.kind == CXCursor_PreprocessingDirective) {
3377 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3378 return cxloc::translateSourceLocation(getCursorContext(C), L);
3379 }
Douglas Gregor48072312010-03-18 15:23:44 +00003380
3381 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003382 SourceLocation L
3383 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003384 return cxloc::translateSourceLocation(getCursorContext(C), L);
3385 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003386
3387 if (C.kind == CXCursor_MacroDefinition) {
3388 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3389 return cxloc::translateSourceLocation(getCursorContext(C), L);
3390 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003391
3392 if (C.kind == CXCursor_InclusionDirective) {
3393 SourceLocation L
3394 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3395 return cxloc::translateSourceLocation(getCursorContext(C), L);
3396 }
3397
Ted Kremenek9a700d22010-05-12 06:16:13 +00003398 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003399 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003400
Douglas Gregorf46034a2010-01-18 23:41:10 +00003401 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003402 SourceLocation Loc = D->getLocation();
3403 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3404 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003405 // FIXME: Multiple variables declared in a single declaration
3406 // currently lack the information needed to correctly determine their
3407 // ranges when accounting for the type-specifier. We use context
3408 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3409 // and if so, whether it is the first decl.
3410 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3411 if (!cxcursor::isFirstInDeclGroup(C))
3412 Loc = VD->getLocation();
3413 }
3414
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003415 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003416}
Douglas Gregora7bde202010-01-19 00:34:46 +00003417
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003418} // end extern "C"
3419
3420static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003421 if (clang_isReference(C.kind)) {
3422 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003423 case CXCursor_ObjCSuperClassRef:
3424 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003425
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003426 case CXCursor_ObjCProtocolRef:
3427 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003428
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003429 case CXCursor_ObjCClassRef:
3430 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003431
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003432 case CXCursor_TypeRef:
3433 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003434
3435 case CXCursor_TemplateRef:
3436 return getCursorTemplateRef(C).second;
3437
Douglas Gregor69319002010-08-31 23:48:11 +00003438 case CXCursor_NamespaceRef:
3439 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003440
3441 case CXCursor_MemberRef:
3442 return getCursorMemberRef(C).second;
3443
Ted Kremenek3064ef92010-08-27 21:34:58 +00003444 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003445 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003446
Douglas Gregor36897b02010-09-10 00:22:18 +00003447 case CXCursor_LabelRef:
3448 return getCursorLabelRef(C).second;
3449
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003450 case CXCursor_OverloadedDeclRef:
3451 return getCursorOverloadedDeclRef(C).second;
3452
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003453 default:
3454 // FIXME: Need a way to enumerate all non-reference cases.
3455 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003456 }
3457 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003458
3459 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003460 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003461
3462 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003463 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003464
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003465 if (C.kind == CXCursor_PreprocessingDirective)
3466 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003467
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003468 if (C.kind == CXCursor_MacroInstantiation)
3469 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003470
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003471 if (C.kind == CXCursor_MacroDefinition)
3472 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003473
3474 if (C.kind == CXCursor_InclusionDirective)
3475 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3476
Ted Kremenek007a7c92010-11-01 23:26:51 +00003477 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3478 Decl *D = cxcursor::getCursorDecl(C);
3479 SourceRange R = D->getSourceRange();
3480 // FIXME: Multiple variables declared in a single declaration
3481 // currently lack the information needed to correctly determine their
3482 // ranges when accounting for the type-specifier. We use context
3483 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3484 // and if so, whether it is the first decl.
3485 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3486 if (!cxcursor::isFirstInDeclGroup(C))
3487 R.setBegin(VD->getLocation());
3488 }
3489 return R;
3490 }
Douglas Gregor66537982010-11-17 17:14:07 +00003491 return SourceRange();
3492}
3493
3494/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3495/// the decl-specifier-seq for declarations.
3496static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3497 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3498 Decl *D = cxcursor::getCursorDecl(C);
3499 SourceRange R = D->getSourceRange();
3500
3501 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3502 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3503 TypeLoc TL = TI->getTypeLoc();
3504 SourceLocation TLoc = TL.getSourceRange().getBegin();
3505 if (TLoc.isValid() && R.getBegin().isValid() &&
3506 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3507 R.setBegin(TLoc);
3508 }
3509
3510 // FIXME: Multiple variables declared in a single declaration
3511 // currently lack the information needed to correctly determine their
3512 // ranges when accounting for the type-specifier. We use context
3513 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3514 // and if so, whether it is the first decl.
3515 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3516 if (!cxcursor::isFirstInDeclGroup(C))
3517 R.setBegin(VD->getLocation());
3518 }
3519 }
3520
3521 return R;
3522 }
3523
3524 return getRawCursorExtent(C);
3525}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003526
3527extern "C" {
3528
3529CXSourceRange clang_getCursorExtent(CXCursor C) {
3530 SourceRange R = getRawCursorExtent(C);
3531 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003532 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003533
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003534 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003535}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003536
3537CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003538 if (clang_isInvalid(C.kind))
3539 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003540
Ted Kremeneka60ed472010-11-16 08:15:36 +00003541 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003542 if (clang_isDeclaration(C.kind)) {
3543 Decl *D = getCursorDecl(C);
3544 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003545 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003546 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003547 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003548 if (ObjCForwardProtocolDecl *Protocols
3549 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003550 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003551 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3552 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3553 return MakeCXCursor(Property, tu);
3554
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003555 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003556 }
3557
Douglas Gregor97b98722010-01-19 23:20:36 +00003558 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003559 Expr *E = getCursorExpr(C);
3560 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003561 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003562 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003563
3564 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003565 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003566
Douglas Gregor97b98722010-01-19 23:20:36 +00003567 return clang_getNullCursor();
3568 }
3569
Douglas Gregor36897b02010-09-10 00:22:18 +00003570 if (clang_isStatement(C.kind)) {
3571 Stmt *S = getCursorStmt(C);
3572 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003573 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003574
3575 return clang_getNullCursor();
3576 }
3577
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003578 if (C.kind == CXCursor_MacroInstantiation) {
3579 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003580 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003581 }
3582
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003583 if (!clang_isReference(C.kind))
3584 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003586 switch (C.kind) {
3587 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003588 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003589
3590 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003591 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003592
3593 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003594 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003595
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003596 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003597 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003598
3599 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003600 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003601
Douglas Gregor69319002010-08-31 23:48:11 +00003602 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003603 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003604
Douglas Gregora67e03f2010-09-09 21:42:20 +00003605 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003606 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003607
Ted Kremenek3064ef92010-08-27 21:34:58 +00003608 case CXCursor_CXXBaseSpecifier: {
3609 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3610 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003611 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003612 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003613
Douglas Gregor36897b02010-09-10 00:22:18 +00003614 case CXCursor_LabelRef:
3615 // FIXME: We end up faking the "parent" declaration here because we
3616 // don't want to make CXCursor larger.
3617 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003618 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3619 .getTranslationUnitDecl(),
3620 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003621
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003622 case CXCursor_OverloadedDeclRef:
3623 return C;
3624
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003625 default:
3626 // We would prefer to enumerate all non-reference cursor kinds here.
3627 llvm_unreachable("Unhandled reference cursor kind");
3628 break;
3629 }
3630 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003631
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003632 return clang_getNullCursor();
3633}
3634
Douglas Gregorb6998662010-01-19 19:34:47 +00003635CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003636 if (clang_isInvalid(C.kind))
3637 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003638
Ted Kremeneka60ed472010-11-16 08:15:36 +00003639 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003640
Douglas Gregorb6998662010-01-19 19:34:47 +00003641 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003642 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003643 C = clang_getCursorReferenced(C);
3644 WasReference = true;
3645 }
3646
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003647 if (C.kind == CXCursor_MacroInstantiation)
3648 return clang_getCursorReferenced(C);
3649
Douglas Gregorb6998662010-01-19 19:34:47 +00003650 if (!clang_isDeclaration(C.kind))
3651 return clang_getNullCursor();
3652
3653 Decl *D = getCursorDecl(C);
3654 if (!D)
3655 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003656
Douglas Gregorb6998662010-01-19 19:34:47 +00003657 switch (D->getKind()) {
3658 // Declaration kinds that don't really separate the notions of
3659 // declaration and definition.
3660 case Decl::Namespace:
3661 case Decl::Typedef:
3662 case Decl::TemplateTypeParm:
3663 case Decl::EnumConstant:
3664 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003665 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003666 case Decl::ObjCIvar:
3667 case Decl::ObjCAtDefsField:
3668 case Decl::ImplicitParam:
3669 case Decl::ParmVar:
3670 case Decl::NonTypeTemplateParm:
3671 case Decl::TemplateTemplateParm:
3672 case Decl::ObjCCategoryImpl:
3673 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003674 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003675 case Decl::LinkageSpec:
3676 case Decl::ObjCPropertyImpl:
3677 case Decl::FileScopeAsm:
3678 case Decl::StaticAssert:
3679 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003680 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003681 return C;
3682
3683 // Declaration kinds that don't make any sense here, but are
3684 // nonetheless harmless.
3685 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003686 break;
3687
3688 // Declaration kinds for which the definition is not resolvable.
3689 case Decl::UnresolvedUsingTypename:
3690 case Decl::UnresolvedUsingValue:
3691 break;
3692
3693 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003694 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003695 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003696
3697 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003698 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003699
3700 case Decl::Enum:
3701 case Decl::Record:
3702 case Decl::CXXRecord:
3703 case Decl::ClassTemplateSpecialization:
3704 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003705 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003706 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003707 return clang_getNullCursor();
3708
3709 case Decl::Function:
3710 case Decl::CXXMethod:
3711 case Decl::CXXConstructor:
3712 case Decl::CXXDestructor:
3713 case Decl::CXXConversion: {
3714 const FunctionDecl *Def = 0;
3715 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003716 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003717 return clang_getNullCursor();
3718 }
3719
3720 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003721 // Ask the variable if it has a definition.
3722 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003723 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003724 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003725 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003726
Douglas Gregorb6998662010-01-19 19:34:47 +00003727 case Decl::FunctionTemplate: {
3728 const FunctionDecl *Def = 0;
3729 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003730 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003731 return clang_getNullCursor();
3732 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003733
Douglas Gregorb6998662010-01-19 19:34:47 +00003734 case Decl::ClassTemplate: {
3735 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003736 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003737 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003738 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003739 return clang_getNullCursor();
3740 }
3741
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003742 case Decl::Using:
3743 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003744 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003745
3746 case Decl::UsingShadow:
3747 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003748 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003749 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003750
3751 case Decl::ObjCMethod: {
3752 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3753 if (Method->isThisDeclarationADefinition())
3754 return C;
3755
3756 // Dig out the method definition in the associated
3757 // @implementation, if we have it.
3758 // FIXME: The ASTs should make finding the definition easier.
3759 if (ObjCInterfaceDecl *Class
3760 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3761 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3762 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3763 Method->isInstanceMethod()))
3764 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003765 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003766
3767 return clang_getNullCursor();
3768 }
3769
3770 case Decl::ObjCCategory:
3771 if (ObjCCategoryImplDecl *Impl
3772 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003773 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003774 return clang_getNullCursor();
3775
3776 case Decl::ObjCProtocol:
3777 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3778 return C;
3779 return clang_getNullCursor();
3780
3781 case Decl::ObjCInterface:
3782 // There are two notions of a "definition" for an Objective-C
3783 // class: the interface and its implementation. When we resolved a
3784 // reference to an Objective-C class, produce the @interface as
3785 // the definition; when we were provided with the interface,
3786 // produce the @implementation as the definition.
3787 if (WasReference) {
3788 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3789 return C;
3790 } else if (ObjCImplementationDecl *Impl
3791 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003792 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003793 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003794
Douglas Gregorb6998662010-01-19 19:34:47 +00003795 case Decl::ObjCProperty:
3796 // FIXME: We don't really know where to find the
3797 // ObjCPropertyImplDecls that implement this property.
3798 return clang_getNullCursor();
3799
3800 case Decl::ObjCCompatibleAlias:
3801 if (ObjCInterfaceDecl *Class
3802 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3803 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003804 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003805
Douglas Gregorb6998662010-01-19 19:34:47 +00003806 return clang_getNullCursor();
3807
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003808 case Decl::ObjCForwardProtocol:
3809 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003810 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003811
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003812 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003813 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003814 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003815
3816 case Decl::Friend:
3817 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003818 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003819 return clang_getNullCursor();
3820
3821 case Decl::FriendTemplate:
3822 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003823 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003824 return clang_getNullCursor();
3825 }
3826
3827 return clang_getNullCursor();
3828}
3829
3830unsigned clang_isCursorDefinition(CXCursor C) {
3831 if (!clang_isDeclaration(C.kind))
3832 return 0;
3833
3834 return clang_getCursorDefinition(C) == C;
3835}
3836
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003837CXCursor clang_getCanonicalCursor(CXCursor C) {
3838 if (!clang_isDeclaration(C.kind))
3839 return C;
3840
3841 if (Decl *D = getCursorDecl(C))
3842 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3843
3844 return C;
3845}
3846
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003847unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003848 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003849 return 0;
3850
3851 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3852 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3853 return E->getNumDecls();
3854
3855 if (OverloadedTemplateStorage *S
3856 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3857 return S->size();
3858
3859 Decl *D = Storage.get<Decl*>();
3860 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003861 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003862 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3863 return Classes->size();
3864 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3865 return Protocols->protocol_size();
3866
3867 return 0;
3868}
3869
3870CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003871 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003872 return clang_getNullCursor();
3873
3874 if (index >= clang_getNumOverloadedDecls(cursor))
3875 return clang_getNullCursor();
3876
Ted Kremeneka60ed472010-11-16 08:15:36 +00003877 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003878 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3879 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003880 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003881
3882 if (OverloadedTemplateStorage *S
3883 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003884 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003885
3886 Decl *D = Storage.get<Decl*>();
3887 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3888 // FIXME: This is, unfortunately, linear time.
3889 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3890 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003891 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003892 }
3893
3894 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003896
3897 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003898 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003899
3900 return clang_getNullCursor();
3901}
3902
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003903void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003904 const char **startBuf,
3905 const char **endBuf,
3906 unsigned *startLine,
3907 unsigned *startColumn,
3908 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003909 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003910 assert(getCursorDecl(C) && "CXCursor has null decl");
3911 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003912 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3913 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003914
Steve Naroff4ade6d62009-09-23 17:52:52 +00003915 SourceManager &SM = FD->getASTContext().getSourceManager();
3916 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3917 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3918 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3919 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3920 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3921 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3922}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003923
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003924void clang_enableStackTraces(void) {
3925 llvm::sys::PrintStackTraceOnErrorSignal();
3926}
3927
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003928void clang_executeOnThread(void (*fn)(void*), void *user_data,
3929 unsigned stack_size) {
3930 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3931}
3932
Ted Kremenekfb480492010-01-13 21:46:36 +00003933} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003934
Ted Kremenekfb480492010-01-13 21:46:36 +00003935//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003936// Token-based Operations.
3937//===----------------------------------------------------------------------===//
3938
3939/* CXToken layout:
3940 * int_data[0]: a CXTokenKind
3941 * int_data[1]: starting token location
3942 * int_data[2]: token length
3943 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003944 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003945 * otherwise unused.
3946 */
3947extern "C" {
3948
3949CXTokenKind clang_getTokenKind(CXToken CXTok) {
3950 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3951}
3952
3953CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3954 switch (clang_getTokenKind(CXTok)) {
3955 case CXToken_Identifier:
3956 case CXToken_Keyword:
3957 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003958 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3959 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003960
3961 case CXToken_Literal: {
3962 // We have stashed the starting pointer in the ptr_data field. Use it.
3963 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003964 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003965 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003966
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003967 case CXToken_Punctuation:
3968 case CXToken_Comment:
3969 break;
3970 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003971
3972 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003973 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003974 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003975 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003976 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003977
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003978 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3979 std::pair<FileID, unsigned> LocInfo
3980 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003981 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003982 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003983 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3984 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003985 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003986
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003987 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003988}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003989
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003990CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003991 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003992 if (!CXXUnit)
3993 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003994
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003995 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3996 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3997}
3998
3999CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004000 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004001 if (!CXXUnit)
4002 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004003
4004 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004005 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4006}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004007
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004008void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4009 CXToken **Tokens, unsigned *NumTokens) {
4010 if (Tokens)
4011 *Tokens = 0;
4012 if (NumTokens)
4013 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004014
Ted Kremeneka60ed472010-11-16 08:15:36 +00004015 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004016 if (!CXXUnit || !Tokens || !NumTokens)
4017 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004018
Douglas Gregorbdf60622010-03-05 21:16:25 +00004019 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4020
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004021 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004022 if (R.isInvalid())
4023 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004024
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004025 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4026 std::pair<FileID, unsigned> BeginLocInfo
4027 = SourceMgr.getDecomposedLoc(R.getBegin());
4028 std::pair<FileID, unsigned> EndLocInfo
4029 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004030
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004031 // Cannot tokenize across files.
4032 if (BeginLocInfo.first != EndLocInfo.first)
4033 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004034
4035 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004036 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004037 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004038 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004039 if (Invalid)
4040 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004041
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004042 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4043 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004044 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004045 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004046
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004047 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004048 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004049 llvm::SmallVector<CXToken, 32> CXTokens;
4050 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004051 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004052 do {
4053 // Lex the next token
4054 Lex.LexFromRawLexer(Tok);
4055 if (Tok.is(tok::eof))
4056 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004057
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004058 // Initialize the CXToken.
4059 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004060
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004061 // - Common fields
4062 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4063 CXTok.int_data[2] = Tok.getLength();
4064 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004065
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004066 // - Kind-specific fields
4067 if (Tok.isLiteral()) {
4068 CXTok.int_data[0] = CXToken_Literal;
4069 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004070 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004071 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004072 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004073 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004074
David Chisnall096428b2010-10-13 21:44:48 +00004075 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004076 CXTok.int_data[0] = CXToken_Keyword;
4077 }
4078 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004079 CXTok.int_data[0] = Tok.is(tok::identifier)
4080 ? CXToken_Identifier
4081 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004082 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004083 CXTok.ptr_data = II;
4084 } else if (Tok.is(tok::comment)) {
4085 CXTok.int_data[0] = CXToken_Comment;
4086 CXTok.ptr_data = 0;
4087 } else {
4088 CXTok.int_data[0] = CXToken_Punctuation;
4089 CXTok.ptr_data = 0;
4090 }
4091 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004092 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004093 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004094
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004095 if (CXTokens.empty())
4096 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004097
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004098 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4099 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4100 *NumTokens = CXTokens.size();
4101}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004102
Ted Kremenek6db61092010-05-05 00:55:15 +00004103void clang_disposeTokens(CXTranslationUnit TU,
4104 CXToken *Tokens, unsigned NumTokens) {
4105 free(Tokens);
4106}
4107
4108} // end: extern "C"
4109
4110//===----------------------------------------------------------------------===//
4111// Token annotation APIs.
4112//===----------------------------------------------------------------------===//
4113
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004114typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004115static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4116 CXCursor parent,
4117 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004118namespace {
4119class AnnotateTokensWorker {
4120 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004121 CXToken *Tokens;
4122 CXCursor *Cursors;
4123 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004124 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004125 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004126 CursorVisitor AnnotateVis;
4127 SourceManager &SrcMgr;
4128
4129 bool MoreTokens() const { return TokIdx < NumTokens; }
4130 unsigned NextToken() const { return TokIdx; }
4131 void AdvanceToken() { ++TokIdx; }
4132 SourceLocation GetTokenLoc(unsigned tokI) {
4133 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4134 }
4135
Ted Kremenek6db61092010-05-05 00:55:15 +00004136public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004137 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004138 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004139 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004140 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004141 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004142 AnnotateVis(tu,
4143 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004144 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004145 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004146
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004147 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004148 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004149 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004150 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004151 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004152 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004153};
4154}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004155
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004156void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4157 // Walk the AST within the region of interest, annotating tokens
4158 // along the way.
4159 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004160
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004161 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4162 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004163 if (Pos != Annotated.end() &&
4164 (clang_isInvalid(Cursors[I].kind) ||
4165 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004166 Cursors[I] = Pos->second;
4167 }
4168
4169 // Finish up annotating any tokens left.
4170 if (!MoreTokens())
4171 return;
4172
4173 const CXCursor &C = clang_getNullCursor();
4174 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4175 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4176 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004177 }
4178}
4179
Ted Kremenek6db61092010-05-05 00:55:15 +00004180enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004181AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004182 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004183 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004184 if (cursorRange.isInvalid())
4185 return CXChildVisit_Recurse;
4186
Douglas Gregor4419b672010-10-21 06:10:04 +00004187 if (clang_isPreprocessing(cursor.kind)) {
4188 // For macro instantiations, just note where the beginning of the macro
4189 // instantiation occurs.
4190 if (cursor.kind == CXCursor_MacroInstantiation) {
4191 Annotated[Loc.int_data] = cursor;
4192 return CXChildVisit_Recurse;
4193 }
4194
Douglas Gregor4419b672010-10-21 06:10:04 +00004195 // Items in the preprocessing record are kept separate from items in
4196 // declarations, so we keep a separate token index.
4197 unsigned SavedTokIdx = TokIdx;
4198 TokIdx = PreprocessingTokIdx;
4199
4200 // Skip tokens up until we catch up to the beginning of the preprocessing
4201 // entry.
4202 while (MoreTokens()) {
4203 const unsigned I = NextToken();
4204 SourceLocation TokLoc = GetTokenLoc(I);
4205 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4206 case RangeBefore:
4207 AdvanceToken();
4208 continue;
4209 case RangeAfter:
4210 case RangeOverlap:
4211 break;
4212 }
4213 break;
4214 }
4215
4216 // Look at all of the tokens within this range.
4217 while (MoreTokens()) {
4218 const unsigned I = NextToken();
4219 SourceLocation TokLoc = GetTokenLoc(I);
4220 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4221 case RangeBefore:
4222 assert(0 && "Infeasible");
4223 case RangeAfter:
4224 break;
4225 case RangeOverlap:
4226 Cursors[I] = cursor;
4227 AdvanceToken();
4228 continue;
4229 }
4230 break;
4231 }
4232
4233 // Save the preprocessing token index; restore the non-preprocessing
4234 // token index.
4235 PreprocessingTokIdx = TokIdx;
4236 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004237 return CXChildVisit_Recurse;
4238 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004240 if (cursorRange.isInvalid())
4241 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004242
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004243 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4244
Ted Kremeneka333c662010-05-12 05:29:33 +00004245 // Adjust the annotated range based specific declarations.
4246 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4247 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004248 Decl *D = cxcursor::getCursorDecl(cursor);
4249 // Don't visit synthesized ObjC methods, since they have no syntatic
4250 // representation in the source.
4251 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4252 if (MD->isSynthesized())
4253 return CXChildVisit_Continue;
4254 }
4255 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004256 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4257 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004258 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004259 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004260 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004261 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004262 }
4263 }
4264 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004265
Ted Kremenek3f404602010-08-14 01:14:06 +00004266 // If the location of the cursor occurs within a macro instantiation, record
4267 // the spelling location of the cursor in our annotation map. We can then
4268 // paper over the token labelings during a post-processing step to try and
4269 // get cursor mappings for tokens that are the *arguments* of a macro
4270 // instantiation.
4271 if (L.isMacroID()) {
4272 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4273 // Only invalidate the old annotation if it isn't part of a preprocessing
4274 // directive. Here we assume that the default construction of CXCursor
4275 // results in CXCursor.kind being an initialized value (i.e., 0). If
4276 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004277
Ted Kremenek3f404602010-08-14 01:14:06 +00004278 CXCursor &oldC = Annotated[rawEncoding];
4279 if (!clang_isPreprocessing(oldC.kind))
4280 oldC = cursor;
4281 }
4282
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004283 const enum CXCursorKind K = clang_getCursorKind(parent);
4284 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004285 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4286 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004287
4288 while (MoreTokens()) {
4289 const unsigned I = NextToken();
4290 SourceLocation TokLoc = GetTokenLoc(I);
4291 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4292 case RangeBefore:
4293 Cursors[I] = updateC;
4294 AdvanceToken();
4295 continue;
4296 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004297 case RangeOverlap:
4298 break;
4299 }
4300 break;
4301 }
4302
4303 // Visit children to get their cursor information.
4304 const unsigned BeforeChildren = NextToken();
4305 VisitChildren(cursor);
4306 const unsigned AfterChildren = NextToken();
4307
4308 // Adjust 'Last' to the last token within the extent of the cursor.
4309 while (MoreTokens()) {
4310 const unsigned I = NextToken();
4311 SourceLocation TokLoc = GetTokenLoc(I);
4312 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4313 case RangeBefore:
4314 assert(0 && "Infeasible");
4315 case RangeAfter:
4316 break;
4317 case RangeOverlap:
4318 Cursors[I] = updateC;
4319 AdvanceToken();
4320 continue;
4321 }
4322 break;
4323 }
4324 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004325
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004326 // Scan the tokens that are at the beginning of the cursor, but are not
4327 // capture by the child cursors.
4328
4329 // For AST elements within macros, rely on a post-annotate pass to
4330 // to correctly annotate the tokens with cursors. Otherwise we can
4331 // get confusing results of having tokens that map to cursors that really
4332 // are expanded by an instantiation.
4333 if (L.isMacroID())
4334 cursor = clang_getNullCursor();
4335
4336 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4337 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4338 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004339
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004340 Cursors[I] = cursor;
4341 }
4342 // Scan the tokens that are at the end of the cursor, but are not captured
4343 // but the child cursors.
4344 for (unsigned I = AfterChildren; I != Last; ++I)
4345 Cursors[I] = cursor;
4346
4347 TokIdx = Last;
4348 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004349}
4350
Ted Kremenek6db61092010-05-05 00:55:15 +00004351static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4352 CXCursor parent,
4353 CXClientData client_data) {
4354 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4355}
4356
Ted Kremenekab979612010-11-11 08:05:23 +00004357// This gets run a separate thread to avoid stack blowout.
4358static void runAnnotateTokensWorker(void *UserData) {
4359 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4360}
4361
Ted Kremenek6db61092010-05-05 00:55:15 +00004362extern "C" {
4363
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004364void clang_annotateTokens(CXTranslationUnit TU,
4365 CXToken *Tokens, unsigned NumTokens,
4366 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004367
4368 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004369 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004370
Douglas Gregor4419b672010-10-21 06:10:04 +00004371 // Any token we don't specifically annotate will have a NULL cursor.
4372 CXCursor C = clang_getNullCursor();
4373 for (unsigned I = 0; I != NumTokens; ++I)
4374 Cursors[I] = C;
4375
Ted Kremeneka60ed472010-11-16 08:15:36 +00004376 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004377 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004378 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004379
Douglas Gregorbdf60622010-03-05 21:16:25 +00004380 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004381
Douglas Gregor0396f462010-03-19 05:22:59 +00004382 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004383 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004384 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4385 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004386 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4387 clang_getTokenLocation(TU,
4388 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004389
Douglas Gregor0396f462010-03-19 05:22:59 +00004390 // A mapping from the source locations found when re-lexing or traversing the
4391 // region of interest to the corresponding cursors.
4392 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004393
4394 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004395 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004396 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4397 std::pair<FileID, unsigned> BeginLocInfo
4398 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4399 std::pair<FileID, unsigned> EndLocInfo
4400 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004401
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004402 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004403 bool Invalid = false;
4404 if (BeginLocInfo.first == EndLocInfo.first &&
4405 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4406 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004407 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4408 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004409 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004410 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004411 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004412
4413 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004414 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004415 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004416 Token Tok;
4417 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004418
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004419 reprocess:
4420 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4421 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004422 // don't see it while preprocessing these tokens later, but keep track
4423 // of all of the token locations inside this preprocessing directive so
4424 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004425 //
4426 // FIXME: Some simple tests here could identify macro definitions and
4427 // #undefs, to provide specific cursor kinds for those.
4428 std::vector<SourceLocation> Locations;
4429 do {
4430 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004431 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004432 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004433
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004434 using namespace cxcursor;
4435 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004436 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4437 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004438 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004439 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4440 Annotated[Locations[I].getRawEncoding()] = Cursor;
4441 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004442
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004443 if (Tok.isAtStartOfLine())
4444 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004445
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004446 continue;
4447 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004448
Douglas Gregor48072312010-03-18 15:23:44 +00004449 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004450 break;
4451 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004452 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004453
Douglas Gregor0396f462010-03-19 05:22:59 +00004454 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004455 // a specific cursor.
4456 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004457 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004458
4459 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004460 // FIXME: We use a ridiculous stack size here because the data-recursion
4461 // algorithm uses a large stack frame than the non-data recursive version,
4462 // and AnnotationTokensWorker currently transforms the data-recursion
4463 // algorithm back into a traditional recursion by explicitly calling
4464 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004465 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004466 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4467 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004468 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4469 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004470}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004471} // end: extern "C"
4472
4473//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004474// Operations for querying linkage of a cursor.
4475//===----------------------------------------------------------------------===//
4476
4477extern "C" {
4478CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004479 if (!clang_isDeclaration(cursor.kind))
4480 return CXLinkage_Invalid;
4481
Ted Kremenek16b42592010-03-03 06:36:57 +00004482 Decl *D = cxcursor::getCursorDecl(cursor);
4483 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4484 switch (ND->getLinkage()) {
4485 case NoLinkage: return CXLinkage_NoLinkage;
4486 case InternalLinkage: return CXLinkage_Internal;
4487 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4488 case ExternalLinkage: return CXLinkage_External;
4489 };
4490
4491 return CXLinkage_Invalid;
4492}
4493} // end: extern "C"
4494
4495//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004496// Operations for querying language of a cursor.
4497//===----------------------------------------------------------------------===//
4498
4499static CXLanguageKind getDeclLanguage(const Decl *D) {
4500 switch (D->getKind()) {
4501 default:
4502 break;
4503 case Decl::ImplicitParam:
4504 case Decl::ObjCAtDefsField:
4505 case Decl::ObjCCategory:
4506 case Decl::ObjCCategoryImpl:
4507 case Decl::ObjCClass:
4508 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004509 case Decl::ObjCForwardProtocol:
4510 case Decl::ObjCImplementation:
4511 case Decl::ObjCInterface:
4512 case Decl::ObjCIvar:
4513 case Decl::ObjCMethod:
4514 case Decl::ObjCProperty:
4515 case Decl::ObjCPropertyImpl:
4516 case Decl::ObjCProtocol:
4517 return CXLanguage_ObjC;
4518 case Decl::CXXConstructor:
4519 case Decl::CXXConversion:
4520 case Decl::CXXDestructor:
4521 case Decl::CXXMethod:
4522 case Decl::CXXRecord:
4523 case Decl::ClassTemplate:
4524 case Decl::ClassTemplatePartialSpecialization:
4525 case Decl::ClassTemplateSpecialization:
4526 case Decl::Friend:
4527 case Decl::FriendTemplate:
4528 case Decl::FunctionTemplate:
4529 case Decl::LinkageSpec:
4530 case Decl::Namespace:
4531 case Decl::NamespaceAlias:
4532 case Decl::NonTypeTemplateParm:
4533 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004534 case Decl::TemplateTemplateParm:
4535 case Decl::TemplateTypeParm:
4536 case Decl::UnresolvedUsingTypename:
4537 case Decl::UnresolvedUsingValue:
4538 case Decl::Using:
4539 case Decl::UsingDirective:
4540 case Decl::UsingShadow:
4541 return CXLanguage_CPlusPlus;
4542 }
4543
4544 return CXLanguage_C;
4545}
4546
4547extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004548
4549enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4550 if (clang_isDeclaration(cursor.kind))
4551 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4552 if (D->hasAttr<UnavailableAttr>() ||
4553 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4554 return CXAvailability_Available;
4555
4556 if (D->hasAttr<DeprecatedAttr>())
4557 return CXAvailability_Deprecated;
4558 }
4559
4560 return CXAvailability_Available;
4561}
4562
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004563CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4564 if (clang_isDeclaration(cursor.kind))
4565 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4566
4567 return CXLanguage_Invalid;
4568}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004569
4570 /// \brief If the given cursor is the "templated" declaration
4571 /// descibing a class or function template, return the class or
4572 /// function template.
4573static Decl *maybeGetTemplateCursor(Decl *D) {
4574 if (!D)
4575 return 0;
4576
4577 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4578 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4579 return FunTmpl;
4580
4581 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4582 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4583 return ClassTmpl;
4584
4585 return D;
4586}
4587
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004588CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4589 if (clang_isDeclaration(cursor.kind)) {
4590 if (Decl *D = getCursorDecl(cursor)) {
4591 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004592 if (!DC)
4593 return clang_getNullCursor();
4594
4595 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4596 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004597 }
4598 }
4599
4600 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4601 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004602 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004603 }
4604
4605 return clang_getNullCursor();
4606}
4607
4608CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4609 if (clang_isDeclaration(cursor.kind)) {
4610 if (Decl *D = getCursorDecl(cursor)) {
4611 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004612 if (!DC)
4613 return clang_getNullCursor();
4614
4615 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4616 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004617 }
4618 }
4619
4620 // FIXME: Note that we can't easily compute the lexical context of a
4621 // statement or expression, so we return nothing.
4622 return clang_getNullCursor();
4623}
4624
Douglas Gregor9f592342010-10-01 20:25:15 +00004625static void CollectOverriddenMethods(DeclContext *Ctx,
4626 ObjCMethodDecl *Method,
4627 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4628 if (!Ctx)
4629 return;
4630
4631 // If we have a class or category implementation, jump straight to the
4632 // interface.
4633 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4634 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4635
4636 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4637 if (!Container)
4638 return;
4639
4640 // Check whether we have a matching method at this level.
4641 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4642 Method->isInstanceMethod()))
4643 if (Method != Overridden) {
4644 // We found an override at this level; there is no need to look
4645 // into other protocols or categories.
4646 Methods.push_back(Overridden);
4647 return;
4648 }
4649
4650 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4651 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4652 PEnd = Protocol->protocol_end();
4653 P != PEnd; ++P)
4654 CollectOverriddenMethods(*P, Method, Methods);
4655 }
4656
4657 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4658 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4659 PEnd = Category->protocol_end();
4660 P != PEnd; ++P)
4661 CollectOverriddenMethods(*P, Method, Methods);
4662 }
4663
4664 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4665 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4666 PEnd = Interface->protocol_end();
4667 P != PEnd; ++P)
4668 CollectOverriddenMethods(*P, Method, Methods);
4669
4670 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4671 Category; Category = Category->getNextClassCategory())
4672 CollectOverriddenMethods(Category, Method, Methods);
4673
4674 // We only look into the superclass if we haven't found anything yet.
4675 if (Methods.empty())
4676 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4677 return CollectOverriddenMethods(Super, Method, Methods);
4678 }
4679}
4680
4681void clang_getOverriddenCursors(CXCursor cursor,
4682 CXCursor **overridden,
4683 unsigned *num_overridden) {
4684 if (overridden)
4685 *overridden = 0;
4686 if (num_overridden)
4687 *num_overridden = 0;
4688 if (!overridden || !num_overridden)
4689 return;
4690
4691 if (!clang_isDeclaration(cursor.kind))
4692 return;
4693
4694 Decl *D = getCursorDecl(cursor);
4695 if (!D)
4696 return;
4697
4698 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004699 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004700 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4701 *num_overridden = CXXMethod->size_overridden_methods();
4702 if (!*num_overridden)
4703 return;
4704
4705 *overridden = new CXCursor [*num_overridden];
4706 unsigned I = 0;
4707 for (CXXMethodDecl::method_iterator
4708 M = CXXMethod->begin_overridden_methods(),
4709 MEnd = CXXMethod->end_overridden_methods();
4710 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004711 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004712 return;
4713 }
4714
4715 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4716 if (!Method)
4717 return;
4718
4719 // Handle Objective-C methods.
4720 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4721 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4722
4723 if (Methods.empty())
4724 return;
4725
4726 *num_overridden = Methods.size();
4727 *overridden = new CXCursor [Methods.size()];
4728 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004729 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004730}
4731
4732void clang_disposeOverriddenCursors(CXCursor *overridden) {
4733 delete [] overridden;
4734}
4735
Douglas Gregorecdcb882010-10-20 22:00:55 +00004736CXFile clang_getIncludedFile(CXCursor cursor) {
4737 if (cursor.kind != CXCursor_InclusionDirective)
4738 return 0;
4739
4740 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4741 return (void *)ID->getFile();
4742}
4743
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004744} // end: extern "C"
4745
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004746
4747//===----------------------------------------------------------------------===//
4748// C++ AST instrospection.
4749//===----------------------------------------------------------------------===//
4750
4751extern "C" {
4752unsigned clang_CXXMethod_isStatic(CXCursor C) {
4753 if (!clang_isDeclaration(C.kind))
4754 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004755
4756 CXXMethodDecl *Method = 0;
4757 Decl *D = cxcursor::getCursorDecl(C);
4758 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4759 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4760 else
4761 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4762 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004763}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004764
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004765} // end: extern "C"
4766
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004767//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004768// Attribute introspection.
4769//===----------------------------------------------------------------------===//
4770
4771extern "C" {
4772CXType clang_getIBOutletCollectionType(CXCursor C) {
4773 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004774 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004775
4776 IBOutletCollectionAttr *A =
4777 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4778
Ted Kremeneka60ed472010-11-16 08:15:36 +00004779 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004780}
4781} // end: extern "C"
4782
4783//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004784// Misc. utility functions.
4785//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004786
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004787/// Default to using an 8 MB stack size on "safety" threads.
4788static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004789
4790namespace clang {
4791
4792bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004793 void (*Fn)(void*), void *UserData,
4794 unsigned Size) {
4795 if (!Size)
4796 Size = GetSafetyThreadStackSize();
4797 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004798 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4799 return CRC.RunSafely(Fn, UserData);
4800}
4801
4802unsigned GetSafetyThreadStackSize() {
4803 return SafetyStackThreadSize;
4804}
4805
4806void SetSafetyThreadStackSize(unsigned Value) {
4807 SafetyStackThreadSize = Value;
4808}
4809
4810}
4811
Ted Kremenek04bb7162010-01-22 22:44:15 +00004812extern "C" {
4813
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004814CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004815 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004816}
4817
4818} // end: extern "C"