blob: 1f46b07ebdb3e9aa87adfd00f18421f252fc8429 [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,
144 MemberRefVisitKind };
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:
1166 // FIXME: The token at this source location might actually have been a
1167 // namespace alias, but we don't model that. Lame!
1168 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1169 TU));
1170
1171 case NestedNameSpecifier::TypeSpec: {
1172 // If the type has a form where we know that the beginning of the source
1173 // range matches up with a reference cursor. Visit the appropriate reference
1174 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001175 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001176 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1177 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1178 if (const TagType *Tag = dyn_cast<TagType>(T))
1179 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1180 if (const TemplateSpecializationType *TST
1181 = dyn_cast<TemplateSpecializationType>(T))
1182 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1183 break;
1184 }
1185
1186 case NestedNameSpecifier::TypeSpecWithTemplate:
1187 case NestedNameSpecifier::Global:
1188 case NestedNameSpecifier::Identifier:
1189 break;
1190 }
1191
1192 return false;
1193}
1194
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001195bool CursorVisitor::VisitTemplateParameters(
1196 const TemplateParameterList *Params) {
1197 if (!Params)
1198 return false;
1199
1200 for (TemplateParameterList::const_iterator P = Params->begin(),
1201 PEnd = Params->end();
1202 P != PEnd; ++P) {
1203 if (Visit(MakeCXCursor(*P, TU)))
1204 return true;
1205 }
1206
1207 return false;
1208}
1209
Douglas Gregor0b36e612010-08-31 20:37:03 +00001210bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1211 switch (Name.getKind()) {
1212 case TemplateName::Template:
1213 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1214
1215 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001216 // Visit the overloaded template set.
1217 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1218 return true;
1219
Douglas Gregor0b36e612010-08-31 20:37:03 +00001220 return false;
1221
1222 case TemplateName::DependentTemplate:
1223 // FIXME: Visit nested-name-specifier.
1224 return false;
1225
1226 case TemplateName::QualifiedTemplate:
1227 // FIXME: Visit nested-name-specifier.
1228 return Visit(MakeCursorTemplateRef(
1229 Name.getAsQualifiedTemplateName()->getDecl(),
1230 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001231
1232 case TemplateName::SubstTemplateTemplateParmPack:
1233 return Visit(MakeCursorTemplateRef(
1234 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1235 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001236 }
1237
1238 return false;
1239}
1240
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001241bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1242 switch (TAL.getArgument().getKind()) {
1243 case TemplateArgument::Null:
1244 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001245 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001246 return false;
1247
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001248 case TemplateArgument::Type:
1249 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1250 return Visit(TSInfo->getTypeLoc());
1251 return false;
1252
1253 case TemplateArgument::Declaration:
1254 if (Expr *E = TAL.getSourceDeclExpression())
1255 return Visit(MakeCXCursor(E, StmtParent, TU));
1256 return false;
1257
1258 case TemplateArgument::Expression:
1259 if (Expr *E = TAL.getSourceExpression())
1260 return Visit(MakeCXCursor(E, StmtParent, TU));
1261 return false;
1262
1263 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001264 case TemplateArgument::TemplateExpansion:
1265 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001266 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001267 }
1268
1269 return false;
1270}
1271
Ted Kremeneka0536d82010-05-07 01:04:29 +00001272bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1273 return VisitDeclContext(D);
1274}
1275
Douglas Gregor01829d32010-08-31 14:41:23 +00001276bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1277 return Visit(TL.getUnqualifiedLoc());
1278}
1279
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001280bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001281 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001282
1283 // Some builtin types (such as Objective-C's "id", "sel", and
1284 // "Class") have associated declarations. Create cursors for those.
1285 QualType VisitType;
1286 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001287 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001288 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001289 case BuiltinType::Char_U:
1290 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291 case BuiltinType::Char16:
1292 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001293 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001294 case BuiltinType::UInt:
1295 case BuiltinType::ULong:
1296 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001297 case BuiltinType::UInt128:
1298 case BuiltinType::Char_S:
1299 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001300 case BuiltinType::WChar_U:
1301 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001302 case BuiltinType::Short:
1303 case BuiltinType::Int:
1304 case BuiltinType::Long:
1305 case BuiltinType::LongLong:
1306 case BuiltinType::Int128:
1307 case BuiltinType::Float:
1308 case BuiltinType::Double:
1309 case BuiltinType::LongDouble:
1310 case BuiltinType::NullPtr:
1311 case BuiltinType::Overload:
1312 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001313 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001314
1315 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001316 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001317
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001318 case BuiltinType::ObjCId:
1319 VisitType = Context.getObjCIdType();
1320 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001321
1322 case BuiltinType::ObjCClass:
1323 VisitType = Context.getObjCClassType();
1324 break;
1325
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001326 case BuiltinType::ObjCSel:
1327 VisitType = Context.getObjCSelType();
1328 break;
1329 }
1330
1331 if (!VisitType.isNull()) {
1332 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001333 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334 TU));
1335 }
1336
1337 return false;
1338}
1339
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001340bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1341 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1342}
1343
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001344bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1345 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1346}
1347
1348bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1349 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1350}
1351
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001352bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001353 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001354 // no context information with which we can match up the depth/index in the
1355 // type to the appropriate
1356 return false;
1357}
1358
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1360 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1361 return true;
1362
John McCallc12c5bb2010-05-15 11:32:37 +00001363 return false;
1364}
1365
1366bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1367 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1368 return true;
1369
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1371 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1372 TU)))
1373 return true;
1374 }
1375
1376 return false;
1377}
1378
1379bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001380 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381}
1382
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001383bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1384 return Visit(TL.getInnerLoc());
1385}
1386
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1388 return Visit(TL.getPointeeLoc());
1389}
1390
1391bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1392 return Visit(TL.getPointeeLoc());
1393}
1394
1395bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1396 return Visit(TL.getPointeeLoc());
1397}
1398
1399bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001400 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001401}
1402
1403bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001404 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001405}
1406
Douglas Gregor01829d32010-08-31 14:41:23 +00001407bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1408 bool SkipResultType) {
1409 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001410 return true;
1411
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001412 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001413 if (Decl *D = TL.getArg(I))
1414 if (Visit(MakeCXCursor(D, TU)))
1415 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001416
1417 return false;
1418}
1419
1420bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1421 if (Visit(TL.getElementLoc()))
1422 return true;
1423
1424 if (Expr *Size = TL.getSizeExpr())
1425 return Visit(MakeCXCursor(Size, StmtParent, TU));
1426
1427 return false;
1428}
1429
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001430bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1431 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001432 // Visit the template name.
1433 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1434 TL.getTemplateNameLoc()))
1435 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001436
1437 // Visit the template arguments.
1438 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1439 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1440 return true;
1441
1442 return false;
1443}
1444
Douglas Gregor2332c112010-01-21 20:48:56 +00001445bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1446 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1447}
1448
1449bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1450 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1451 return Visit(TSInfo->getTypeLoc());
1452
1453 return false;
1454}
1455
Douglas Gregor7536dd52010-12-20 02:24:11 +00001456bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1457 return Visit(TL.getPatternLoc());
1458}
1459
Ted Kremenek3064ef92010-08-27 21:34:58 +00001460bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1461 if (D->isDefinition()) {
1462 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1463 E = D->bases_end(); I != E; ++I) {
1464 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1465 return true;
1466 }
1467 }
1468
1469 return VisitTagDecl(D);
1470}
1471
Ted Kremenek09dfa372010-02-18 05:46:33 +00001472bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001473 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1474 i != e; ++i)
1475 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001476 return true;
1477
1478 return false;
1479}
1480
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001481//===----------------------------------------------------------------------===//
1482// Data-recursive visitor methods.
1483//===----------------------------------------------------------------------===//
1484
Ted Kremenek28a71942010-11-13 00:36:47 +00001485namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001486#define DEF_JOB(NAME, DATA, KIND)\
1487class NAME : public VisitorJob {\
1488public:\
1489 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1490 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001491 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001492};
1493
1494DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1495DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001496DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001497DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001498DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1499 ExplicitTemplateArgsVisitKind)
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:
1531 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1532 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
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 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001538 LabelStmt *get() const { return static_cast<LabelStmt*>(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 Gregoree8aff02011-01-04 17:33:58 +00001640 // FIXME: Variadic templates SizeOfPackExpr!
1641
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();
1688 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1689 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001690 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001691 }
1692 if (size == WL.size())
1693 return;
1694 // Now reverse the entries we just added. This will match the DFS
1695 // ordering performed by the worklist.
1696 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1697 std::reverse(I, E);
1698}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001699void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1700 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1701}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001702void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1703 AddDecl(B->getBlockDecl());
1704}
Ted Kremenek28a71942010-11-13 00:36:47 +00001705void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1706 EnqueueChildren(E);
1707 AddTypeLoc(E->getTypeSourceInfo());
1708}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001709void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1710 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1711 E = S->body_rend(); I != E; ++I) {
1712 AddStmt(*I);
1713 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001714}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001715void EnqueueVisitor::
1716VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1717 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1718 AddDeclarationNameInfo(E);
1719 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1720 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1721 if (!E->isImplicitAccess())
1722 AddStmt(E->getBase());
1723}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001724void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1725 // Enqueue the initializer or constructor arguments.
1726 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1727 AddStmt(E->getConstructorArg(I-1));
1728 // Enqueue the array size, if any.
1729 AddStmt(E->getArraySize());
1730 // Enqueue the allocated type.
1731 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1732 // Enqueue the placement arguments.
1733 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1734 AddStmt(E->getPlacementArg(I-1));
1735}
Ted Kremenek28a71942010-11-13 00:36:47 +00001736void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001737 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1738 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001739 AddStmt(CE->getCallee());
1740 AddStmt(CE->getArg(0));
1741}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001742void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1743 // Visit the name of the type being destroyed.
1744 AddTypeLoc(E->getDestroyedTypeInfo());
1745 // Visit the scope type that looks disturbingly like the nested-name-specifier
1746 // but isn't.
1747 AddTypeLoc(E->getScopeTypeInfo());
1748 // Visit the nested-name-specifier.
1749 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1750 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1751 // Visit base expression.
1752 AddStmt(E->getBase());
1753}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001754void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1755 AddTypeLoc(E->getTypeSourceInfo());
1756}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001757void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1758 EnqueueChildren(E);
1759 AddTypeLoc(E->getTypeSourceInfo());
1760}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001761void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1762 EnqueueChildren(E);
1763 if (E->isTypeOperand())
1764 AddTypeLoc(E->getTypeOperandSourceInfo());
1765}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001766
1767void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1768 *E) {
1769 EnqueueChildren(E);
1770 AddTypeLoc(E->getTypeSourceInfo());
1771}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001772void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1773 EnqueueChildren(E);
1774 if (E->isTypeOperand())
1775 AddTypeLoc(E->getTypeOperandSourceInfo());
1776}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001777void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001778 if (DR->hasExplicitTemplateArgs()) {
1779 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1780 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001781 WL.push_back(DeclRefExprParts(DR, Parent));
1782}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001783void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1784 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1785 AddDeclarationNameInfo(E);
1786 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1787 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1788}
Ted Kremenek035dc412010-11-13 00:36:50 +00001789void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1790 unsigned size = WL.size();
1791 bool isFirst = true;
1792 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1793 D != DEnd; ++D) {
1794 AddDecl(*D, isFirst);
1795 isFirst = false;
1796 }
1797 if (size == WL.size())
1798 return;
1799 // Now reverse the entries we just added. This will match the DFS
1800 // ordering performed by the worklist.
1801 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1802 std::reverse(I, E);
1803}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001804void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1805 AddStmt(E->getInit());
1806 typedef DesignatedInitExpr::Designator Designator;
1807 for (DesignatedInitExpr::reverse_designators_iterator
1808 D = E->designators_rbegin(), DEnd = E->designators_rend();
1809 D != DEnd; ++D) {
1810 if (D->isFieldDesignator()) {
1811 if (FieldDecl *Field = D->getField())
1812 AddMemberRef(Field, D->getFieldLoc());
1813 continue;
1814 }
1815 if (D->isArrayDesignator()) {
1816 AddStmt(E->getArrayIndex(*D));
1817 continue;
1818 }
1819 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1820 AddStmt(E->getArrayRangeEnd(*D));
1821 AddStmt(E->getArrayRangeStart(*D));
1822 }
1823}
Ted Kremenek28a71942010-11-13 00:36:47 +00001824void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1825 EnqueueChildren(E);
1826 AddTypeLoc(E->getTypeInfoAsWritten());
1827}
1828void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1829 AddStmt(FS->getBody());
1830 AddStmt(FS->getInc());
1831 AddStmt(FS->getCond());
1832 AddDecl(FS->getConditionVariable());
1833 AddStmt(FS->getInit());
1834}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001835void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1836 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1837}
Ted Kremenek28a71942010-11-13 00:36:47 +00001838void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1839 AddStmt(If->getElse());
1840 AddStmt(If->getThen());
1841 AddStmt(If->getCond());
1842 AddDecl(If->getConditionVariable());
1843}
1844void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1845 // We care about the syntactic form of the initializer list, only.
1846 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1847 IE = Syntactic;
1848 EnqueueChildren(IE);
1849}
1850void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001851 WL.push_back(MemberExprParts(M, Parent));
1852
1853 // If the base of the member access expression is an implicit 'this', don't
1854 // visit it.
1855 // FIXME: If we ever want to show these implicit accesses, this will be
1856 // unfortunate. However, clang_getCursor() relies on this behavior.
1857 if (CXXThisExpr *This
1858 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1859 if (This->isImplicit())
1860 return;
1861
Ted Kremenek28a71942010-11-13 00:36:47 +00001862 AddStmt(M->getBase());
1863}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001864void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1865 AddTypeLoc(E->getEncodedTypeSourceInfo());
1866}
Ted Kremenek28a71942010-11-13 00:36:47 +00001867void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1868 EnqueueChildren(M);
1869 AddTypeLoc(M->getClassReceiverTypeInfo());
1870}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001871void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1872 // Visit the components of the offsetof expression.
1873 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1874 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1875 const OffsetOfNode &Node = E->getComponent(I-1);
1876 switch (Node.getKind()) {
1877 case OffsetOfNode::Array:
1878 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1879 break;
1880 case OffsetOfNode::Field:
1881 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1882 break;
1883 case OffsetOfNode::Identifier:
1884 case OffsetOfNode::Base:
1885 continue;
1886 }
1887 }
1888 // Visit the type into which we're computing the offset.
1889 AddTypeLoc(E->getTypeSourceInfo());
1890}
Ted Kremenek28a71942010-11-13 00:36:47 +00001891void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001892 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001893 WL.push_back(OverloadExprParts(E, Parent));
1894}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001895void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1896 EnqueueChildren(E);
1897 if (E->isArgumentType())
1898 AddTypeLoc(E->getArgumentTypeInfo());
1899}
Ted Kremenek28a71942010-11-13 00:36:47 +00001900void EnqueueVisitor::VisitStmt(Stmt *S) {
1901 EnqueueChildren(S);
1902}
1903void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1904 AddStmt(S->getBody());
1905 AddStmt(S->getCond());
1906 AddDecl(S->getConditionVariable());
1907}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001908
Ted Kremenek28a71942010-11-13 00:36:47 +00001909void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1910 AddStmt(W->getBody());
1911 AddStmt(W->getCond());
1912 AddDecl(W->getConditionVariable());
1913}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001914void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1915 AddTypeLoc(E->getQueriedTypeSourceInfo());
1916}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001917
1918void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00001919 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00001920 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00001921}
1922
Ted Kremenek28a71942010-11-13 00:36:47 +00001923void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1924 VisitOverloadExpr(U);
1925 if (!U->isImplicitAccess())
1926 AddStmt(U->getBase());
1927}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001928void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1929 AddStmt(E->getSubExpr());
1930 AddTypeLoc(E->getWrittenTypeInfo());
1931}
Ted Kremenek60458782010-11-12 21:34:16 +00001932
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001933void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001934 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001935}
1936
1937bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1938 if (RegionOfInterest.isValid()) {
1939 SourceRange Range = getRawCursorExtent(C);
1940 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1941 return false;
1942 }
1943 return true;
1944}
1945
1946bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1947 while (!WL.empty()) {
1948 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001949 VisitorJob LI = WL.back();
1950 WL.pop_back();
1951
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001952 // Set the Parent field, then back to its old value once we're done.
1953 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1954
1955 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001956 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001957 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001958 if (!D)
1959 continue;
1960
1961 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001962 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001963 return true;
1964
1965 continue;
1966 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001967 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1968 const ExplicitTemplateArgumentList *ArgList =
1969 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1970 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1971 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1972 Arg != ArgEnd; ++Arg) {
1973 if (VisitTemplateArgumentLoc(*Arg))
1974 return true;
1975 }
1976 continue;
1977 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001978 case VisitorJob::TypeLocVisitKind: {
1979 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001980 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001981 return true;
1982 continue;
1983 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001984 case VisitorJob::LabelRefVisitKind: {
1985 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1986 if (Visit(MakeCursorLabelRef(LS,
1987 cast<LabelRefVisit>(&LI)->getLoc(),
1988 TU)))
1989 return true;
1990 continue;
1991 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001992 case VisitorJob::NestedNameSpecifierVisitKind: {
1993 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
1994 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
1995 return true;
1996 continue;
1997 }
1998 case VisitorJob::DeclarationNameInfoVisitKind: {
1999 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2000 ->get()))
2001 return true;
2002 continue;
2003 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002004 case VisitorJob::MemberRefVisitKind: {
2005 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2006 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2007 return true;
2008 continue;
2009 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002010 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002011 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002012 if (!S)
2013 continue;
2014
Ted Kremenekf1107452010-11-12 18:26:56 +00002015 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002016 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002017 if (!IsInRegionOfInterest(Cursor))
2018 continue;
2019 switch (Visitor(Cursor, Parent, ClientData)) {
2020 case CXChildVisit_Break: return true;
2021 case CXChildVisit_Continue: break;
2022 case CXChildVisit_Recurse:
2023 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002024 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002025 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002026 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002027 }
2028 case VisitorJob::MemberExprPartsKind: {
2029 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002030 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002031
2032 // Visit the nested-name-specifier
2033 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2034 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2035 return true;
2036
2037 // Visit the declaration name.
2038 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2039 return true;
2040
2041 // Visit the explicitly-specified template arguments, if any.
2042 if (M->hasExplicitTemplateArgs()) {
2043 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2044 *ArgEnd = Arg + M->getNumTemplateArgs();
2045 Arg != ArgEnd; ++Arg) {
2046 if (VisitTemplateArgumentLoc(*Arg))
2047 return true;
2048 }
2049 }
2050 continue;
2051 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002052 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002053 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002054 // Visit nested-name-specifier, if present.
2055 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2056 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2057 return true;
2058 // Visit declaration name.
2059 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2060 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002061 continue;
2062 }
Ted Kremenek60458782010-11-12 21:34:16 +00002063 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002064 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002065 // Visit the nested-name-specifier.
2066 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2067 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2068 return true;
2069 // Visit the declaration name.
2070 if (VisitDeclarationNameInfo(O->getNameInfo()))
2071 return true;
2072 // Visit the overloaded declaration reference.
2073 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2074 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002075 continue;
2076 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002077 }
2078 }
2079 return false;
2080}
2081
Ted Kremenekcdba6592010-11-18 00:42:18 +00002082bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002083 VisitorWorkList *WL = 0;
2084 if (!WorkListFreeList.empty()) {
2085 WL = WorkListFreeList.back();
2086 WL->clear();
2087 WorkListFreeList.pop_back();
2088 }
2089 else {
2090 WL = new VisitorWorkList();
2091 WorkListCache.push_back(WL);
2092 }
2093 EnqueueWorkList(*WL, S);
2094 bool result = RunVisitorWorkList(*WL);
2095 WorkListFreeList.push_back(WL);
2096 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002097}
2098
2099//===----------------------------------------------------------------------===//
2100// Misc. API hooks.
2101//===----------------------------------------------------------------------===//
2102
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002103static llvm::sys::Mutex EnableMultithreadingMutex;
2104static bool EnabledMultithreading;
2105
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002106extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002107CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2108 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002109 // Disable pretty stack trace functionality, which will otherwise be a very
2110 // poor citizen of the world and set up all sorts of signal handlers.
2111 llvm::DisablePrettyStackTrace = true;
2112
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002113 // We use crash recovery to make some of our APIs more reliable, implicitly
2114 // enable it.
2115 llvm::CrashRecoveryContext::Enable();
2116
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002117 // Enable support for multithreading in LLVM.
2118 {
2119 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2120 if (!EnabledMultithreading) {
2121 llvm::llvm_start_multithreaded();
2122 EnabledMultithreading = true;
2123 }
2124 }
2125
Douglas Gregora030b7c2010-01-22 20:35:53 +00002126 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002127 if (excludeDeclarationsFromPCH)
2128 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002129 if (displayDiagnostics)
2130 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002131 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002132}
2133
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002134void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002135 if (CIdx)
2136 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002137}
2138
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002139CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002140 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002141 if (!CIdx)
2142 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002144 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002145 FileSystemOptions FileSystemOpts;
2146 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002147
Douglas Gregor28019772010-04-05 23:52:57 +00002148 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002149 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002150 CXXIdx->getOnlyLocalDecls(),
2151 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002152 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002153}
2154
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002155unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002156 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002157 CXTranslationUnit_CacheCompletionResults |
2158 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002159}
2160
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002161CXTranslationUnit
2162clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2163 const char *source_filename,
2164 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002165 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002166 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002167 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002168 return clang_parseTranslationUnit(CIdx, source_filename,
2169 command_line_args, num_command_line_args,
2170 unsaved_files, num_unsaved_files,
2171 CXTranslationUnit_DetailedPreprocessingRecord);
2172}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002173
2174struct ParseTranslationUnitInfo {
2175 CXIndex CIdx;
2176 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002177 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002178 int num_command_line_args;
2179 struct CXUnsavedFile *unsaved_files;
2180 unsigned num_unsaved_files;
2181 unsigned options;
2182 CXTranslationUnit result;
2183};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002184static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002185 ParseTranslationUnitInfo *PTUI =
2186 static_cast<ParseTranslationUnitInfo*>(UserData);
2187 CXIndex CIdx = PTUI->CIdx;
2188 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002189 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002190 int num_command_line_args = PTUI->num_command_line_args;
2191 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2192 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2193 unsigned options = PTUI->options;
2194 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002195
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002196 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002197 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002198
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002199 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2200
Douglas Gregor44c181a2010-07-23 00:33:23 +00002201 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002202 bool CompleteTranslationUnit
2203 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002204 bool CacheCodeCompetionResults
2205 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002206 bool CXXPrecompilePreamble
2207 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2208 bool CXXChainedPCH
2209 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002210
Douglas Gregor5352ac02010-01-28 00:27:43 +00002211 // Configure the diagnostics.
2212 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002213 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002214 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2215 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002216
Douglas Gregor4db64a42010-01-23 00:14:00 +00002217 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2218 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002219 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002220 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002221 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002222 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2223 Buffer));
2224 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002225
Douglas Gregorb10daed2010-10-11 16:52:23 +00002226 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002227
Ted Kremenek139ba862009-10-22 00:03:57 +00002228 // The 'source_filename' argument is optional. If the caller does not
2229 // specify it then it is assumed that the source file is specified
2230 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002231 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002232 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002233
2234 // Since the Clang C library is primarily used by batch tools dealing with
2235 // (often very broken) source code, where spell-checking can have a
2236 // significant negative impact on performance (particularly when
2237 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002238 // Only do this if we haven't found a spell-checking-related argument.
2239 bool FoundSpellCheckingArgument = false;
2240 for (int I = 0; I != num_command_line_args; ++I) {
2241 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2242 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2243 FoundSpellCheckingArgument = true;
2244 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002245 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002246 }
2247 if (!FoundSpellCheckingArgument)
2248 Args.push_back("-fno-spell-checking");
2249
2250 Args.insert(Args.end(), command_line_args,
2251 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002252
Douglas Gregor44c181a2010-07-23 00:33:23 +00002253 // Do we need the detailed preprocessing record?
2254 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002255 Args.push_back("-Xclang");
2256 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002257 }
2258
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002259 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002260 llvm::OwningPtr<ASTUnit> Unit(
2261 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2262 Diags,
2263 CXXIdx->getClangResourcesPath(),
2264 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002265 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002266 RemappedFiles.data(),
2267 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002268 PrecompilePreamble,
2269 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002270 CacheCodeCompetionResults,
2271 CXXPrecompilePreamble,
2272 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002273
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002274 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002275 // Make sure to check that 'Unit' is non-NULL.
2276 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2277 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2278 DEnd = Unit->stored_diag_end();
2279 D != DEnd; ++D) {
2280 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2281 CXString Msg = clang_formatDiagnostic(&Diag,
2282 clang_defaultDiagnosticDisplayOptions());
2283 fprintf(stderr, "%s\n", clang_getCString(Msg));
2284 clang_disposeString(Msg);
2285 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002286#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002287 // On Windows, force a flush, since there may be multiple copies of
2288 // stderr and stdout in the file system, all with different buffers
2289 // but writing to the same device.
2290 fflush(stderr);
2291#endif
2292 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002293 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002294
Ted Kremeneka60ed472010-11-16 08:15:36 +00002295 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002296}
2297CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2298 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002299 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002300 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002301 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002302 unsigned num_unsaved_files,
2303 unsigned options) {
2304 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002305 num_command_line_args, unsaved_files,
2306 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002307 llvm::CrashRecoveryContext CRC;
2308
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002309 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002310 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2311 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2312 fprintf(stderr, " 'command_line_args' : [");
2313 for (int i = 0; i != num_command_line_args; ++i) {
2314 if (i)
2315 fprintf(stderr, ", ");
2316 fprintf(stderr, "'%s'", command_line_args[i]);
2317 }
2318 fprintf(stderr, "],\n");
2319 fprintf(stderr, " 'unsaved_files' : [");
2320 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2321 if (i)
2322 fprintf(stderr, ", ");
2323 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2324 unsaved_files[i].Length);
2325 }
2326 fprintf(stderr, "],\n");
2327 fprintf(stderr, " 'options' : %d,\n", options);
2328 fprintf(stderr, "}\n");
2329
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002330 return 0;
2331 }
2332
2333 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002334}
2335
Douglas Gregor19998442010-08-13 15:35:05 +00002336unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2337 return CXSaveTranslationUnit_None;
2338}
2339
2340int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2341 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002342 if (!TU)
2343 return 1;
2344
Ted Kremeneka60ed472010-11-16 08:15:36 +00002345 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002346}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002347
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002348void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002349 if (CTUnit) {
2350 // If the translation unit has been marked as unsafe to free, just discard
2351 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002352 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002353 return;
2354
Ted Kremeneka60ed472010-11-16 08:15:36 +00002355 delete static_cast<ASTUnit *>(CTUnit->TUData);
2356 disposeCXStringPool(CTUnit->StringPool);
2357 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002358 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002359}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002360
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002361unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2362 return CXReparse_None;
2363}
2364
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002365struct ReparseTranslationUnitInfo {
2366 CXTranslationUnit TU;
2367 unsigned num_unsaved_files;
2368 struct CXUnsavedFile *unsaved_files;
2369 unsigned options;
2370 int result;
2371};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002372
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002373static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002374 ReparseTranslationUnitInfo *RTUI =
2375 static_cast<ReparseTranslationUnitInfo*>(UserData);
2376 CXTranslationUnit TU = RTUI->TU;
2377 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2378 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2379 unsigned options = RTUI->options;
2380 (void) options;
2381 RTUI->result = 1;
2382
Douglas Gregorabc563f2010-07-19 21:46:24 +00002383 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002384 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002385
Ted Kremeneka60ed472010-11-16 08:15:36 +00002386 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002387 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002388
2389 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2390 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2391 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2392 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002393 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002394 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2395 Buffer));
2396 }
2397
Douglas Gregor593b0c12010-09-23 18:47:53 +00002398 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2399 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002400}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002401
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002402int clang_reparseTranslationUnit(CXTranslationUnit TU,
2403 unsigned num_unsaved_files,
2404 struct CXUnsavedFile *unsaved_files,
2405 unsigned options) {
2406 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2407 options, 0 };
2408 llvm::CrashRecoveryContext CRC;
2409
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002410 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002411 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002412 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002413 return 1;
2414 }
2415
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002416
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002417 return RTUI.result;
2418}
2419
Douglas Gregordf95a132010-08-09 20:45:32 +00002420
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002421CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002422 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002423 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002424
Ted Kremeneka60ed472010-11-16 08:15:36 +00002425 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002426 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002427}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002428
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002429CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002430 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002431 return Result;
2432}
2433
Ted Kremenekfb480492010-01-13 21:46:36 +00002434} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002435
Ted Kremenekfb480492010-01-13 21:46:36 +00002436//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002437// CXSourceLocation and CXSourceRange Operations.
2438//===----------------------------------------------------------------------===//
2439
Douglas Gregorb9790342010-01-22 21:44:22 +00002440extern "C" {
2441CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002442 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002443 return Result;
2444}
2445
2446unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002447 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2448 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2449 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002450}
2451
2452CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2453 CXFile file,
2454 unsigned line,
2455 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002456 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002457 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002458
Ted Kremeneka60ed472010-11-16 08:15:36 +00002459 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002460 SourceLocation SLoc
2461 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002462 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002463 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002464 if (SLoc.isInvalid()) return clang_getNullLocation();
2465
2466 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2467}
2468
2469CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2470 CXFile file,
2471 unsigned offset) {
2472 if (!tu || !file)
2473 return clang_getNullLocation();
2474
Ted Kremeneka60ed472010-11-16 08:15:36 +00002475 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002476 SourceLocation Start
2477 = CXXUnit->getSourceManager().getLocation(
2478 static_cast<const FileEntry *>(file),
2479 1, 1);
2480 if (Start.isInvalid()) return clang_getNullLocation();
2481
2482 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2483
2484 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002485
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002486 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002487}
2488
Douglas Gregor5352ac02010-01-28 00:27:43 +00002489CXSourceRange clang_getNullRange() {
2490 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2491 return Result;
2492}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002493
Douglas Gregor5352ac02010-01-28 00:27:43 +00002494CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2495 if (begin.ptr_data[0] != end.ptr_data[0] ||
2496 begin.ptr_data[1] != end.ptr_data[1])
2497 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002498
2499 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002500 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002501 return Result;
2502}
2503
Douglas Gregor46766dc2010-01-26 19:19:08 +00002504void clang_getInstantiationLocation(CXSourceLocation location,
2505 CXFile *file,
2506 unsigned *line,
2507 unsigned *column,
2508 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002509 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2510
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002511 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002512 if (file)
2513 *file = 0;
2514 if (line)
2515 *line = 0;
2516 if (column)
2517 *column = 0;
2518 if (offset)
2519 *offset = 0;
2520 return;
2521 }
2522
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002523 const SourceManager &SM =
2524 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002525 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002526
2527 if (file)
2528 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2529 if (line)
2530 *line = SM.getInstantiationLineNumber(InstLoc);
2531 if (column)
2532 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002533 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002534 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002535}
2536
Douglas Gregora9b06d42010-11-09 06:24:54 +00002537void clang_getSpellingLocation(CXSourceLocation location,
2538 CXFile *file,
2539 unsigned *line,
2540 unsigned *column,
2541 unsigned *offset) {
2542 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2543
2544 if (!location.ptr_data[0] || Loc.isInvalid()) {
2545 if (file)
2546 *file = 0;
2547 if (line)
2548 *line = 0;
2549 if (column)
2550 *column = 0;
2551 if (offset)
2552 *offset = 0;
2553 return;
2554 }
2555
2556 const SourceManager &SM =
2557 *static_cast<const SourceManager*>(location.ptr_data[0]);
2558 SourceLocation SpellLoc = Loc;
2559 if (SpellLoc.isMacroID()) {
2560 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2561 if (SimpleSpellingLoc.isFileID() &&
2562 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2563 SpellLoc = SimpleSpellingLoc;
2564 else
2565 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2566 }
2567
2568 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2569 FileID FID = LocInfo.first;
2570 unsigned FileOffset = LocInfo.second;
2571
2572 if (file)
2573 *file = (void *)SM.getFileEntryForID(FID);
2574 if (line)
2575 *line = SM.getLineNumber(FID, FileOffset);
2576 if (column)
2577 *column = SM.getColumnNumber(FID, FileOffset);
2578 if (offset)
2579 *offset = FileOffset;
2580}
2581
Douglas Gregor1db19de2010-01-19 21:36:55 +00002582CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002583 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002584 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002585 return Result;
2586}
2587
2588CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002589 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002590 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002591 return Result;
2592}
2593
Douglas Gregorb9790342010-01-22 21:44:22 +00002594} // end: extern "C"
2595
Douglas Gregor1db19de2010-01-19 21:36:55 +00002596//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002597// CXFile Operations.
2598//===----------------------------------------------------------------------===//
2599
2600extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002601CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002602 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002603 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002604
Steve Naroff88145032009-10-27 14:35:18 +00002605 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002606 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002607}
2608
2609time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002610 if (!SFile)
2611 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002612
Steve Naroff88145032009-10-27 14:35:18 +00002613 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2614 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002615}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002616
Douglas Gregorb9790342010-01-22 21:44:22 +00002617CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2618 if (!tu)
2619 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002620
Ted Kremeneka60ed472010-11-16 08:15:36 +00002621 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002622
Douglas Gregorb9790342010-01-22 21:44:22 +00002623 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002624 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002625}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002626
Ted Kremenekfb480492010-01-13 21:46:36 +00002627} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002628
Ted Kremenekfb480492010-01-13 21:46:36 +00002629//===----------------------------------------------------------------------===//
2630// CXCursor Operations.
2631//===----------------------------------------------------------------------===//
2632
Ted Kremenekfb480492010-01-13 21:46:36 +00002633static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002634 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2635 return getDeclFromExpr(CE->getSubExpr());
2636
Ted Kremenekfb480492010-01-13 21:46:36 +00002637 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2638 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002639 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2640 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002641 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2642 return ME->getMemberDecl();
2643 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2644 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002645 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002646 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002647
Ted Kremenekfb480492010-01-13 21:46:36 +00002648 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2649 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002650 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2651 if (!CE->isElidable())
2652 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002653 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2654 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002655
Douglas Gregordb1314e2010-10-01 21:11:22 +00002656 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2657 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002658 if (SubstNonTypeTemplateParmPackExpr *NTTP
2659 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2660 return NTTP->getParameterPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002661
Ted Kremenekfb480492010-01-13 21:46:36 +00002662 return 0;
2663}
2664
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002665static SourceLocation getLocationFromExpr(Expr *E) {
2666 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2667 return /*FIXME:*/Msg->getLeftLoc();
2668 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2669 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002670 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2671 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002672 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2673 return Member->getMemberLoc();
2674 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2675 return Ivar->getLocation();
2676 return E->getLocStart();
2677}
2678
Ted Kremenekfb480492010-01-13 21:46:36 +00002679extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002680
2681unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002682 CXCursorVisitor visitor,
2683 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002684 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2685 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002686 return CursorVis.VisitChildren(parent);
2687}
2688
David Chisnall3387c652010-11-03 14:12:26 +00002689#ifndef __has_feature
2690#define __has_feature(x) 0
2691#endif
2692#if __has_feature(blocks)
2693typedef enum CXChildVisitResult
2694 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2695
2696static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2697 CXClientData client_data) {
2698 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2699 return block(cursor, parent);
2700}
2701#else
2702// If we are compiled with a compiler that doesn't have native blocks support,
2703// define and call the block manually, so the
2704typedef struct _CXChildVisitResult
2705{
2706 void *isa;
2707 int flags;
2708 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002709 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2710 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002711} *CXCursorVisitorBlock;
2712
2713static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2714 CXClientData client_data) {
2715 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2716 return block->invoke(block, cursor, parent);
2717}
2718#endif
2719
2720
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002721unsigned clang_visitChildrenWithBlock(CXCursor parent,
2722 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002723 return clang_visitChildren(parent, visitWithBlock, block);
2724}
2725
Douglas Gregor78205d42010-01-20 21:45:58 +00002726static CXString getDeclSpelling(Decl *D) {
2727 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002728 if (!ND) {
2729 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2730 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2731 return createCXString(Property->getIdentifier()->getName());
2732
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002733 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002734 }
2735
Douglas Gregor78205d42010-01-20 21:45:58 +00002736 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002737 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002738
Douglas Gregor78205d42010-01-20 21:45:58 +00002739 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2740 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2741 // and returns different names. NamedDecl returns the class name and
2742 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002743 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002744
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002745 if (isa<UsingDirectiveDecl>(D))
2746 return createCXString("");
2747
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002748 llvm::SmallString<1024> S;
2749 llvm::raw_svector_ostream os(S);
2750 ND->printName(os);
2751
2752 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002753}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002754
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002755CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002756 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002757 return clang_getTranslationUnitSpelling(
2758 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002759
Steve Narofff334b4e2009-09-02 18:26:48 +00002760 if (clang_isReference(C.kind)) {
2761 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002762 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002763 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002764 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002765 }
2766 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002767 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002768 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002769 }
2770 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002771 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002772 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002773 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002774 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002775 case CXCursor_CXXBaseSpecifier: {
2776 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2777 return createCXString(B->getType().getAsString());
2778 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002779 case CXCursor_TypeRef: {
2780 TypeDecl *Type = getCursorTypeRef(C).first;
2781 assert(Type && "Missing type decl");
2782
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002783 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2784 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002785 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002786 case CXCursor_TemplateRef: {
2787 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002788 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002789
2790 return createCXString(Template->getNameAsString());
2791 }
Douglas Gregor69319002010-08-31 23:48:11 +00002792
2793 case CXCursor_NamespaceRef: {
2794 NamedDecl *NS = getCursorNamespaceRef(C).first;
2795 assert(NS && "Missing namespace decl");
2796
2797 return createCXString(NS->getNameAsString());
2798 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002799
Douglas Gregora67e03f2010-09-09 21:42:20 +00002800 case CXCursor_MemberRef: {
2801 FieldDecl *Field = getCursorMemberRef(C).first;
2802 assert(Field && "Missing member decl");
2803
2804 return createCXString(Field->getNameAsString());
2805 }
2806
Douglas Gregor36897b02010-09-10 00:22:18 +00002807 case CXCursor_LabelRef: {
2808 LabelStmt *Label = getCursorLabelRef(C).first;
2809 assert(Label && "Missing label");
2810
2811 return createCXString(Label->getID()->getName());
2812 }
2813
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002814 case CXCursor_OverloadedDeclRef: {
2815 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2816 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2817 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2818 return createCXString(ND->getNameAsString());
2819 return createCXString("");
2820 }
2821 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2822 return createCXString(E->getName().getAsString());
2823 OverloadedTemplateStorage *Ovl
2824 = Storage.get<OverloadedTemplateStorage*>();
2825 if (Ovl->size() == 0)
2826 return createCXString("");
2827 return createCXString((*Ovl->begin())->getNameAsString());
2828 }
2829
Daniel Dunbaracca7252009-11-30 20:42:49 +00002830 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002831 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002832 }
2833 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002834
2835 if (clang_isExpression(C.kind)) {
2836 Decl *D = getDeclFromExpr(getCursorExpr(C));
2837 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002838 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002839 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002840 }
2841
Douglas Gregor36897b02010-09-10 00:22:18 +00002842 if (clang_isStatement(C.kind)) {
2843 Stmt *S = getCursorStmt(C);
2844 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2845 return createCXString(Label->getID()->getName());
2846
2847 return createCXString("");
2848 }
2849
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002850 if (C.kind == CXCursor_MacroInstantiation)
2851 return createCXString(getCursorMacroInstantiation(C)->getName()
2852 ->getNameStart());
2853
Douglas Gregor572feb22010-03-18 18:04:21 +00002854 if (C.kind == CXCursor_MacroDefinition)
2855 return createCXString(getCursorMacroDefinition(C)->getName()
2856 ->getNameStart());
2857
Douglas Gregorecdcb882010-10-20 22:00:55 +00002858 if (C.kind == CXCursor_InclusionDirective)
2859 return createCXString(getCursorInclusionDirective(C)->getFileName());
2860
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002861 if (clang_isDeclaration(C.kind))
2862 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002863
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002864 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002865}
2866
Douglas Gregor358559d2010-10-02 22:49:11 +00002867CXString clang_getCursorDisplayName(CXCursor C) {
2868 if (!clang_isDeclaration(C.kind))
2869 return clang_getCursorSpelling(C);
2870
2871 Decl *D = getCursorDecl(C);
2872 if (!D)
2873 return createCXString("");
2874
2875 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2876 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2877 D = FunTmpl->getTemplatedDecl();
2878
2879 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2880 llvm::SmallString<64> Str;
2881 llvm::raw_svector_ostream OS(Str);
2882 OS << Function->getNameAsString();
2883 if (Function->getPrimaryTemplate())
2884 OS << "<>";
2885 OS << "(";
2886 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2887 if (I)
2888 OS << ", ";
2889 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2890 }
2891
2892 if (Function->isVariadic()) {
2893 if (Function->getNumParams())
2894 OS << ", ";
2895 OS << "...";
2896 }
2897 OS << ")";
2898 return createCXString(OS.str());
2899 }
2900
2901 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2902 llvm::SmallString<64> Str;
2903 llvm::raw_svector_ostream OS(Str);
2904 OS << ClassTemplate->getNameAsString();
2905 OS << "<";
2906 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2907 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2908 if (I)
2909 OS << ", ";
2910
2911 NamedDecl *Param = Params->getParam(I);
2912 if (Param->getIdentifier()) {
2913 OS << Param->getIdentifier()->getName();
2914 continue;
2915 }
2916
2917 // There is no parameter name, which makes this tricky. Try to come up
2918 // with something useful that isn't too long.
2919 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2920 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2921 else if (NonTypeTemplateParmDecl *NTTP
2922 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2923 OS << NTTP->getType().getAsString(Policy);
2924 else
2925 OS << "template<...> class";
2926 }
2927
2928 OS << ">";
2929 return createCXString(OS.str());
2930 }
2931
2932 if (ClassTemplateSpecializationDecl *ClassSpec
2933 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2934 // If the type was explicitly written, use that.
2935 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2936 return createCXString(TSInfo->getType().getAsString(Policy));
2937
2938 llvm::SmallString<64> Str;
2939 llvm::raw_svector_ostream OS(Str);
2940 OS << ClassSpec->getNameAsString();
2941 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002942 ClassSpec->getTemplateArgs().data(),
2943 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002944 Policy);
2945 return createCXString(OS.str());
2946 }
2947
2948 return clang_getCursorSpelling(C);
2949}
2950
Ted Kremeneke68fff62010-02-17 00:41:32 +00002951CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002952 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002953 case CXCursor_FunctionDecl:
2954 return createCXString("FunctionDecl");
2955 case CXCursor_TypedefDecl:
2956 return createCXString("TypedefDecl");
2957 case CXCursor_EnumDecl:
2958 return createCXString("EnumDecl");
2959 case CXCursor_EnumConstantDecl:
2960 return createCXString("EnumConstantDecl");
2961 case CXCursor_StructDecl:
2962 return createCXString("StructDecl");
2963 case CXCursor_UnionDecl:
2964 return createCXString("UnionDecl");
2965 case CXCursor_ClassDecl:
2966 return createCXString("ClassDecl");
2967 case CXCursor_FieldDecl:
2968 return createCXString("FieldDecl");
2969 case CXCursor_VarDecl:
2970 return createCXString("VarDecl");
2971 case CXCursor_ParmDecl:
2972 return createCXString("ParmDecl");
2973 case CXCursor_ObjCInterfaceDecl:
2974 return createCXString("ObjCInterfaceDecl");
2975 case CXCursor_ObjCCategoryDecl:
2976 return createCXString("ObjCCategoryDecl");
2977 case CXCursor_ObjCProtocolDecl:
2978 return createCXString("ObjCProtocolDecl");
2979 case CXCursor_ObjCPropertyDecl:
2980 return createCXString("ObjCPropertyDecl");
2981 case CXCursor_ObjCIvarDecl:
2982 return createCXString("ObjCIvarDecl");
2983 case CXCursor_ObjCInstanceMethodDecl:
2984 return createCXString("ObjCInstanceMethodDecl");
2985 case CXCursor_ObjCClassMethodDecl:
2986 return createCXString("ObjCClassMethodDecl");
2987 case CXCursor_ObjCImplementationDecl:
2988 return createCXString("ObjCImplementationDecl");
2989 case CXCursor_ObjCCategoryImplDecl:
2990 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002991 case CXCursor_CXXMethod:
2992 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002993 case CXCursor_UnexposedDecl:
2994 return createCXString("UnexposedDecl");
2995 case CXCursor_ObjCSuperClassRef:
2996 return createCXString("ObjCSuperClassRef");
2997 case CXCursor_ObjCProtocolRef:
2998 return createCXString("ObjCProtocolRef");
2999 case CXCursor_ObjCClassRef:
3000 return createCXString("ObjCClassRef");
3001 case CXCursor_TypeRef:
3002 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003003 case CXCursor_TemplateRef:
3004 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003005 case CXCursor_NamespaceRef:
3006 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003007 case CXCursor_MemberRef:
3008 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003009 case CXCursor_LabelRef:
3010 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003011 case CXCursor_OverloadedDeclRef:
3012 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003013 case CXCursor_UnexposedExpr:
3014 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003015 case CXCursor_BlockExpr:
3016 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003017 case CXCursor_DeclRefExpr:
3018 return createCXString("DeclRefExpr");
3019 case CXCursor_MemberRefExpr:
3020 return createCXString("MemberRefExpr");
3021 case CXCursor_CallExpr:
3022 return createCXString("CallExpr");
3023 case CXCursor_ObjCMessageExpr:
3024 return createCXString("ObjCMessageExpr");
3025 case CXCursor_UnexposedStmt:
3026 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003027 case CXCursor_LabelStmt:
3028 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003029 case CXCursor_InvalidFile:
3030 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003031 case CXCursor_InvalidCode:
3032 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003033 case CXCursor_NoDeclFound:
3034 return createCXString("NoDeclFound");
3035 case CXCursor_NotImplemented:
3036 return createCXString("NotImplemented");
3037 case CXCursor_TranslationUnit:
3038 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003039 case CXCursor_UnexposedAttr:
3040 return createCXString("UnexposedAttr");
3041 case CXCursor_IBActionAttr:
3042 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003043 case CXCursor_IBOutletAttr:
3044 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003045 case CXCursor_IBOutletCollectionAttr:
3046 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003047 case CXCursor_PreprocessingDirective:
3048 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003049 case CXCursor_MacroDefinition:
3050 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003051 case CXCursor_MacroInstantiation:
3052 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003053 case CXCursor_InclusionDirective:
3054 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003055 case CXCursor_Namespace:
3056 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003057 case CXCursor_LinkageSpec:
3058 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003059 case CXCursor_CXXBaseSpecifier:
3060 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003061 case CXCursor_Constructor:
3062 return createCXString("CXXConstructor");
3063 case CXCursor_Destructor:
3064 return createCXString("CXXDestructor");
3065 case CXCursor_ConversionFunction:
3066 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003067 case CXCursor_TemplateTypeParameter:
3068 return createCXString("TemplateTypeParameter");
3069 case CXCursor_NonTypeTemplateParameter:
3070 return createCXString("NonTypeTemplateParameter");
3071 case CXCursor_TemplateTemplateParameter:
3072 return createCXString("TemplateTemplateParameter");
3073 case CXCursor_FunctionTemplate:
3074 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003075 case CXCursor_ClassTemplate:
3076 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003077 case CXCursor_ClassTemplatePartialSpecialization:
3078 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003079 case CXCursor_NamespaceAlias:
3080 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003081 case CXCursor_UsingDirective:
3082 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003083 case CXCursor_UsingDeclaration:
3084 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003085 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003086
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003087 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003088 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003089}
Steve Naroff89922f82009-08-31 00:59:03 +00003090
Ted Kremeneke68fff62010-02-17 00:41:32 +00003091enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3092 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003093 CXClientData client_data) {
3094 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003095
3096 // If our current best cursor is the construction of a temporary object,
3097 // don't replace that cursor with a type reference, because we want
3098 // clang_getCursor() to point at the constructor.
3099 if (clang_isExpression(BestCursor->kind) &&
3100 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3101 cursor.kind == CXCursor_TypeRef)
3102 return CXChildVisit_Recurse;
3103
Douglas Gregor85fe1562010-12-10 07:23:11 +00003104 // Don't override a preprocessing cursor with another preprocessing
3105 // cursor; we want the outermost preprocessing cursor.
3106 if (clang_isPreprocessing(cursor.kind) &&
3107 clang_isPreprocessing(BestCursor->kind))
3108 return CXChildVisit_Recurse;
3109
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003110 *BestCursor = cursor;
3111 return CXChildVisit_Recurse;
3112}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003113
Douglas Gregorb9790342010-01-22 21:44:22 +00003114CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3115 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003116 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003117
Ted Kremeneka60ed472010-11-16 08:15:36 +00003118 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003119 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3120
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003121 // Translate the given source location to make it point at the beginning of
3122 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003123 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003124
3125 // Guard against an invalid SourceLocation, or we may assert in one
3126 // of the following calls.
3127 if (SLoc.isInvalid())
3128 return clang_getNullCursor();
3129
Douglas Gregor40749ee2010-11-03 00:35:38 +00003130 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003131 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3132 CXXUnit->getASTContext().getLangOptions());
3133
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003134 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3135 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003136 // FIXME: Would be great to have a "hint" cursor, then walk from that
3137 // hint cursor upward until we find a cursor whose source range encloses
3138 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003139 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3140 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003141 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003142 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003143 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003144
3145 if (Logging) {
3146 CXFile SearchFile;
3147 unsigned SearchLine, SearchColumn;
3148 CXFile ResultFile;
3149 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003150 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3151 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003152 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3153
3154 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3155 0);
3156 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3157 &ResultColumn, 0);
3158 SearchFileName = clang_getFileName(SearchFile);
3159 ResultFileName = clang_getFileName(ResultFile);
3160 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003161 USR = clang_getCursorUSR(Result);
3162 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003163 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3164 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003165 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3166 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003167 clang_disposeString(SearchFileName);
3168 clang_disposeString(ResultFileName);
3169 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003170 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003171
3172 CXCursor Definition = clang_getCursorDefinition(Result);
3173 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3174 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3175 CXString DefinitionKindSpelling
3176 = clang_getCursorKindSpelling(Definition.kind);
3177 CXFile DefinitionFile;
3178 unsigned DefinitionLine, DefinitionColumn;
3179 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3180 &DefinitionLine, &DefinitionColumn, 0);
3181 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3182 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3183 clang_getCString(DefinitionKindSpelling),
3184 clang_getCString(DefinitionFileName),
3185 DefinitionLine, DefinitionColumn);
3186 clang_disposeString(DefinitionFileName);
3187 clang_disposeString(DefinitionKindSpelling);
3188 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003189 }
3190
Ted Kremeneke68fff62010-02-17 00:41:32 +00003191 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003192}
3193
Ted Kremenek73885552009-11-17 19:28:59 +00003194CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003195 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003196}
3197
3198unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003199 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003200}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003201
Douglas Gregor9ce55842010-11-20 00:09:34 +00003202unsigned clang_hashCursor(CXCursor C) {
3203 unsigned Index = 0;
3204 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3205 Index = 1;
3206
3207 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3208 std::make_pair(C.kind, C.data[Index]));
3209}
3210
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003211unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003212 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3213}
3214
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003215unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003216 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3217}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003218
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003219unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003220 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3221}
3222
Douglas Gregor97b98722010-01-19 23:20:36 +00003223unsigned clang_isExpression(enum CXCursorKind K) {
3224 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3225}
3226
3227unsigned clang_isStatement(enum CXCursorKind K) {
3228 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3229}
3230
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003231unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3232 return K == CXCursor_TranslationUnit;
3233}
3234
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003235unsigned clang_isPreprocessing(enum CXCursorKind K) {
3236 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3237}
3238
Ted Kremenekad6eff62010-03-08 21:17:29 +00003239unsigned clang_isUnexposed(enum CXCursorKind K) {
3240 switch (K) {
3241 case CXCursor_UnexposedDecl:
3242 case CXCursor_UnexposedExpr:
3243 case CXCursor_UnexposedStmt:
3244 case CXCursor_UnexposedAttr:
3245 return true;
3246 default:
3247 return false;
3248 }
3249}
3250
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003251CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003252 return C.kind;
3253}
3254
Douglas Gregor98258af2010-01-18 22:46:11 +00003255CXSourceLocation clang_getCursorLocation(CXCursor C) {
3256 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003257 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003258 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003259 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3260 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003261 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003262 }
3263
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003264 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003265 std::pair<ObjCProtocolDecl *, SourceLocation> P
3266 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003267 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003268 }
3269
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003270 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003271 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3272 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003273 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003274 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003275
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003276 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003277 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003278 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003279 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003280
3281 case CXCursor_TemplateRef: {
3282 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3283 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3284 }
3285
Douglas Gregor69319002010-08-31 23:48:11 +00003286 case CXCursor_NamespaceRef: {
3287 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3288 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3289 }
3290
Douglas Gregora67e03f2010-09-09 21:42:20 +00003291 case CXCursor_MemberRef: {
3292 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3293 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3294 }
3295
Ted Kremenek3064ef92010-08-27 21:34:58 +00003296 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003297 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3298 if (!BaseSpec)
3299 return clang_getNullLocation();
3300
3301 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3302 return cxloc::translateSourceLocation(getCursorContext(C),
3303 TSInfo->getTypeLoc().getBeginLoc());
3304
3305 return cxloc::translateSourceLocation(getCursorContext(C),
3306 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003307 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003308
Douglas Gregor36897b02010-09-10 00:22:18 +00003309 case CXCursor_LabelRef: {
3310 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3311 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3312 }
3313
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003314 case CXCursor_OverloadedDeclRef:
3315 return cxloc::translateSourceLocation(getCursorContext(C),
3316 getCursorOverloadedDeclRef(C).second);
3317
Douglas Gregorf46034a2010-01-18 23:41:10 +00003318 default:
3319 // FIXME: Need a way to enumerate all non-reference cases.
3320 llvm_unreachable("Missed a reference kind");
3321 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003322 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003323
3324 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003325 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003326 getLocationFromExpr(getCursorExpr(C)));
3327
Douglas Gregor36897b02010-09-10 00:22:18 +00003328 if (clang_isStatement(C.kind))
3329 return cxloc::translateSourceLocation(getCursorContext(C),
3330 getCursorStmt(C)->getLocStart());
3331
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003332 if (C.kind == CXCursor_PreprocessingDirective) {
3333 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3334 return cxloc::translateSourceLocation(getCursorContext(C), L);
3335 }
Douglas Gregor48072312010-03-18 15:23:44 +00003336
3337 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003338 SourceLocation L
3339 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003340 return cxloc::translateSourceLocation(getCursorContext(C), L);
3341 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003342
3343 if (C.kind == CXCursor_MacroDefinition) {
3344 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3345 return cxloc::translateSourceLocation(getCursorContext(C), L);
3346 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003347
3348 if (C.kind == CXCursor_InclusionDirective) {
3349 SourceLocation L
3350 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3351 return cxloc::translateSourceLocation(getCursorContext(C), L);
3352 }
3353
Ted Kremenek9a700d22010-05-12 06:16:13 +00003354 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003355 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003356
Douglas Gregorf46034a2010-01-18 23:41:10 +00003357 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003358 SourceLocation Loc = D->getLocation();
3359 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3360 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003361 // FIXME: Multiple variables declared in a single declaration
3362 // currently lack the information needed to correctly determine their
3363 // ranges when accounting for the type-specifier. We use context
3364 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3365 // and if so, whether it is the first decl.
3366 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3367 if (!cxcursor::isFirstInDeclGroup(C))
3368 Loc = VD->getLocation();
3369 }
3370
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003371 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003372}
Douglas Gregora7bde202010-01-19 00:34:46 +00003373
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003374} // end extern "C"
3375
3376static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003377 if (clang_isReference(C.kind)) {
3378 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003379 case CXCursor_ObjCSuperClassRef:
3380 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003381
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003382 case CXCursor_ObjCProtocolRef:
3383 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003384
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003385 case CXCursor_ObjCClassRef:
3386 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003387
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003388 case CXCursor_TypeRef:
3389 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003390
3391 case CXCursor_TemplateRef:
3392 return getCursorTemplateRef(C).second;
3393
Douglas Gregor69319002010-08-31 23:48:11 +00003394 case CXCursor_NamespaceRef:
3395 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003396
3397 case CXCursor_MemberRef:
3398 return getCursorMemberRef(C).second;
3399
Ted Kremenek3064ef92010-08-27 21:34:58 +00003400 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003401 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003402
Douglas Gregor36897b02010-09-10 00:22:18 +00003403 case CXCursor_LabelRef:
3404 return getCursorLabelRef(C).second;
3405
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003406 case CXCursor_OverloadedDeclRef:
3407 return getCursorOverloadedDeclRef(C).second;
3408
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003409 default:
3410 // FIXME: Need a way to enumerate all non-reference cases.
3411 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003412 }
3413 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003414
3415 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003416 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003417
3418 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003419 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003420
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003421 if (C.kind == CXCursor_PreprocessingDirective)
3422 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003423
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003424 if (C.kind == CXCursor_MacroInstantiation)
3425 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003426
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003427 if (C.kind == CXCursor_MacroDefinition)
3428 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003429
3430 if (C.kind == CXCursor_InclusionDirective)
3431 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3432
Ted Kremenek007a7c92010-11-01 23:26:51 +00003433 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3434 Decl *D = cxcursor::getCursorDecl(C);
3435 SourceRange R = D->getSourceRange();
3436 // FIXME: Multiple variables declared in a single declaration
3437 // currently lack the information needed to correctly determine their
3438 // ranges when accounting for the type-specifier. We use context
3439 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3440 // and if so, whether it is the first decl.
3441 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3442 if (!cxcursor::isFirstInDeclGroup(C))
3443 R.setBegin(VD->getLocation());
3444 }
3445 return R;
3446 }
Douglas Gregor66537982010-11-17 17:14:07 +00003447 return SourceRange();
3448}
3449
3450/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3451/// the decl-specifier-seq for declarations.
3452static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3453 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3454 Decl *D = cxcursor::getCursorDecl(C);
3455 SourceRange R = D->getSourceRange();
3456
3457 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3458 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3459 TypeLoc TL = TI->getTypeLoc();
3460 SourceLocation TLoc = TL.getSourceRange().getBegin();
3461 if (TLoc.isValid() && R.getBegin().isValid() &&
3462 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3463 R.setBegin(TLoc);
3464 }
3465
3466 // FIXME: Multiple variables declared in a single declaration
3467 // currently lack the information needed to correctly determine their
3468 // ranges when accounting for the type-specifier. We use context
3469 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3470 // and if so, whether it is the first decl.
3471 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3472 if (!cxcursor::isFirstInDeclGroup(C))
3473 R.setBegin(VD->getLocation());
3474 }
3475 }
3476
3477 return R;
3478 }
3479
3480 return getRawCursorExtent(C);
3481}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003482
3483extern "C" {
3484
3485CXSourceRange clang_getCursorExtent(CXCursor C) {
3486 SourceRange R = getRawCursorExtent(C);
3487 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003488 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003489
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003490 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003491}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003492
3493CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003494 if (clang_isInvalid(C.kind))
3495 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003496
Ted Kremeneka60ed472010-11-16 08:15:36 +00003497 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003498 if (clang_isDeclaration(C.kind)) {
3499 Decl *D = getCursorDecl(C);
3500 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003501 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003502 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003503 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003504 if (ObjCForwardProtocolDecl *Protocols
3505 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003506 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003507 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3508 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3509 return MakeCXCursor(Property, tu);
3510
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003511 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003512 }
3513
Douglas Gregor97b98722010-01-19 23:20:36 +00003514 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003515 Expr *E = getCursorExpr(C);
3516 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003517 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003518 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003519
3520 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003521 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003522
Douglas Gregor97b98722010-01-19 23:20:36 +00003523 return clang_getNullCursor();
3524 }
3525
Douglas Gregor36897b02010-09-10 00:22:18 +00003526 if (clang_isStatement(C.kind)) {
3527 Stmt *S = getCursorStmt(C);
3528 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003529 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003530
3531 return clang_getNullCursor();
3532 }
3533
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003534 if (C.kind == CXCursor_MacroInstantiation) {
3535 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003536 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003537 }
3538
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003539 if (!clang_isReference(C.kind))
3540 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003541
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003542 switch (C.kind) {
3543 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003544 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003545
3546 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003547 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003548
3549 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003550 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003551
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003552 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003553 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003554
3555 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003556 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003557
Douglas Gregor69319002010-08-31 23:48:11 +00003558 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003559 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003560
Douglas Gregora67e03f2010-09-09 21:42:20 +00003561 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003562 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003563
Ted Kremenek3064ef92010-08-27 21:34:58 +00003564 case CXCursor_CXXBaseSpecifier: {
3565 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3566 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003567 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003568 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003569
Douglas Gregor36897b02010-09-10 00:22:18 +00003570 case CXCursor_LabelRef:
3571 // FIXME: We end up faking the "parent" declaration here because we
3572 // don't want to make CXCursor larger.
3573 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003574 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3575 .getTranslationUnitDecl(),
3576 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003577
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003578 case CXCursor_OverloadedDeclRef:
3579 return C;
3580
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003581 default:
3582 // We would prefer to enumerate all non-reference cursor kinds here.
3583 llvm_unreachable("Unhandled reference cursor kind");
3584 break;
3585 }
3586 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003587
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003588 return clang_getNullCursor();
3589}
3590
Douglas Gregorb6998662010-01-19 19:34:47 +00003591CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003592 if (clang_isInvalid(C.kind))
3593 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003594
Ted Kremeneka60ed472010-11-16 08:15:36 +00003595 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003596
Douglas Gregorb6998662010-01-19 19:34:47 +00003597 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003598 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003599 C = clang_getCursorReferenced(C);
3600 WasReference = true;
3601 }
3602
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003603 if (C.kind == CXCursor_MacroInstantiation)
3604 return clang_getCursorReferenced(C);
3605
Douglas Gregorb6998662010-01-19 19:34:47 +00003606 if (!clang_isDeclaration(C.kind))
3607 return clang_getNullCursor();
3608
3609 Decl *D = getCursorDecl(C);
3610 if (!D)
3611 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003612
Douglas Gregorb6998662010-01-19 19:34:47 +00003613 switch (D->getKind()) {
3614 // Declaration kinds that don't really separate the notions of
3615 // declaration and definition.
3616 case Decl::Namespace:
3617 case Decl::Typedef:
3618 case Decl::TemplateTypeParm:
3619 case Decl::EnumConstant:
3620 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003621 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003622 case Decl::ObjCIvar:
3623 case Decl::ObjCAtDefsField:
3624 case Decl::ImplicitParam:
3625 case Decl::ParmVar:
3626 case Decl::NonTypeTemplateParm:
3627 case Decl::TemplateTemplateParm:
3628 case Decl::ObjCCategoryImpl:
3629 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003630 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003631 case Decl::LinkageSpec:
3632 case Decl::ObjCPropertyImpl:
3633 case Decl::FileScopeAsm:
3634 case Decl::StaticAssert:
3635 case Decl::Block:
3636 return C;
3637
3638 // Declaration kinds that don't make any sense here, but are
3639 // nonetheless harmless.
3640 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003641 break;
3642
3643 // Declaration kinds for which the definition is not resolvable.
3644 case Decl::UnresolvedUsingTypename:
3645 case Decl::UnresolvedUsingValue:
3646 break;
3647
3648 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003649 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003650 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003651
3652 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003653 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003654
3655 case Decl::Enum:
3656 case Decl::Record:
3657 case Decl::CXXRecord:
3658 case Decl::ClassTemplateSpecialization:
3659 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003660 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003661 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003662 return clang_getNullCursor();
3663
3664 case Decl::Function:
3665 case Decl::CXXMethod:
3666 case Decl::CXXConstructor:
3667 case Decl::CXXDestructor:
3668 case Decl::CXXConversion: {
3669 const FunctionDecl *Def = 0;
3670 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003671 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003672 return clang_getNullCursor();
3673 }
3674
3675 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003676 // Ask the variable if it has a definition.
3677 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003678 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003679 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003680 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003681
Douglas Gregorb6998662010-01-19 19:34:47 +00003682 case Decl::FunctionTemplate: {
3683 const FunctionDecl *Def = 0;
3684 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003685 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003686 return clang_getNullCursor();
3687 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003688
Douglas Gregorb6998662010-01-19 19:34:47 +00003689 case Decl::ClassTemplate: {
3690 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003691 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003692 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003693 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003694 return clang_getNullCursor();
3695 }
3696
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003697 case Decl::Using:
3698 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003699 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003700
3701 case Decl::UsingShadow:
3702 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003703 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003704 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003705
3706 case Decl::ObjCMethod: {
3707 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3708 if (Method->isThisDeclarationADefinition())
3709 return C;
3710
3711 // Dig out the method definition in the associated
3712 // @implementation, if we have it.
3713 // FIXME: The ASTs should make finding the definition easier.
3714 if (ObjCInterfaceDecl *Class
3715 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3716 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3717 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3718 Method->isInstanceMethod()))
3719 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003720 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003721
3722 return clang_getNullCursor();
3723 }
3724
3725 case Decl::ObjCCategory:
3726 if (ObjCCategoryImplDecl *Impl
3727 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003728 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003729 return clang_getNullCursor();
3730
3731 case Decl::ObjCProtocol:
3732 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3733 return C;
3734 return clang_getNullCursor();
3735
3736 case Decl::ObjCInterface:
3737 // There are two notions of a "definition" for an Objective-C
3738 // class: the interface and its implementation. When we resolved a
3739 // reference to an Objective-C class, produce the @interface as
3740 // the definition; when we were provided with the interface,
3741 // produce the @implementation as the definition.
3742 if (WasReference) {
3743 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3744 return C;
3745 } else if (ObjCImplementationDecl *Impl
3746 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003747 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003748 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003749
Douglas Gregorb6998662010-01-19 19:34:47 +00003750 case Decl::ObjCProperty:
3751 // FIXME: We don't really know where to find the
3752 // ObjCPropertyImplDecls that implement this property.
3753 return clang_getNullCursor();
3754
3755 case Decl::ObjCCompatibleAlias:
3756 if (ObjCInterfaceDecl *Class
3757 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3758 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003759 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003760
Douglas Gregorb6998662010-01-19 19:34:47 +00003761 return clang_getNullCursor();
3762
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003763 case Decl::ObjCForwardProtocol:
3764 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003765 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003766
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003767 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003768 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003769 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003770
3771 case Decl::Friend:
3772 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003773 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003774 return clang_getNullCursor();
3775
3776 case Decl::FriendTemplate:
3777 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003778 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003779 return clang_getNullCursor();
3780 }
3781
3782 return clang_getNullCursor();
3783}
3784
3785unsigned clang_isCursorDefinition(CXCursor C) {
3786 if (!clang_isDeclaration(C.kind))
3787 return 0;
3788
3789 return clang_getCursorDefinition(C) == C;
3790}
3791
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003792CXCursor clang_getCanonicalCursor(CXCursor C) {
3793 if (!clang_isDeclaration(C.kind))
3794 return C;
3795
3796 if (Decl *D = getCursorDecl(C))
3797 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3798
3799 return C;
3800}
3801
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003802unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003803 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003804 return 0;
3805
3806 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3807 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3808 return E->getNumDecls();
3809
3810 if (OverloadedTemplateStorage *S
3811 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3812 return S->size();
3813
3814 Decl *D = Storage.get<Decl*>();
3815 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003816 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003817 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3818 return Classes->size();
3819 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3820 return Protocols->protocol_size();
3821
3822 return 0;
3823}
3824
3825CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003826 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003827 return clang_getNullCursor();
3828
3829 if (index >= clang_getNumOverloadedDecls(cursor))
3830 return clang_getNullCursor();
3831
Ted Kremeneka60ed472010-11-16 08:15:36 +00003832 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003833 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3834 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003835 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003836
3837 if (OverloadedTemplateStorage *S
3838 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003839 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003840
3841 Decl *D = Storage.get<Decl*>();
3842 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3843 // FIXME: This is, unfortunately, linear time.
3844 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3845 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003846 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003847 }
3848
3849 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003850 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003851
3852 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003853 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003854
3855 return clang_getNullCursor();
3856}
3857
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003858void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003859 const char **startBuf,
3860 const char **endBuf,
3861 unsigned *startLine,
3862 unsigned *startColumn,
3863 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003864 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003865 assert(getCursorDecl(C) && "CXCursor has null decl");
3866 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003867 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3868 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869
Steve Naroff4ade6d62009-09-23 17:52:52 +00003870 SourceManager &SM = FD->getASTContext().getSourceManager();
3871 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3872 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3873 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3874 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3875 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3876 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3877}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003878
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003879void clang_enableStackTraces(void) {
3880 llvm::sys::PrintStackTraceOnErrorSignal();
3881}
3882
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003883void clang_executeOnThread(void (*fn)(void*), void *user_data,
3884 unsigned stack_size) {
3885 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3886}
3887
Ted Kremenekfb480492010-01-13 21:46:36 +00003888} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003889
Ted Kremenekfb480492010-01-13 21:46:36 +00003890//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891// Token-based Operations.
3892//===----------------------------------------------------------------------===//
3893
3894/* CXToken layout:
3895 * int_data[0]: a CXTokenKind
3896 * int_data[1]: starting token location
3897 * int_data[2]: token length
3898 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003899 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003900 * otherwise unused.
3901 */
3902extern "C" {
3903
3904CXTokenKind clang_getTokenKind(CXToken CXTok) {
3905 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3906}
3907
3908CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3909 switch (clang_getTokenKind(CXTok)) {
3910 case CXToken_Identifier:
3911 case CXToken_Keyword:
3912 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003913 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3914 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003915
3916 case CXToken_Literal: {
3917 // We have stashed the starting pointer in the ptr_data field. Use it.
3918 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003919 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003920 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003921
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003922 case CXToken_Punctuation:
3923 case CXToken_Comment:
3924 break;
3925 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003926
3927 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003928 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003929 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003930 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003931 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003932
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003933 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3934 std::pair<FileID, unsigned> LocInfo
3935 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003936 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003937 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003938 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3939 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003940 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003941
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003942 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003943}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003944
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003945CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003946 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003947 if (!CXXUnit)
3948 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003949
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003950 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3951 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3952}
3953
3954CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003955 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003956 if (!CXXUnit)
3957 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003958
3959 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003960 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3961}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003962
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003963void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3964 CXToken **Tokens, unsigned *NumTokens) {
3965 if (Tokens)
3966 *Tokens = 0;
3967 if (NumTokens)
3968 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003969
Ted Kremeneka60ed472010-11-16 08:15:36 +00003970 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003971 if (!CXXUnit || !Tokens || !NumTokens)
3972 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003973
Douglas Gregorbdf60622010-03-05 21:16:25 +00003974 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3975
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003976 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003977 if (R.isInvalid())
3978 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003979
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003980 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3981 std::pair<FileID, unsigned> BeginLocInfo
3982 = SourceMgr.getDecomposedLoc(R.getBegin());
3983 std::pair<FileID, unsigned> EndLocInfo
3984 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003985
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003986 // Cannot tokenize across files.
3987 if (BeginLocInfo.first != EndLocInfo.first)
3988 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003989
3990 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003991 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003992 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003993 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003994 if (Invalid)
3995 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003996
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003997 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3998 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003999 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004000 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004001
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004002 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004003 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004004 llvm::SmallVector<CXToken, 32> CXTokens;
4005 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004006 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004007 do {
4008 // Lex the next token
4009 Lex.LexFromRawLexer(Tok);
4010 if (Tok.is(tok::eof))
4011 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004012
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004013 // Initialize the CXToken.
4014 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004015
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004016 // - Common fields
4017 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4018 CXTok.int_data[2] = Tok.getLength();
4019 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004020
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004021 // - Kind-specific fields
4022 if (Tok.isLiteral()) {
4023 CXTok.int_data[0] = CXToken_Literal;
4024 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004025 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004026 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004027 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004028 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004029
David Chisnall096428b2010-10-13 21:44:48 +00004030 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004031 CXTok.int_data[0] = CXToken_Keyword;
4032 }
4033 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004034 CXTok.int_data[0] = Tok.is(tok::identifier)
4035 ? CXToken_Identifier
4036 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004037 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004038 CXTok.ptr_data = II;
4039 } else if (Tok.is(tok::comment)) {
4040 CXTok.int_data[0] = CXToken_Comment;
4041 CXTok.ptr_data = 0;
4042 } else {
4043 CXTok.int_data[0] = CXToken_Punctuation;
4044 CXTok.ptr_data = 0;
4045 }
4046 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004047 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004048 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004049
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004050 if (CXTokens.empty())
4051 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004052
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004053 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4054 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4055 *NumTokens = CXTokens.size();
4056}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004057
Ted Kremenek6db61092010-05-05 00:55:15 +00004058void clang_disposeTokens(CXTranslationUnit TU,
4059 CXToken *Tokens, unsigned NumTokens) {
4060 free(Tokens);
4061}
4062
4063} // end: extern "C"
4064
4065//===----------------------------------------------------------------------===//
4066// Token annotation APIs.
4067//===----------------------------------------------------------------------===//
4068
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004069typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004070static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4071 CXCursor parent,
4072 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004073namespace {
4074class AnnotateTokensWorker {
4075 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004076 CXToken *Tokens;
4077 CXCursor *Cursors;
4078 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004079 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004080 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004081 CursorVisitor AnnotateVis;
4082 SourceManager &SrcMgr;
4083
4084 bool MoreTokens() const { return TokIdx < NumTokens; }
4085 unsigned NextToken() const { return TokIdx; }
4086 void AdvanceToken() { ++TokIdx; }
4087 SourceLocation GetTokenLoc(unsigned tokI) {
4088 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4089 }
4090
Ted Kremenek6db61092010-05-05 00:55:15 +00004091public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004092 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004093 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004094 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004095 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004096 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004097 AnnotateVis(tu,
4098 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004099 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004100 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004101
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004102 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004103 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004104 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004105 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004106 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004107 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004108};
4109}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004110
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004111void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4112 // Walk the AST within the region of interest, annotating tokens
4113 // along the way.
4114 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004115
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004116 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4117 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004118 if (Pos != Annotated.end() &&
4119 (clang_isInvalid(Cursors[I].kind) ||
4120 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004121 Cursors[I] = Pos->second;
4122 }
4123
4124 // Finish up annotating any tokens left.
4125 if (!MoreTokens())
4126 return;
4127
4128 const CXCursor &C = clang_getNullCursor();
4129 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4130 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4131 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004132 }
4133}
4134
Ted Kremenek6db61092010-05-05 00:55:15 +00004135enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004136AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004137 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004138 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004139 if (cursorRange.isInvalid())
4140 return CXChildVisit_Recurse;
4141
Douglas Gregor4419b672010-10-21 06:10:04 +00004142 if (clang_isPreprocessing(cursor.kind)) {
4143 // For macro instantiations, just note where the beginning of the macro
4144 // instantiation occurs.
4145 if (cursor.kind == CXCursor_MacroInstantiation) {
4146 Annotated[Loc.int_data] = cursor;
4147 return CXChildVisit_Recurse;
4148 }
4149
Douglas Gregor4419b672010-10-21 06:10:04 +00004150 // Items in the preprocessing record are kept separate from items in
4151 // declarations, so we keep a separate token index.
4152 unsigned SavedTokIdx = TokIdx;
4153 TokIdx = PreprocessingTokIdx;
4154
4155 // Skip tokens up until we catch up to the beginning of the preprocessing
4156 // entry.
4157 while (MoreTokens()) {
4158 const unsigned I = NextToken();
4159 SourceLocation TokLoc = GetTokenLoc(I);
4160 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4161 case RangeBefore:
4162 AdvanceToken();
4163 continue;
4164 case RangeAfter:
4165 case RangeOverlap:
4166 break;
4167 }
4168 break;
4169 }
4170
4171 // Look at all of the tokens within this range.
4172 while (MoreTokens()) {
4173 const unsigned I = NextToken();
4174 SourceLocation TokLoc = GetTokenLoc(I);
4175 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4176 case RangeBefore:
4177 assert(0 && "Infeasible");
4178 case RangeAfter:
4179 break;
4180 case RangeOverlap:
4181 Cursors[I] = cursor;
4182 AdvanceToken();
4183 continue;
4184 }
4185 break;
4186 }
4187
4188 // Save the preprocessing token index; restore the non-preprocessing
4189 // token index.
4190 PreprocessingTokIdx = TokIdx;
4191 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004192 return CXChildVisit_Recurse;
4193 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004194
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004195 if (cursorRange.isInvalid())
4196 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004197
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004198 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4199
Ted Kremeneka333c662010-05-12 05:29:33 +00004200 // Adjust the annotated range based specific declarations.
4201 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4202 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004203 Decl *D = cxcursor::getCursorDecl(cursor);
4204 // Don't visit synthesized ObjC methods, since they have no syntatic
4205 // representation in the source.
4206 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4207 if (MD->isSynthesized())
4208 return CXChildVisit_Continue;
4209 }
4210 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004211 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4212 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004213 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004214 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004215 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004216 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004217 }
4218 }
4219 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004220
Ted Kremenek3f404602010-08-14 01:14:06 +00004221 // If the location of the cursor occurs within a macro instantiation, record
4222 // the spelling location of the cursor in our annotation map. We can then
4223 // paper over the token labelings during a post-processing step to try and
4224 // get cursor mappings for tokens that are the *arguments* of a macro
4225 // instantiation.
4226 if (L.isMacroID()) {
4227 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4228 // Only invalidate the old annotation if it isn't part of a preprocessing
4229 // directive. Here we assume that the default construction of CXCursor
4230 // results in CXCursor.kind being an initialized value (i.e., 0). If
4231 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004232
Ted Kremenek3f404602010-08-14 01:14:06 +00004233 CXCursor &oldC = Annotated[rawEncoding];
4234 if (!clang_isPreprocessing(oldC.kind))
4235 oldC = cursor;
4236 }
4237
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238 const enum CXCursorKind K = clang_getCursorKind(parent);
4239 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004240 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4241 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004242
4243 while (MoreTokens()) {
4244 const unsigned I = NextToken();
4245 SourceLocation TokLoc = GetTokenLoc(I);
4246 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4247 case RangeBefore:
4248 Cursors[I] = updateC;
4249 AdvanceToken();
4250 continue;
4251 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252 case RangeOverlap:
4253 break;
4254 }
4255 break;
4256 }
4257
4258 // Visit children to get their cursor information.
4259 const unsigned BeforeChildren = NextToken();
4260 VisitChildren(cursor);
4261 const unsigned AfterChildren = NextToken();
4262
4263 // Adjust 'Last' to the last token within the extent of the cursor.
4264 while (MoreTokens()) {
4265 const unsigned I = NextToken();
4266 SourceLocation TokLoc = GetTokenLoc(I);
4267 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4268 case RangeBefore:
4269 assert(0 && "Infeasible");
4270 case RangeAfter:
4271 break;
4272 case RangeOverlap:
4273 Cursors[I] = updateC;
4274 AdvanceToken();
4275 continue;
4276 }
4277 break;
4278 }
4279 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004280
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004281 // Scan the tokens that are at the beginning of the cursor, but are not
4282 // capture by the child cursors.
4283
4284 // For AST elements within macros, rely on a post-annotate pass to
4285 // to correctly annotate the tokens with cursors. Otherwise we can
4286 // get confusing results of having tokens that map to cursors that really
4287 // are expanded by an instantiation.
4288 if (L.isMacroID())
4289 cursor = clang_getNullCursor();
4290
4291 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4292 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4293 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004294
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004295 Cursors[I] = cursor;
4296 }
4297 // Scan the tokens that are at the end of the cursor, but are not captured
4298 // but the child cursors.
4299 for (unsigned I = AfterChildren; I != Last; ++I)
4300 Cursors[I] = cursor;
4301
4302 TokIdx = Last;
4303 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004304}
4305
Ted Kremenek6db61092010-05-05 00:55:15 +00004306static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4307 CXCursor parent,
4308 CXClientData client_data) {
4309 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4310}
4311
Ted Kremenekab979612010-11-11 08:05:23 +00004312// This gets run a separate thread to avoid stack blowout.
4313static void runAnnotateTokensWorker(void *UserData) {
4314 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4315}
4316
Ted Kremenek6db61092010-05-05 00:55:15 +00004317extern "C" {
4318
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004319void clang_annotateTokens(CXTranslationUnit TU,
4320 CXToken *Tokens, unsigned NumTokens,
4321 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004322
4323 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004324 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004325
Douglas Gregor4419b672010-10-21 06:10:04 +00004326 // Any token we don't specifically annotate will have a NULL cursor.
4327 CXCursor C = clang_getNullCursor();
4328 for (unsigned I = 0; I != NumTokens; ++I)
4329 Cursors[I] = C;
4330
Ted Kremeneka60ed472010-11-16 08:15:36 +00004331 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004332 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004333 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004334
Douglas Gregorbdf60622010-03-05 21:16:25 +00004335 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004336
Douglas Gregor0396f462010-03-19 05:22:59 +00004337 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004338 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004339 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4340 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004341 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4342 clang_getTokenLocation(TU,
4343 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004344
Douglas Gregor0396f462010-03-19 05:22:59 +00004345 // A mapping from the source locations found when re-lexing or traversing the
4346 // region of interest to the corresponding cursors.
4347 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004348
4349 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004350 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004351 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4352 std::pair<FileID, unsigned> BeginLocInfo
4353 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4354 std::pair<FileID, unsigned> EndLocInfo
4355 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004356
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004357 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004358 bool Invalid = false;
4359 if (BeginLocInfo.first == EndLocInfo.first &&
4360 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4361 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004362 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4363 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004364 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004365 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004366 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004367
4368 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004369 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004370 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004371 Token Tok;
4372 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004373
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004374 reprocess:
4375 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4376 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004377 // don't see it while preprocessing these tokens later, but keep track
4378 // of all of the token locations inside this preprocessing directive so
4379 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004380 //
4381 // FIXME: Some simple tests here could identify macro definitions and
4382 // #undefs, to provide specific cursor kinds for those.
4383 std::vector<SourceLocation> Locations;
4384 do {
4385 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004386 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004387 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004388
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004389 using namespace cxcursor;
4390 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004391 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4392 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004393 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004394 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4395 Annotated[Locations[I].getRawEncoding()] = Cursor;
4396 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004397
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004398 if (Tok.isAtStartOfLine())
4399 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004400
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004401 continue;
4402 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004403
Douglas Gregor48072312010-03-18 15:23:44 +00004404 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004405 break;
4406 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004407 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004408
Douglas Gregor0396f462010-03-19 05:22:59 +00004409 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004410 // a specific cursor.
4411 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004412 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004413
4414 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004415 // FIXME: We use a ridiculous stack size here because the data-recursion
4416 // algorithm uses a large stack frame than the non-data recursive version,
4417 // and AnnotationTokensWorker currently transforms the data-recursion
4418 // algorithm back into a traditional recursion by explicitly calling
4419 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004420 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004421 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4422 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004423 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4424 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004425}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004426} // end: extern "C"
4427
4428//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004429// Operations for querying linkage of a cursor.
4430//===----------------------------------------------------------------------===//
4431
4432extern "C" {
4433CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004434 if (!clang_isDeclaration(cursor.kind))
4435 return CXLinkage_Invalid;
4436
Ted Kremenek16b42592010-03-03 06:36:57 +00004437 Decl *D = cxcursor::getCursorDecl(cursor);
4438 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4439 switch (ND->getLinkage()) {
4440 case NoLinkage: return CXLinkage_NoLinkage;
4441 case InternalLinkage: return CXLinkage_Internal;
4442 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4443 case ExternalLinkage: return CXLinkage_External;
4444 };
4445
4446 return CXLinkage_Invalid;
4447}
4448} // end: extern "C"
4449
4450//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004451// Operations for querying language of a cursor.
4452//===----------------------------------------------------------------------===//
4453
4454static CXLanguageKind getDeclLanguage(const Decl *D) {
4455 switch (D->getKind()) {
4456 default:
4457 break;
4458 case Decl::ImplicitParam:
4459 case Decl::ObjCAtDefsField:
4460 case Decl::ObjCCategory:
4461 case Decl::ObjCCategoryImpl:
4462 case Decl::ObjCClass:
4463 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004464 case Decl::ObjCForwardProtocol:
4465 case Decl::ObjCImplementation:
4466 case Decl::ObjCInterface:
4467 case Decl::ObjCIvar:
4468 case Decl::ObjCMethod:
4469 case Decl::ObjCProperty:
4470 case Decl::ObjCPropertyImpl:
4471 case Decl::ObjCProtocol:
4472 return CXLanguage_ObjC;
4473 case Decl::CXXConstructor:
4474 case Decl::CXXConversion:
4475 case Decl::CXXDestructor:
4476 case Decl::CXXMethod:
4477 case Decl::CXXRecord:
4478 case Decl::ClassTemplate:
4479 case Decl::ClassTemplatePartialSpecialization:
4480 case Decl::ClassTemplateSpecialization:
4481 case Decl::Friend:
4482 case Decl::FriendTemplate:
4483 case Decl::FunctionTemplate:
4484 case Decl::LinkageSpec:
4485 case Decl::Namespace:
4486 case Decl::NamespaceAlias:
4487 case Decl::NonTypeTemplateParm:
4488 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004489 case Decl::TemplateTemplateParm:
4490 case Decl::TemplateTypeParm:
4491 case Decl::UnresolvedUsingTypename:
4492 case Decl::UnresolvedUsingValue:
4493 case Decl::Using:
4494 case Decl::UsingDirective:
4495 case Decl::UsingShadow:
4496 return CXLanguage_CPlusPlus;
4497 }
4498
4499 return CXLanguage_C;
4500}
4501
4502extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004503
4504enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4505 if (clang_isDeclaration(cursor.kind))
4506 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4507 if (D->hasAttr<UnavailableAttr>() ||
4508 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4509 return CXAvailability_Available;
4510
4511 if (D->hasAttr<DeprecatedAttr>())
4512 return CXAvailability_Deprecated;
4513 }
4514
4515 return CXAvailability_Available;
4516}
4517
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004518CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4519 if (clang_isDeclaration(cursor.kind))
4520 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4521
4522 return CXLanguage_Invalid;
4523}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004524
4525 /// \brief If the given cursor is the "templated" declaration
4526 /// descibing a class or function template, return the class or
4527 /// function template.
4528static Decl *maybeGetTemplateCursor(Decl *D) {
4529 if (!D)
4530 return 0;
4531
4532 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4533 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4534 return FunTmpl;
4535
4536 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4537 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4538 return ClassTmpl;
4539
4540 return D;
4541}
4542
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004543CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4544 if (clang_isDeclaration(cursor.kind)) {
4545 if (Decl *D = getCursorDecl(cursor)) {
4546 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004547 if (!DC)
4548 return clang_getNullCursor();
4549
4550 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4551 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004552 }
4553 }
4554
4555 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4556 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004557 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004558 }
4559
4560 return clang_getNullCursor();
4561}
4562
4563CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4564 if (clang_isDeclaration(cursor.kind)) {
4565 if (Decl *D = getCursorDecl(cursor)) {
4566 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004567 if (!DC)
4568 return clang_getNullCursor();
4569
4570 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4571 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004572 }
4573 }
4574
4575 // FIXME: Note that we can't easily compute the lexical context of a
4576 // statement or expression, so we return nothing.
4577 return clang_getNullCursor();
4578}
4579
Douglas Gregor9f592342010-10-01 20:25:15 +00004580static void CollectOverriddenMethods(DeclContext *Ctx,
4581 ObjCMethodDecl *Method,
4582 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4583 if (!Ctx)
4584 return;
4585
4586 // If we have a class or category implementation, jump straight to the
4587 // interface.
4588 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4589 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4590
4591 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4592 if (!Container)
4593 return;
4594
4595 // Check whether we have a matching method at this level.
4596 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4597 Method->isInstanceMethod()))
4598 if (Method != Overridden) {
4599 // We found an override at this level; there is no need to look
4600 // into other protocols or categories.
4601 Methods.push_back(Overridden);
4602 return;
4603 }
4604
4605 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4606 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4607 PEnd = Protocol->protocol_end();
4608 P != PEnd; ++P)
4609 CollectOverriddenMethods(*P, Method, Methods);
4610 }
4611
4612 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4613 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4614 PEnd = Category->protocol_end();
4615 P != PEnd; ++P)
4616 CollectOverriddenMethods(*P, Method, Methods);
4617 }
4618
4619 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4620 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4621 PEnd = Interface->protocol_end();
4622 P != PEnd; ++P)
4623 CollectOverriddenMethods(*P, Method, Methods);
4624
4625 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4626 Category; Category = Category->getNextClassCategory())
4627 CollectOverriddenMethods(Category, Method, Methods);
4628
4629 // We only look into the superclass if we haven't found anything yet.
4630 if (Methods.empty())
4631 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4632 return CollectOverriddenMethods(Super, Method, Methods);
4633 }
4634}
4635
4636void clang_getOverriddenCursors(CXCursor cursor,
4637 CXCursor **overridden,
4638 unsigned *num_overridden) {
4639 if (overridden)
4640 *overridden = 0;
4641 if (num_overridden)
4642 *num_overridden = 0;
4643 if (!overridden || !num_overridden)
4644 return;
4645
4646 if (!clang_isDeclaration(cursor.kind))
4647 return;
4648
4649 Decl *D = getCursorDecl(cursor);
4650 if (!D)
4651 return;
4652
4653 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004654 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004655 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4656 *num_overridden = CXXMethod->size_overridden_methods();
4657 if (!*num_overridden)
4658 return;
4659
4660 *overridden = new CXCursor [*num_overridden];
4661 unsigned I = 0;
4662 for (CXXMethodDecl::method_iterator
4663 M = CXXMethod->begin_overridden_methods(),
4664 MEnd = CXXMethod->end_overridden_methods();
4665 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004666 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004667 return;
4668 }
4669
4670 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4671 if (!Method)
4672 return;
4673
4674 // Handle Objective-C methods.
4675 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4676 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4677
4678 if (Methods.empty())
4679 return;
4680
4681 *num_overridden = Methods.size();
4682 *overridden = new CXCursor [Methods.size()];
4683 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004684 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004685}
4686
4687void clang_disposeOverriddenCursors(CXCursor *overridden) {
4688 delete [] overridden;
4689}
4690
Douglas Gregorecdcb882010-10-20 22:00:55 +00004691CXFile clang_getIncludedFile(CXCursor cursor) {
4692 if (cursor.kind != CXCursor_InclusionDirective)
4693 return 0;
4694
4695 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4696 return (void *)ID->getFile();
4697}
4698
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004699} // end: extern "C"
4700
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004701
4702//===----------------------------------------------------------------------===//
4703// C++ AST instrospection.
4704//===----------------------------------------------------------------------===//
4705
4706extern "C" {
4707unsigned clang_CXXMethod_isStatic(CXCursor C) {
4708 if (!clang_isDeclaration(C.kind))
4709 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004710
4711 CXXMethodDecl *Method = 0;
4712 Decl *D = cxcursor::getCursorDecl(C);
4713 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4714 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4715 else
4716 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4717 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004718}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004719
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004720} // end: extern "C"
4721
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004722//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004723// Attribute introspection.
4724//===----------------------------------------------------------------------===//
4725
4726extern "C" {
4727CXType clang_getIBOutletCollectionType(CXCursor C) {
4728 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004729 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004730
4731 IBOutletCollectionAttr *A =
4732 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4733
Ted Kremeneka60ed472010-11-16 08:15:36 +00004734 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004735}
4736} // end: extern "C"
4737
4738//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004739// Misc. utility functions.
4740//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004741
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004742/// Default to using an 8 MB stack size on "safety" threads.
4743static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004744
4745namespace clang {
4746
4747bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004748 void (*Fn)(void*), void *UserData,
4749 unsigned Size) {
4750 if (!Size)
4751 Size = GetSafetyThreadStackSize();
4752 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004753 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4754 return CRC.RunSafely(Fn, UserData);
4755}
4756
4757unsigned GetSafetyThreadStackSize() {
4758 return SafetyStackThreadSize;
4759}
4760
4761void SetSafetyThreadStackSize(unsigned Value) {
4762 SafetyStackThreadSize = Value;
4763}
4764
4765}
4766
Ted Kremenek04bb7162010-01-22 22:44:15 +00004767extern "C" {
4768
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004769CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004770 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004771}
4772
4773} // end: extern "C"