blob: 062a36729121f344a6b283be8b3770c787c69ec5 [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 Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
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
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000126
127class VisitorJob {
128public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000129 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000130 TypeLocVisitKind, OverloadExprPartsKind,
131 DeclRefExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000132protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000133 void *dataA;
134 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135 CXCursor parent;
136 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000137 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
138 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000139public:
140 Kind getKind() const { return K; }
141 const CXCursor &getParent() const { return parent; }
142 static bool classof(VisitorJob *VJ) { return true; }
143};
144
145typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
146
Douglas Gregorb1373d02010-01-20 20:59:29 +0000147// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000148class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000149 public TypeLocVisitor<CursorVisitor, bool>,
150 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000151{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000153 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000154
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000155 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000157
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000158 /// \brief The declaration that serves at the parent of any statement or
159 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000160 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000161
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000162 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000167
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000168 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
169 // to the visitor. Declarations with a PCH level greater than this value will
170 // be suppressed.
171 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172
173 /// \brief When valid, a source range to which the cursor should restrict
174 /// its search.
175 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000177 // FIXME: Eventually remove. This part of a hack to support proper
178 // iteration over all Decls contained lexically within an ObjC container.
179 DeclContext::decl_iterator *DI_current;
180 DeclContext::decl_iterator DE_current;
181
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000183 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000184 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
186 /// \brief Determine whether this particular source range comes before, comes
187 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000189 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000190 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
191
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000192 class SetParentRAII {
193 CXCursor &Parent;
194 Decl *&StmtParent;
195 CXCursor OldParent;
196
197 public:
198 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
199 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
200 {
201 Parent = NewParent;
202 if (clang_isDeclaration(Parent.kind))
203 StmtParent = getCursorDecl(Parent);
204 }
205
206 ~SetParentRAII() {
207 Parent = OldParent;
208 if (clang_isDeclaration(Parent.kind))
209 StmtParent = getCursorDecl(Parent);
210 }
211 };
212
Steve Naroff89922f82009-08-31 00:59:03 +0000213public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
215 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000216 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000218 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
219 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 {
221 Parent.kind = CXCursor_NoDeclFound;
222 Parent.data[0] = 0;
223 Parent.data[1] = 0;
224 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000225 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000226 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000227
Ted Kremenekab979612010-11-11 08:05:23 +0000228 ASTUnit *getASTUnit() const { return TU; }
229
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000230 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000231
232 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
233 getPreprocessedEntities();
234
Douglas Gregorb1373d02010-01-20 20:59:29 +0000235 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000237 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000238 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000239 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000240 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000241 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000243 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
244 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000245 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000246 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000247 bool VisitClassTemplatePartialSpecializationDecl(
248 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000249 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000250 bool VisitEnumConstantDecl(EnumConstantDecl *D);
251 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
252 bool VisitFunctionDecl(FunctionDecl *ND);
253 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000254 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000255 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000256 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000257 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000258 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000259 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
260 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
261 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
262 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000263 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000264 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
265 bool VisitObjCImplDecl(ObjCImplDecl *D);
266 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
267 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000268 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
269 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
270 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000271 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000272 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000273 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000274 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000275 bool VisitUsingDecl(UsingDecl *D);
276 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
277 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000278
Douglas Gregor01829d32010-08-31 14:41:23 +0000279 // Name visitor
280 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000281 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000282
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000283 // Template visitors
284 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000285 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
287
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000288 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000289 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000290 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000291 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000292 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
293 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000294 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000295 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000296 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000297 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
298 bool VisitPointerTypeLoc(PointerTypeLoc TL);
299 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
300 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
301 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
302 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000303 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000304 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000305 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000306 // FIXME: Implement visitors here when the unimplemented TypeLocs get
307 // implemented
308 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
309 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000310
Douglas Gregora59e3902010-01-21 23:27:09 +0000311 // Statement visitors
312 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000313
Douglas Gregor336fd812010-01-23 00:40:08 +0000314 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000315 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000316 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000317 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000318 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
319 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000320 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000321 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000322 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000323 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000324 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000325 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000326 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000327 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000328 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000329
330#define DATA_RECURSIVE_VISIT(NAME)\
331bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
332 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenek73d15c42010-11-13 01:09:29 +0000333 DATA_RECURSIVE_VISIT(BlockExpr)
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000334 DATA_RECURSIVE_VISIT(CompoundLiteralExpr)
Ted Kremenek11b8e3e2010-11-13 05:55:53 +0000335 DATA_RECURSIVE_VISIT(CXXDefaultArgExpr)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000336 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek11b8e3e2010-11-13 05:55:53 +0000337 DATA_RECURSIVE_VISIT(CXXNewExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000338 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenek73d15c42010-11-13 01:09:29 +0000339 DATA_RECURSIVE_VISIT(CXXTemporaryObjectExpr)
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000340 DATA_RECURSIVE_VISIT(DeclRefExpr)
Ted Kremenek035dc412010-11-13 00:36:50 +0000341 DATA_RECURSIVE_VISIT(DeclStmt)
Ted Kremenek99394242010-11-12 22:24:57 +0000342 DATA_RECURSIVE_VISIT(ExplicitCastExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000343 DATA_RECURSIVE_VISIT(DoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000344 DATA_RECURSIVE_VISIT(IfStmt)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000345 DATA_RECURSIVE_VISIT(InitListExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000346 DATA_RECURSIVE_VISIT(ForStmt)
Ted Kremenek1876bf62010-11-13 00:58:15 +0000347 DATA_RECURSIVE_VISIT(GotoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000348 DATA_RECURSIVE_VISIT(MemberExpr)
Ted Kremenek73d15c42010-11-13 01:09:29 +0000349 DATA_RECURSIVE_VISIT(ObjCEncodeExpr)
Ted Kremenekc373e3c2010-11-12 22:24:55 +0000350 DATA_RECURSIVE_VISIT(ObjCMessageExpr)
Ted Kremenek60458782010-11-12 21:34:16 +0000351 DATA_RECURSIVE_VISIT(OverloadExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000352 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekbb677132010-11-12 18:27:04 +0000353 DATA_RECURSIVE_VISIT(WhileStmt)
Ted Kremenek60458782010-11-12 21:34:16 +0000354 DATA_RECURSIVE_VISIT(UnresolvedMemberExpr)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000355
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000356 // Data-recursive visitor functions.
357 bool IsInRegionOfInterest(CXCursor C);
358 bool RunVisitorWorkList(VisitorWorkList &WL);
359 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
360 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000361};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000362
Ted Kremenekab188932010-01-05 19:32:54 +0000363} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000364
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000365static SourceRange getRawCursorExtent(CXCursor C);
366
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
369}
370
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \brief Visit the given cursor and, if requested by the visitor,
372/// its children.
373///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374/// \param Cursor the cursor to visit.
375///
376/// \param CheckRegionOfInterest if true, then the caller already checked that
377/// this cursor is within the region of interest.
378///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379/// \returns true if the visitation should be aborted, false if it
380/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382 if (clang_isInvalid(Cursor.kind))
383 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000384
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 if (clang_isDeclaration(Cursor.kind)) {
386 Decl *D = getCursorDecl(Cursor);
387 assert(D && "Invalid declaration cursor");
388 if (D->getPCHLevel() > MaxPCHLevel)
389 return false;
390
391 if (D->isImplicit())
392 return false;
393 }
394
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000395 // If we have a range of interest, and this cursor doesn't intersect with it,
396 // we're done.
397 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000398 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000399 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000400 return false;
401 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403 switch (Visitor(Cursor, Parent, ClientData)) {
404 case CXChildVisit_Break:
405 return true;
406
407 case CXChildVisit_Continue:
408 return false;
409
410 case CXChildVisit_Recurse:
411 return VisitChildren(Cursor);
412 }
413
Douglas Gregorfd643772010-01-25 16:45:46 +0000414 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000415}
416
Douglas Gregor788f5a12010-03-20 00:41:21 +0000417std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
418CursorVisitor::getPreprocessedEntities() {
419 PreprocessingRecord &PPRec
420 = *TU->getPreprocessor().getPreprocessingRecord();
421
422 bool OnlyLocalDecls
423 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
424
425 // There is no region of interest; we have to walk everything.
426 if (RegionOfInterest.isInvalid())
427 return std::make_pair(PPRec.begin(OnlyLocalDecls),
428 PPRec.end(OnlyLocalDecls));
429
430 // Find the file in which the region of interest lands.
431 SourceManager &SM = TU->getSourceManager();
432 std::pair<FileID, unsigned> Begin
433 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
434 std::pair<FileID, unsigned> End
435 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
436
437 // The region of interest spans files; we have to walk everything.
438 if (Begin.first != End.first)
439 return std::make_pair(PPRec.begin(OnlyLocalDecls),
440 PPRec.end(OnlyLocalDecls));
441
442 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
443 = TU->getPreprocessedEntitiesByFile();
444 if (ByFileMap.empty()) {
445 // Build the mapping from files to sets of preprocessed entities.
446 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
447 EEnd = PPRec.end(OnlyLocalDecls);
448 E != EEnd; ++E) {
449 std::pair<FileID, unsigned> P
450 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
451 ByFileMap[P.first].push_back(*E);
452 }
453 }
454
455 return std::make_pair(ByFileMap[Begin.first].begin(),
456 ByFileMap[Begin.first].end());
457}
458
Douglas Gregorb1373d02010-01-20 20:59:29 +0000459/// \brief Visit the children of the given cursor.
460///
461/// \returns true if the visitation should be aborted, false if it
462/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000464 if (clang_isReference(Cursor.kind)) {
465 // By definition, references have no children.
466 return false;
467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
469 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000471 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473 if (clang_isDeclaration(Cursor.kind)) {
474 Decl *D = getCursorDecl(Cursor);
475 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000476 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478
Douglas Gregora59e3902010-01-21 23:27:09 +0000479 if (clang_isStatement(Cursor.kind))
480 return Visit(getCursorStmt(Cursor));
481 if (clang_isExpression(Cursor.kind))
482 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000483
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000485 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000486 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
487 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000488 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
489 TLEnd = CXXUnit->top_level_end();
490 TL != TLEnd; ++TL) {
491 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000492 return true;
493 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 } else if (VisitDeclContext(
495 CXXUnit->getASTContext().getTranslationUnitDecl()))
496 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000497
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000499 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 // FIXME: Once we have the ability to deserialize a preprocessing record,
501 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000502 PreprocessingRecord::iterator E, EEnd;
503 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
505 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
506 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000507
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 continue;
509 }
510
511 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
512 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
513 return true;
514
515 continue;
516 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000517
518 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
519 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
520 return true;
521
522 continue;
523 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000524 }
525 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000526 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000528
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000530 return false;
531}
532
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000534 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
535 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000536
Ted Kremenek664cffd2010-07-22 11:30:19 +0000537 if (Stmt *Body = B->getBody())
538 return Visit(MakeCXCursor(Body, StmtParent, TU));
539
540 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000541}
542
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
544 if (RegionOfInterest.isValid()) {
545 SourceRange Range = getRawCursorExtent(Cursor);
546 if (Range.isInvalid())
547 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000548
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000549 switch (CompareRegionOfInterest(Range)) {
550 case RangeBefore:
551 // This declaration comes before the region of interest; skip it.
552 return llvm::Optional<bool>();
553
554 case RangeAfter:
555 // This declaration comes after the region of interest; we're done.
556 return false;
557
558 case RangeOverlap:
559 // This declaration overlaps the region of interest; visit it.
560 break;
561 }
562 }
563 return true;
564}
565
566bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
567 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
568
569 // FIXME: Eventually remove. This part of a hack to support proper
570 // iteration over all Decls contained lexically within an ObjC container.
571 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
572 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
573
574 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000575 Decl *D = *I;
576 if (D->getLexicalDeclContext() != DC)
577 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000578 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000579 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
580 if (!V.hasValue())
581 continue;
582 if (!V.getValue())
583 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585 return true;
586 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000588}
589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
591 llvm_unreachable("Translation units are visited directly by Visit()");
592 return false;
593}
594
595bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
596 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
597 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599 return false;
600}
601
602bool CursorVisitor::VisitTagDecl(TagDecl *D) {
603 return VisitDeclContext(D);
604}
605
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000606bool CursorVisitor::VisitClassTemplateSpecializationDecl(
607 ClassTemplateSpecializationDecl *D) {
608 bool ShouldVisitBody = false;
609 switch (D->getSpecializationKind()) {
610 case TSK_Undeclared:
611 case TSK_ImplicitInstantiation:
612 // Nothing to visit
613 return false;
614
615 case TSK_ExplicitInstantiationDeclaration:
616 case TSK_ExplicitInstantiationDefinition:
617 break;
618
619 case TSK_ExplicitSpecialization:
620 ShouldVisitBody = true;
621 break;
622 }
623
624 // Visit the template arguments used in the specialization.
625 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
626 TypeLoc TL = SpecType->getTypeLoc();
627 if (TemplateSpecializationTypeLoc *TSTLoc
628 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
629 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
630 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
631 return true;
632 }
633 }
634
635 if (ShouldVisitBody && VisitCXXRecordDecl(D))
636 return true;
637
638 return false;
639}
640
Douglas Gregor74dbe642010-08-31 19:31:58 +0000641bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
642 ClassTemplatePartialSpecializationDecl *D) {
643 // FIXME: Visit the "outer" template parameter lists on the TagDecl
644 // before visiting these template parameters.
645 if (VisitTemplateParameters(D->getTemplateParameters()))
646 return true;
647
648 // Visit the partial specialization arguments.
649 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
650 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
651 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
652 return true;
653
654 return VisitCXXRecordDecl(D);
655}
656
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000657bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000658 // Visit the default argument.
659 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
660 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
661 if (Visit(DefArg->getTypeLoc()))
662 return true;
663
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000664 return false;
665}
666
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000667bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
668 if (Expr *Init = D->getInitExpr())
669 return Visit(MakeCXCursor(Init, StmtParent, TU));
670 return false;
671}
672
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000673bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
674 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
675 if (Visit(TSInfo->getTypeLoc()))
676 return true;
677
678 return false;
679}
680
Douglas Gregora67e03f2010-09-09 21:42:20 +0000681/// \brief Compare two base or member initializers based on their source order.
682static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
683 CXXBaseOrMemberInitializer const * const *X
684 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
685 CXXBaseOrMemberInitializer const * const *Y
686 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
687
688 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
689 return -1;
690 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
691 return 1;
692 else
693 return 0;
694}
695
Douglas Gregorb1373d02010-01-20 20:59:29 +0000696bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000697 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
698 // Visit the function declaration's syntactic components in the order
699 // written. This requires a bit of work.
700 TypeLoc TL = TSInfo->getTypeLoc();
701 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
702
703 // If we have a function declared directly (without the use of a typedef),
704 // visit just the return type. Otherwise, just visit the function's type
705 // now.
706 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
707 (!FTL && Visit(TL)))
708 return true;
709
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000710 // Visit the nested-name-specifier, if present.
711 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
712 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
713 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000714
715 // Visit the declaration name.
716 if (VisitDeclarationNameInfo(ND->getNameInfo()))
717 return true;
718
719 // FIXME: Visit explicitly-specified template arguments!
720
721 // Visit the function parameters, if we have a function type.
722 if (FTL && VisitFunctionTypeLoc(*FTL, true))
723 return true;
724
725 // FIXME: Attributes?
726 }
727
Douglas Gregora67e03f2010-09-09 21:42:20 +0000728 if (ND->isThisDeclarationADefinition()) {
729 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
730 // Find the initializers that were written in the source.
731 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
732 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
733 IEnd = Constructor->init_end();
734 I != IEnd; ++I) {
735 if (!(*I)->isWritten())
736 continue;
737
738 WrittenInits.push_back(*I);
739 }
740
741 // Sort the initializers in source order
742 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
743 &CompareCXXBaseOrMemberInitializers);
744
745 // Visit the initializers in source order
746 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
747 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
748 if (Init->isMemberInitializer()) {
749 if (Visit(MakeCursorMemberRef(Init->getMember(),
750 Init->getMemberLocation(), TU)))
751 return true;
752 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
753 if (Visit(BaseInfo->getTypeLoc()))
754 return true;
755 }
756
757 // Visit the initializer value.
758 if (Expr *Initializer = Init->getInit())
759 if (Visit(MakeCXCursor(Initializer, ND, TU)))
760 return true;
761 }
762 }
763
764 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
765 return true;
766 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000767
Douglas Gregorb1373d02010-01-20 20:59:29 +0000768 return false;
769}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000770
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000771bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
772 if (VisitDeclaratorDecl(D))
773 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000774
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000775 if (Expr *BitWidth = D->getBitWidth())
776 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000778 return false;
779}
780
781bool CursorVisitor::VisitVarDecl(VarDecl *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 *Init = D->getInit())
786 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788 return false;
789}
790
Douglas Gregor84b51d72010-09-01 20:16:53 +0000791bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
792 if (VisitDeclaratorDecl(D))
793 return true;
794
795 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
796 if (Expr *DefArg = D->getDefaultArgument())
797 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
798
799 return false;
800}
801
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000802bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
803 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
804 // before visiting these template parameters.
805 if (VisitTemplateParameters(D->getTemplateParameters()))
806 return true;
807
808 return VisitFunctionDecl(D->getTemplatedDecl());
809}
810
Douglas Gregor39d6f072010-08-31 19:02:00 +0000811bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
812 // FIXME: Visit the "outer" template parameter lists on the TagDecl
813 // before visiting these template parameters.
814 if (VisitTemplateParameters(D->getTemplateParameters()))
815 return true;
816
817 return VisitCXXRecordDecl(D->getTemplatedDecl());
818}
819
Douglas Gregor84b51d72010-09-01 20:16:53 +0000820bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
821 if (VisitTemplateParameters(D->getTemplateParameters()))
822 return true;
823
824 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
825 VisitTemplateArgumentLoc(D->getDefaultArgument()))
826 return true;
827
828 return false;
829}
830
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000831bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000832 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
833 if (Visit(TSInfo->getTypeLoc()))
834 return true;
835
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000836 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000837 PEnd = ND->param_end();
838 P != PEnd; ++P) {
839 if (Visit(MakeCXCursor(*P, TU)))
840 return true;
841 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 if (ND->isThisDeclarationADefinition() &&
844 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
845 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000846
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000847 return false;
848}
849
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000850namespace {
851 struct ContainerDeclsSort {
852 SourceManager &SM;
853 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
854 bool operator()(Decl *A, Decl *B) {
855 SourceLocation L_A = A->getLocStart();
856 SourceLocation L_B = B->getLocStart();
857 assert(L_A.isValid() && L_B.isValid());
858 return SM.isBeforeInTranslationUnit(L_A, L_B);
859 }
860 };
861}
862
Douglas Gregora59e3902010-01-21 23:27:09 +0000863bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000864 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
865 // an @implementation can lexically contain Decls that are not properly
866 // nested in the AST. When we identify such cases, we need to retrofit
867 // this nesting here.
868 if (!DI_current)
869 return VisitDeclContext(D);
870
871 // Scan the Decls that immediately come after the container
872 // in the current DeclContext. If any fall within the
873 // container's lexical region, stash them into a vector
874 // for later processing.
875 llvm::SmallVector<Decl *, 24> DeclsInContainer;
876 SourceLocation EndLoc = D->getSourceRange().getEnd();
877 SourceManager &SM = TU->getSourceManager();
878 if (EndLoc.isValid()) {
879 DeclContext::decl_iterator next = *DI_current;
880 while (++next != DE_current) {
881 Decl *D_next = *next;
882 if (!D_next)
883 break;
884 SourceLocation L = D_next->getLocStart();
885 if (!L.isValid())
886 break;
887 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
888 *DI_current = next;
889 DeclsInContainer.push_back(D_next);
890 continue;
891 }
892 break;
893 }
894 }
895
896 // The common case.
897 if (DeclsInContainer.empty())
898 return VisitDeclContext(D);
899
900 // Get all the Decls in the DeclContext, and sort them with the
901 // additional ones we've collected. Then visit them.
902 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
903 I!=E; ++I) {
904 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000905 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
906 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000907 continue;
908 DeclsInContainer.push_back(subDecl);
909 }
910
911 // Now sort the Decls so that they appear in lexical order.
912 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
913 ContainerDeclsSort(SM));
914
915 // Now visit the decls.
916 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
917 E = DeclsInContainer.end(); I != E; ++I) {
918 CXCursor Cursor = MakeCXCursor(*I, TU);
919 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
920 if (!V.hasValue())
921 continue;
922 if (!V.getValue())
923 return false;
924 if (Visit(Cursor, true))
925 return true;
926 }
927 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000928}
929
Douglas Gregorb1373d02010-01-20 20:59:29 +0000930bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000931 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
932 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000935 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
936 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
937 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000938 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000939 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000940
Douglas Gregora59e3902010-01-21 23:27:09 +0000941 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000942}
943
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000944bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
945 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
946 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
947 E = PID->protocol_end(); I != E; ++I, ++PL)
948 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000951 return VisitObjCContainerDecl(PID);
952}
953
Ted Kremenek23173d72010-05-18 21:09:07 +0000954bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000955 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000956 return true;
957
Ted Kremenek23173d72010-05-18 21:09:07 +0000958 // FIXME: This implements a workaround with @property declarations also being
959 // installed in the DeclContext for the @interface. Eventually this code
960 // should be removed.
961 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
962 if (!CDecl || !CDecl->IsClassExtension())
963 return false;
964
965 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
966 if (!ID)
967 return false;
968
969 IdentifierInfo *PropertyId = PD->getIdentifier();
970 ObjCPropertyDecl *prevDecl =
971 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
972
973 if (!prevDecl)
974 return false;
975
976 // Visit synthesized methods since they will be skipped when visiting
977 // the @interface.
978 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000979 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000980 if (Visit(MakeCXCursor(MD, TU)))
981 return true;
982
983 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000984 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000985 if (Visit(MakeCXCursor(MD, TU)))
986 return true;
987
988 return false;
989}
990
Douglas Gregorb1373d02010-01-20 20:59:29 +0000991bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000992 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000993 if (D->getSuperClass() &&
994 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000996 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000997 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000999 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1000 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1001 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001002 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001004
Douglas Gregora59e3902010-01-21 23:27:09 +00001005 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001006}
1007
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001008bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1009 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001010}
1011
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001012bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001013 // 'ID' could be null when dealing with invalid code.
1014 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1015 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1016 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001017
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018 return VisitObjCImplDecl(D);
1019}
1020
1021bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1022#if 0
1023 // Issue callbacks for super class.
1024 // FIXME: No source location information!
1025 if (D->getSuperClass() &&
1026 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028 TU)))
1029 return true;
1030#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001032 return VisitObjCImplDecl(D);
1033}
1034
1035bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1036 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1037 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1038 E = D->protocol_end();
1039 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001040 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001041 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042
1043 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001044}
1045
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1047 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1048 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1049 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001050
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001051 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001052}
1053
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001054bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1055 return VisitDeclContext(D);
1056}
1057
Douglas Gregor69319002010-08-31 23:48:11 +00001058bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001059 // Visit nested-name-specifier.
1060 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1061 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1062 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001063
1064 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1065 D->getTargetNameLoc(), TU));
1066}
1067
Douglas Gregor7e242562010-09-01 19:52:22 +00001068bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001069 // Visit nested-name-specifier.
1070 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1071 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1072 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001073
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001074 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1075 return true;
1076
Douglas Gregor7e242562010-09-01 19:52:22 +00001077 return VisitDeclarationNameInfo(D->getNameInfo());
1078}
1079
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001080bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001081 // Visit nested-name-specifier.
1082 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1083 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1084 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001085
1086 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1087 D->getIdentLocation(), TU));
1088}
1089
Douglas Gregor7e242562010-09-01 19:52:22 +00001090bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001091 // Visit nested-name-specifier.
1092 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1093 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1094 return true;
1095
Douglas Gregor7e242562010-09-01 19:52:22 +00001096 return VisitDeclarationNameInfo(D->getNameInfo());
1097}
1098
1099bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1100 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001101 // Visit nested-name-specifier.
1102 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1103 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1104 return true;
1105
Douglas Gregor7e242562010-09-01 19:52:22 +00001106 return false;
1107}
1108
Douglas Gregor01829d32010-08-31 14:41:23 +00001109bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1110 switch (Name.getName().getNameKind()) {
1111 case clang::DeclarationName::Identifier:
1112 case clang::DeclarationName::CXXLiteralOperatorName:
1113 case clang::DeclarationName::CXXOperatorName:
1114 case clang::DeclarationName::CXXUsingDirective:
1115 return false;
1116
1117 case clang::DeclarationName::CXXConstructorName:
1118 case clang::DeclarationName::CXXDestructorName:
1119 case clang::DeclarationName::CXXConversionFunctionName:
1120 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1121 return Visit(TSInfo->getTypeLoc());
1122 return false;
1123
1124 case clang::DeclarationName::ObjCZeroArgSelector:
1125 case clang::DeclarationName::ObjCOneArgSelector:
1126 case clang::DeclarationName::ObjCMultiArgSelector:
1127 // FIXME: Per-identifier location info?
1128 return false;
1129 }
1130
1131 return false;
1132}
1133
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001134bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1135 SourceRange Range) {
1136 // FIXME: This whole routine is a hack to work around the lack of proper
1137 // source information in nested-name-specifiers (PR5791). Since we do have
1138 // a beginning source location, we can visit the first component of the
1139 // nested-name-specifier, if it's a single-token component.
1140 if (!NNS)
1141 return false;
1142
1143 // Get the first component in the nested-name-specifier.
1144 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1145 NNS = Prefix;
1146
1147 switch (NNS->getKind()) {
1148 case NestedNameSpecifier::Namespace:
1149 // FIXME: The token at this source location might actually have been a
1150 // namespace alias, but we don't model that. Lame!
1151 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1152 TU));
1153
1154 case NestedNameSpecifier::TypeSpec: {
1155 // If the type has a form where we know that the beginning of the source
1156 // range matches up with a reference cursor. Visit the appropriate reference
1157 // cursor.
1158 Type *T = NNS->getAsType();
1159 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1160 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1161 if (const TagType *Tag = dyn_cast<TagType>(T))
1162 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1163 if (const TemplateSpecializationType *TST
1164 = dyn_cast<TemplateSpecializationType>(T))
1165 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1166 break;
1167 }
1168
1169 case NestedNameSpecifier::TypeSpecWithTemplate:
1170 case NestedNameSpecifier::Global:
1171 case NestedNameSpecifier::Identifier:
1172 break;
1173 }
1174
1175 return false;
1176}
1177
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001178bool CursorVisitor::VisitTemplateParameters(
1179 const TemplateParameterList *Params) {
1180 if (!Params)
1181 return false;
1182
1183 for (TemplateParameterList::const_iterator P = Params->begin(),
1184 PEnd = Params->end();
1185 P != PEnd; ++P) {
1186 if (Visit(MakeCXCursor(*P, TU)))
1187 return true;
1188 }
1189
1190 return false;
1191}
1192
Douglas Gregor0b36e612010-08-31 20:37:03 +00001193bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1194 switch (Name.getKind()) {
1195 case TemplateName::Template:
1196 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1197
1198 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001199 // Visit the overloaded template set.
1200 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1201 return true;
1202
Douglas Gregor0b36e612010-08-31 20:37:03 +00001203 return false;
1204
1205 case TemplateName::DependentTemplate:
1206 // FIXME: Visit nested-name-specifier.
1207 return false;
1208
1209 case TemplateName::QualifiedTemplate:
1210 // FIXME: Visit nested-name-specifier.
1211 return Visit(MakeCursorTemplateRef(
1212 Name.getAsQualifiedTemplateName()->getDecl(),
1213 Loc, TU));
1214 }
1215
1216 return false;
1217}
1218
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001219bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1220 switch (TAL.getArgument().getKind()) {
1221 case TemplateArgument::Null:
1222 case TemplateArgument::Integral:
1223 return false;
1224
1225 case TemplateArgument::Pack:
1226 // FIXME: Implement when variadic templates come along.
1227 return false;
1228
1229 case TemplateArgument::Type:
1230 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1231 return Visit(TSInfo->getTypeLoc());
1232 return false;
1233
1234 case TemplateArgument::Declaration:
1235 if (Expr *E = TAL.getSourceDeclExpression())
1236 return Visit(MakeCXCursor(E, StmtParent, TU));
1237 return false;
1238
1239 case TemplateArgument::Expression:
1240 if (Expr *E = TAL.getSourceExpression())
1241 return Visit(MakeCXCursor(E, StmtParent, TU));
1242 return false;
1243
1244 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001245 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1246 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001247 }
1248
1249 return false;
1250}
1251
Ted Kremeneka0536d82010-05-07 01:04:29 +00001252bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1253 return VisitDeclContext(D);
1254}
1255
Douglas Gregor01829d32010-08-31 14:41:23 +00001256bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1257 return Visit(TL.getUnqualifiedLoc());
1258}
1259
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001260bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1261 ASTContext &Context = TU->getASTContext();
1262
1263 // Some builtin types (such as Objective-C's "id", "sel", and
1264 // "Class") have associated declarations. Create cursors for those.
1265 QualType VisitType;
1266 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001267 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001268 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001269 case BuiltinType::Char_U:
1270 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001271 case BuiltinType::Char16:
1272 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001273 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001274 case BuiltinType::UInt:
1275 case BuiltinType::ULong:
1276 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277 case BuiltinType::UInt128:
1278 case BuiltinType::Char_S:
1279 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001280 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001281 case BuiltinType::Short:
1282 case BuiltinType::Int:
1283 case BuiltinType::Long:
1284 case BuiltinType::LongLong:
1285 case BuiltinType::Int128:
1286 case BuiltinType::Float:
1287 case BuiltinType::Double:
1288 case BuiltinType::LongDouble:
1289 case BuiltinType::NullPtr:
1290 case BuiltinType::Overload:
1291 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001292 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001293
1294 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001295 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001296
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001297 case BuiltinType::ObjCId:
1298 VisitType = Context.getObjCIdType();
1299 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001300
1301 case BuiltinType::ObjCClass:
1302 VisitType = Context.getObjCClassType();
1303 break;
1304
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001305 case BuiltinType::ObjCSel:
1306 VisitType = Context.getObjCSelType();
1307 break;
1308 }
1309
1310 if (!VisitType.isNull()) {
1311 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001312 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001313 TU));
1314 }
1315
1316 return false;
1317}
1318
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001319bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1320 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1321}
1322
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1324 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1325}
1326
1327bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1328 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1329}
1330
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001331bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001332 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001333 // no context information with which we can match up the depth/index in the
1334 // type to the appropriate
1335 return false;
1336}
1337
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1339 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1340 return true;
1341
John McCallc12c5bb2010-05-15 11:32:37 +00001342 return false;
1343}
1344
1345bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1346 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1347 return true;
1348
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001349 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1350 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1351 TU)))
1352 return true;
1353 }
1354
1355 return false;
1356}
1357
1358bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001359 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001360}
1361
1362bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1363 return Visit(TL.getPointeeLoc());
1364}
1365
1366bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1367 return Visit(TL.getPointeeLoc());
1368}
1369
1370bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1371 return Visit(TL.getPointeeLoc());
1372}
1373
1374bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001375 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376}
1377
1378bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001379 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380}
1381
Douglas Gregor01829d32010-08-31 14:41:23 +00001382bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1383 bool SkipResultType) {
1384 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385 return true;
1386
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001388 if (Decl *D = TL.getArg(I))
1389 if (Visit(MakeCXCursor(D, TU)))
1390 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001391
1392 return false;
1393}
1394
1395bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1396 if (Visit(TL.getElementLoc()))
1397 return true;
1398
1399 if (Expr *Size = TL.getSizeExpr())
1400 return Visit(MakeCXCursor(Size, StmtParent, TU));
1401
1402 return false;
1403}
1404
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001405bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1406 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001407 // Visit the template name.
1408 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1409 TL.getTemplateNameLoc()))
1410 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001411
1412 // Visit the template arguments.
1413 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1414 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1415 return true;
1416
1417 return false;
1418}
1419
Douglas Gregor2332c112010-01-21 20:48:56 +00001420bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1421 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1422}
1423
1424bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1425 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1426 return Visit(TSInfo->getTypeLoc());
1427
1428 return false;
1429}
1430
Douglas Gregora59e3902010-01-21 23:27:09 +00001431bool CursorVisitor::VisitStmt(Stmt *S) {
1432 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1433 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001434 if (Stmt *C = *Child)
1435 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1436 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438
Douglas Gregora59e3902010-01-21 23:27:09 +00001439 return false;
1440}
1441
Ted Kremenek3064ef92010-08-27 21:34:58 +00001442bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1443 if (D->isDefinition()) {
1444 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1445 E = D->bases_end(); I != E; ++I) {
1446 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1447 return true;
1448 }
1449 }
1450
1451 return VisitTagDecl(D);
1452}
1453
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001454bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001455 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001456 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1457 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001458
1459 // Visit the components of the offsetof expression.
1460 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1461 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1462 const OffsetOfNode &Node = E->getComponent(I);
1463 switch (Node.getKind()) {
1464 case OffsetOfNode::Array:
1465 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1466 StmtParent, TU)))
1467 return true;
1468 break;
1469
1470 case OffsetOfNode::Field:
1471 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1472 TU)))
1473 return true;
1474 break;
1475
1476 case OffsetOfNode::Identifier:
1477 case OffsetOfNode::Base:
1478 continue;
1479 }
1480 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001481
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001482 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001483}
1484
Douglas Gregor336fd812010-01-23 00:40:08 +00001485bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1486 if (E->isArgumentType()) {
1487 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1488 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001489
Douglas Gregor336fd812010-01-23 00:40:08 +00001490 return false;
1491 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001492
Douglas Gregor336fd812010-01-23 00:40:08 +00001493 return VisitExpr(E);
1494}
1495
Douglas Gregor36897b02010-09-10 00:22:18 +00001496bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1497 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1498}
1499
Douglas Gregor648220e2010-08-10 15:02:34 +00001500bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1501 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1502 Visit(E->getArgTInfo2()->getTypeLoc());
1503}
1504
1505bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1506 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1507 return true;
1508
1509 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1510}
1511
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001512bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1513 // Visit the designators.
1514 typedef DesignatedInitExpr::Designator Designator;
1515 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1516 DEnd = E->designators_end();
1517 D != DEnd; ++D) {
1518 if (D->isFieldDesignator()) {
1519 if (FieldDecl *Field = D->getField())
1520 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1521 return true;
1522
1523 continue;
1524 }
1525
1526 if (D->isArrayDesignator()) {
1527 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1528 return true;
1529
1530 continue;
1531 }
1532
1533 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1534 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1535 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1536 return true;
1537 }
1538
1539 // Visit the initializer value itself.
1540 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1541}
1542
Douglas Gregor94802292010-09-02 21:20:16 +00001543bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1544 if (E->isTypeOperand()) {
1545 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1546 return Visit(TSInfo->getTypeLoc());
1547
1548 return false;
1549 }
1550
1551 return VisitExpr(E);
1552}
1553
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001554bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1555 if (E->isTypeOperand()) {
1556 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1557 return Visit(TSInfo->getTypeLoc());
1558
1559 return false;
1560 }
1561
1562 return VisitExpr(E);
1563}
1564
Douglas Gregorab6677e2010-09-08 00:15:04 +00001565bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1566 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1567 return Visit(TSInfo->getTypeLoc());
1568
1569 return false;
1570}
1571
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001572bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1573 // Visit base expression.
1574 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1575 return true;
1576
1577 // Visit the nested-name-specifier.
1578 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1579 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1580 return true;
1581
1582 // Visit the scope type that looks disturbingly like the nested-name-specifier
1583 // but isn't.
1584 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1585 if (Visit(TSInfo->getTypeLoc()))
1586 return true;
1587
1588 // Visit the name of the type being destroyed.
1589 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1590 if (Visit(TSInfo->getTypeLoc()))
1591 return true;
1592
1593 return false;
1594}
1595
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001596bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1597 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1598}
1599
Douglas Gregorbfebed22010-09-03 17:24:10 +00001600bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1601 DependentScopeDeclRefExpr *E) {
1602 // Visit the nested-name-specifier.
1603 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1604 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1605 return true;
1606
1607 // Visit the declaration name.
1608 if (VisitDeclarationNameInfo(E->getNameInfo()))
1609 return true;
1610
1611 // Visit the explicitly-specified template arguments.
1612 if (const ExplicitTemplateArgumentList *ArgList
1613 = E->getOptionalExplicitTemplateArgs()) {
1614 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1615 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1616 Arg != ArgEnd; ++Arg) {
1617 if (VisitTemplateArgumentLoc(*Arg))
1618 return true;
1619 }
1620 }
1621
1622 return false;
1623}
1624
Douglas Gregorab6677e2010-09-08 00:15:04 +00001625bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1626 CXXUnresolvedConstructExpr *E) {
1627 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1628 if (Visit(TSInfo->getTypeLoc()))
1629 return true;
1630
1631 return VisitExpr(E);
1632}
1633
Douglas Gregor25d63622010-09-03 17:35:34 +00001634bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1635 CXXDependentScopeMemberExpr *E) {
1636 // Visit the base expression, if there is one.
1637 if (!E->isImplicitAccess() &&
1638 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1639 return true;
1640
1641 // Visit the nested-name-specifier.
1642 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1643 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1644 return true;
1645
1646 // Visit the declaration name.
1647 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1648 return true;
1649
1650 // Visit the explicitly-specified template arguments.
1651 if (const ExplicitTemplateArgumentList *ArgList
1652 = E->getOptionalExplicitTemplateArgs()) {
1653 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1654 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1655 Arg != ArgEnd; ++Arg) {
1656 if (VisitTemplateArgumentLoc(*Arg))
1657 return true;
1658 }
1659 }
1660
1661 return false;
1662}
1663
Ted Kremenek09dfa372010-02-18 05:46:33 +00001664bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001665 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1666 i != e; ++i)
1667 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001668 return true;
1669
1670 return false;
1671}
1672
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001673//===----------------------------------------------------------------------===//
1674// Data-recursive visitor methods.
1675//===----------------------------------------------------------------------===//
1676
Ted Kremenek28a71942010-11-13 00:36:47 +00001677namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001678#define DEF_JOB(NAME, DATA, KIND)\
1679class NAME : public VisitorJob {\
1680public:\
1681 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1682 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1683 DATA *get() const { return static_cast<DATA*>(dataA); }\
1684};
1685
1686DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1687DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001688DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001689DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1690#undef DEF_JOB
1691
1692class DeclVisit : public VisitorJob {
1693public:
1694 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1695 VisitorJob(parent, VisitorJob::DeclVisitKind,
1696 d, isFirst ? (void*) 1 : (void*) 0) {}
1697 static bool classof(const VisitorJob *VJ) {
1698 return VJ->getKind () == DeclVisitKind;
1699 }
1700 Decl *get() { return static_cast<Decl*>(dataA);}
1701 bool isFirst() const { return dataB ? true : false; }
1702};
1703
1704class TypeLocVisit : public VisitorJob {
1705public:
1706 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1707 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1708 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1709
1710 static bool classof(const VisitorJob *VJ) {
1711 return VJ->getKind() == TypeLocVisitKind;
1712 }
1713
1714 TypeLoc get() {
1715 QualType T = QualType::getFromOpaquePtr(dataA);
1716 return TypeLoc(T, dataB);
1717 }
1718};
1719
Ted Kremenek28a71942010-11-13 00:36:47 +00001720class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1721 VisitorWorkList &WL;
1722 CXCursor Parent;
1723public:
1724 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1725 : WL(wl), Parent(parent) {}
1726
Ted Kremenek73d15c42010-11-13 01:09:29 +00001727 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001728 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001729 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001730 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1731 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001732 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001733 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001734 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001735 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001736 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1737 void VisitForStmt(ForStmt *FS);
1738 void VisitIfStmt(IfStmt *If);
1739 void VisitInitListExpr(InitListExpr *IE);
1740 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001741 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001742 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1743 void VisitOverloadExpr(OverloadExpr *E);
1744 void VisitStmt(Stmt *S);
1745 void VisitSwitchStmt(SwitchStmt *S);
1746 void VisitWhileStmt(WhileStmt *W);
1747 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1748
1749private:
1750 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001751 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001752 void AddTypeLoc(TypeSourceInfo *TI);
1753 void EnqueueChildren(Stmt *S);
1754};
1755} // end anonyous namespace
1756
1757void EnqueueVisitor::AddStmt(Stmt *S) {
1758 if (S)
1759 WL.push_back(StmtVisit(S, Parent));
1760}
Ted Kremenek035dc412010-11-13 00:36:50 +00001761void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001762 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001763 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001764}
1765void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1766 if (TI)
1767 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1768 }
1769void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001770 unsigned size = WL.size();
1771 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1772 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001773 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001774 }
1775 if (size == WL.size())
1776 return;
1777 // Now reverse the entries we just added. This will match the DFS
1778 // ordering performed by the worklist.
1779 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1780 std::reverse(I, E);
1781}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001782void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1783 AddDecl(B->getBlockDecl());
1784}
Ted Kremenek28a71942010-11-13 00:36:47 +00001785void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1786 EnqueueChildren(E);
1787 AddTypeLoc(E->getTypeSourceInfo());
1788}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001789void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1790 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1791 E = S->body_rend(); I != E; ++I) {
1792 AddStmt(*I);
1793 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001794}
1795void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1796 // Enqueue the initializer or constructor arguments.
1797 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1798 AddStmt(E->getConstructorArg(I-1));
1799 // Enqueue the array size, if any.
1800 AddStmt(E->getArraySize());
1801 // Enqueue the allocated type.
1802 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1803 // Enqueue the placement arguments.
1804 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1805 AddStmt(E->getPlacementArg(I-1));
1806}
Ted Kremenek28a71942010-11-13 00:36:47 +00001807void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1808 // Note that we enqueue things in reverse order so that
1809 // they are visited correctly by the DFS.
1810 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
1811 AddStmt(CE->getArg(N-I));
1812 AddStmt(CE->getCallee());
1813 AddStmt(CE->getArg(0));
1814}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001815void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1816 EnqueueChildren(E);
1817 AddTypeLoc(E->getTypeSourceInfo());
1818}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001819void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1820 WL.push_back(DeclRefExprParts(DR, Parent));
1821}
Ted Kremenek035dc412010-11-13 00:36:50 +00001822void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1823 unsigned size = WL.size();
1824 bool isFirst = true;
1825 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1826 D != DEnd; ++D) {
1827 AddDecl(*D, isFirst);
1828 isFirst = false;
1829 }
1830 if (size == WL.size())
1831 return;
1832 // Now reverse the entries we just added. This will match the DFS
1833 // ordering performed by the worklist.
1834 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1835 std::reverse(I, E);
1836}
Ted Kremenek28a71942010-11-13 00:36:47 +00001837void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1838 EnqueueChildren(E);
1839 AddTypeLoc(E->getTypeInfoAsWritten());
1840}
1841void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1842 AddStmt(FS->getBody());
1843 AddStmt(FS->getInc());
1844 AddStmt(FS->getCond());
1845 AddDecl(FS->getConditionVariable());
1846 AddStmt(FS->getInit());
1847}
1848void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1849 AddStmt(If->getElse());
1850 AddStmt(If->getThen());
1851 AddStmt(If->getCond());
1852 AddDecl(If->getConditionVariable());
1853}
1854void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1855 // We care about the syntactic form of the initializer list, only.
1856 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1857 IE = Syntactic;
1858 EnqueueChildren(IE);
1859}
1860void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1861 WL.push_back(MemberExprParts(M, Parent));
1862 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}
1871void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001872 WL.push_back(OverloadExprParts(E, Parent));
1873}
Ted Kremenek28a71942010-11-13 00:36:47 +00001874void EnqueueVisitor::VisitStmt(Stmt *S) {
1875 EnqueueChildren(S);
1876}
1877void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1878 AddStmt(S->getBody());
1879 AddStmt(S->getCond());
1880 AddDecl(S->getConditionVariable());
1881}
1882void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1883 AddStmt(W->getBody());
1884 AddStmt(W->getCond());
1885 AddDecl(W->getConditionVariable());
1886}
1887void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1888 VisitOverloadExpr(U);
1889 if (!U->isImplicitAccess())
1890 AddStmt(U->getBase());
1891}
Ted Kremenek60458782010-11-12 21:34:16 +00001892
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001893void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001894 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001895}
1896
1897bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1898 if (RegionOfInterest.isValid()) {
1899 SourceRange Range = getRawCursorExtent(C);
1900 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1901 return false;
1902 }
1903 return true;
1904}
1905
1906bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1907 while (!WL.empty()) {
1908 // Dequeue the worklist item.
1909 VisitorJob LI = WL.back(); WL.pop_back();
1910
1911 // Set the Parent field, then back to its old value once we're done.
1912 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1913
1914 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001915 case VisitorJob::DeclVisitKind: {
1916 Decl *D = cast<DeclVisit>(LI).get();
1917 if (!D)
1918 continue;
1919
1920 // For now, perform default visitation for Decls.
Ted Kremenek035dc412010-11-13 00:36:50 +00001921 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(LI).isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001922 return true;
1923
1924 continue;
1925 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001926 case VisitorJob::TypeLocVisitKind: {
1927 // Perform default visitation for TypeLocs.
1928 if (Visit(cast<TypeLocVisit>(LI).get()))
1929 return true;
1930 continue;
1931 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001932 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001933 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001934 if (!S)
1935 continue;
1936
Ted Kremenekf1107452010-11-12 18:26:56 +00001937 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001938 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1939
1940 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001941 case Stmt::GotoStmtClass: {
1942 GotoStmt *GS = cast<GotoStmt>(S);
1943 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1944 GS->getLabelLoc(), TU))) {
1945 return true;
1946 }
1947 continue;
1948 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001949 default: {
Ted Kremenek99394242010-11-12 22:24:57 +00001950 // FIXME: this entire switch stmt will eventually
1951 // go away.
1952 if (!isa<ExplicitCastExpr>(S)) {
1953 // Perform default visitation for other cases.
1954 if (Visit(Cursor))
1955 return true;
1956 continue;
1957 }
1958 // Fall-through.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001959 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001960 case Stmt::BinaryOperatorClass:
Ted Kremenek73d15c42010-11-13 01:09:29 +00001961 case Stmt::BlockExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001962 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001963 case Stmt::CaseStmtClass:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001964 case Stmt::CompoundLiteralExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001965 case Stmt::CompoundStmtClass:
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001966 case Stmt::CXXDefaultArgExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001967 case Stmt::CXXMemberCallExprClass:
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001968 case Stmt::CXXNewExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001969 case Stmt::CXXOperatorCallExprClass:
Ted Kremenek73d15c42010-11-13 01:09:29 +00001970 case Stmt::CXXTemporaryObjectExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001971 case Stmt::DefaultStmtClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001972 case Stmt::DoStmtClass:
1973 case Stmt::ForStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001974 case Stmt::IfStmtClass:
Ted Kremeneka6b70432010-11-12 21:34:09 +00001975 case Stmt::InitListExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001976 case Stmt::MemberExprClass:
Ted Kremenek73d15c42010-11-13 01:09:29 +00001977 case Stmt::ObjCEncodeExprClass:
Ted Kremenekc373e3c2010-11-12 22:24:55 +00001978 case Stmt::ObjCMessageExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001979 case Stmt::ParenExprClass:
1980 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00001981 case Stmt::UnaryOperatorClass:
Ted Kremenek60458782010-11-12 21:34:16 +00001982 case Stmt::UnresolvedLookupExprClass:
1983 case Stmt::UnresolvedMemberExprClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001984 case Stmt::WhileStmtClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001985 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001986 if (!IsInRegionOfInterest(Cursor))
1987 continue;
1988 switch (Visitor(Cursor, Parent, ClientData)) {
1989 case CXChildVisit_Break:
1990 return true;
1991 case CXChildVisit_Continue:
1992 break;
1993 case CXChildVisit_Recurse:
1994 EnqueueWorkList(WL, S);
1995 break;
1996 }
1997 }
1998 }
1999 continue;
2000 }
2001 case VisitorJob::MemberExprPartsKind: {
2002 // Handle the other pieces in the MemberExpr besides the base.
2003 MemberExpr *M = cast<MemberExprParts>(LI).get();
2004
2005 // Visit the nested-name-specifier
2006 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2007 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2008 return true;
2009
2010 // Visit the declaration name.
2011 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2012 return true;
2013
2014 // Visit the explicitly-specified template arguments, if any.
2015 if (M->hasExplicitTemplateArgs()) {
2016 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2017 *ArgEnd = Arg + M->getNumTemplateArgs();
2018 Arg != ArgEnd; ++Arg) {
2019 if (VisitTemplateArgumentLoc(*Arg))
2020 return true;
2021 }
2022 }
2023 continue;
2024 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002025 case VisitorJob::DeclRefExprPartsKind: {
2026 DeclRefExpr *DR = cast<DeclRefExprParts>(LI).get();
2027 // Visit nested-name-specifier, if present.
2028 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2029 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2030 return true;
2031 // Visit declaration name.
2032 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2033 return true;
2034 // Visit explicitly-specified template arguments.
2035 if (DR->hasExplicitTemplateArgs()) {
2036 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2037 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2038 *ArgEnd = Arg + Args.NumTemplateArgs;
2039 Arg != ArgEnd; ++Arg)
2040 if (VisitTemplateArgumentLoc(*Arg))
2041 return true;
2042 }
2043 continue;
2044 }
Ted Kremenek60458782010-11-12 21:34:16 +00002045 case VisitorJob::OverloadExprPartsKind: {
2046 OverloadExpr *O = cast<OverloadExprParts>(LI).get();
2047 // Visit the nested-name-specifier.
2048 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2049 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2050 return true;
2051 // Visit the declaration name.
2052 if (VisitDeclarationNameInfo(O->getNameInfo()))
2053 return true;
2054 // Visit the overloaded declaration reference.
2055 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2056 return true;
2057 // Visit the explicitly-specified template arguments.
2058 if (const ExplicitTemplateArgumentList *ArgList
2059 = O->getOptionalExplicitTemplateArgs()) {
2060 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2061 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2062 Arg != ArgEnd; ++Arg) {
2063 if (VisitTemplateArgumentLoc(*Arg))
2064 return true;
2065 }
2066 }
2067 continue;
2068 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002069 }
2070 }
2071 return false;
2072}
2073
2074bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2075 VisitorWorkList WL;
2076 EnqueueWorkList(WL, S);
2077 return RunVisitorWorkList(WL);
2078}
2079
2080//===----------------------------------------------------------------------===//
2081// Misc. API hooks.
2082//===----------------------------------------------------------------------===//
2083
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002084static llvm::sys::Mutex EnableMultithreadingMutex;
2085static bool EnabledMultithreading;
2086
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002087extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002088CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2089 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002090 // Disable pretty stack trace functionality, which will otherwise be a very
2091 // poor citizen of the world and set up all sorts of signal handlers.
2092 llvm::DisablePrettyStackTrace = true;
2093
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002094 // We use crash recovery to make some of our APIs more reliable, implicitly
2095 // enable it.
2096 llvm::CrashRecoveryContext::Enable();
2097
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002098 // Enable support for multithreading in LLVM.
2099 {
2100 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2101 if (!EnabledMultithreading) {
2102 llvm::llvm_start_multithreaded();
2103 EnabledMultithreading = true;
2104 }
2105 }
2106
Douglas Gregora030b7c2010-01-22 20:35:53 +00002107 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002108 if (excludeDeclarationsFromPCH)
2109 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002110 if (displayDiagnostics)
2111 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002112 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002113}
2114
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002115void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002116 if (CIdx)
2117 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002118}
2119
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002120CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002121 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002122 if (!CIdx)
2123 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002124
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002125 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002126 FileSystemOptions FileSystemOpts;
2127 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002128
Douglas Gregor28019772010-04-05 23:52:57 +00002129 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002130 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002131 CXXIdx->getOnlyLocalDecls(),
2132 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002133}
2134
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002135unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002136 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002137 CXTranslationUnit_CacheCompletionResults |
2138 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002139}
2140
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002141CXTranslationUnit
2142clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2143 const char *source_filename,
2144 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002145 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002146 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002147 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002148 return clang_parseTranslationUnit(CIdx, source_filename,
2149 command_line_args, num_command_line_args,
2150 unsaved_files, num_unsaved_files,
2151 CXTranslationUnit_DetailedPreprocessingRecord);
2152}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002153
2154struct ParseTranslationUnitInfo {
2155 CXIndex CIdx;
2156 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002157 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002158 int num_command_line_args;
2159 struct CXUnsavedFile *unsaved_files;
2160 unsigned num_unsaved_files;
2161 unsigned options;
2162 CXTranslationUnit result;
2163};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002164static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002165 ParseTranslationUnitInfo *PTUI =
2166 static_cast<ParseTranslationUnitInfo*>(UserData);
2167 CXIndex CIdx = PTUI->CIdx;
2168 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002169 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002170 int num_command_line_args = PTUI->num_command_line_args;
2171 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2172 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2173 unsigned options = PTUI->options;
2174 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002175
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002176 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002177 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002178
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002179 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2180
Douglas Gregor44c181a2010-07-23 00:33:23 +00002181 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002182 bool CompleteTranslationUnit
2183 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002184 bool CacheCodeCompetionResults
2185 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002186 bool CXXPrecompilePreamble
2187 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2188 bool CXXChainedPCH
2189 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002190
Douglas Gregor5352ac02010-01-28 00:27:43 +00002191 // Configure the diagnostics.
2192 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002193 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2194 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
Douglas Gregor4db64a42010-01-23 00:14:00 +00002196 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2197 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002198 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002199 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002200 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002201 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2202 Buffer));
2203 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002204
Douglas Gregorb10daed2010-10-11 16:52:23 +00002205 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002206
Ted Kremenek139ba862009-10-22 00:03:57 +00002207 // The 'source_filename' argument is optional. If the caller does not
2208 // specify it then it is assumed that the source file is specified
2209 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002210 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002211 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002212
2213 // Since the Clang C library is primarily used by batch tools dealing with
2214 // (often very broken) source code, where spell-checking can have a
2215 // significant negative impact on performance (particularly when
2216 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002217 // Only do this if we haven't found a spell-checking-related argument.
2218 bool FoundSpellCheckingArgument = false;
2219 for (int I = 0; I != num_command_line_args; ++I) {
2220 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2221 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2222 FoundSpellCheckingArgument = true;
2223 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002224 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002225 }
2226 if (!FoundSpellCheckingArgument)
2227 Args.push_back("-fno-spell-checking");
2228
2229 Args.insert(Args.end(), command_line_args,
2230 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002231
Douglas Gregor44c181a2010-07-23 00:33:23 +00002232 // Do we need the detailed preprocessing record?
2233 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002234 Args.push_back("-Xclang");
2235 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002236 }
2237
Douglas Gregorb10daed2010-10-11 16:52:23 +00002238 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002239 llvm::OwningPtr<ASTUnit> Unit(
2240 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2241 Diags,
2242 CXXIdx->getClangResourcesPath(),
2243 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002244 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002245 RemappedFiles.data(),
2246 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002247 PrecompilePreamble,
2248 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002249 CacheCodeCompetionResults,
2250 CXXPrecompilePreamble,
2251 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002252
Douglas Gregorb10daed2010-10-11 16:52:23 +00002253 if (NumErrors != Diags->getNumErrors()) {
2254 // Make sure to check that 'Unit' is non-NULL.
2255 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2256 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2257 DEnd = Unit->stored_diag_end();
2258 D != DEnd; ++D) {
2259 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2260 CXString Msg = clang_formatDiagnostic(&Diag,
2261 clang_defaultDiagnosticDisplayOptions());
2262 fprintf(stderr, "%s\n", clang_getCString(Msg));
2263 clang_disposeString(Msg);
2264 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002265#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002266 // On Windows, force a flush, since there may be multiple copies of
2267 // stderr and stdout in the file system, all with different buffers
2268 // but writing to the same device.
2269 fflush(stderr);
2270#endif
2271 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002272 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002273
Douglas Gregorb10daed2010-10-11 16:52:23 +00002274 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002275}
2276CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2277 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002278 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002279 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002280 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002281 unsigned num_unsaved_files,
2282 unsigned options) {
2283 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002284 num_command_line_args, unsaved_files,
2285 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002286 llvm::CrashRecoveryContext CRC;
2287
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002288 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002289 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2290 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2291 fprintf(stderr, " 'command_line_args' : [");
2292 for (int i = 0; i != num_command_line_args; ++i) {
2293 if (i)
2294 fprintf(stderr, ", ");
2295 fprintf(stderr, "'%s'", command_line_args[i]);
2296 }
2297 fprintf(stderr, "],\n");
2298 fprintf(stderr, " 'unsaved_files' : [");
2299 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2300 if (i)
2301 fprintf(stderr, ", ");
2302 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2303 unsaved_files[i].Length);
2304 }
2305 fprintf(stderr, "],\n");
2306 fprintf(stderr, " 'options' : %d,\n", options);
2307 fprintf(stderr, "}\n");
2308
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002309 return 0;
2310 }
2311
2312 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002313}
2314
Douglas Gregor19998442010-08-13 15:35:05 +00002315unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2316 return CXSaveTranslationUnit_None;
2317}
2318
2319int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2320 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002321 if (!TU)
2322 return 1;
2323
2324 return static_cast<ASTUnit *>(TU)->Save(FileName);
2325}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002326
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002327void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002328 if (CTUnit) {
2329 // If the translation unit has been marked as unsafe to free, just discard
2330 // it.
2331 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2332 return;
2333
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002334 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002335 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002336}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002337
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002338unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2339 return CXReparse_None;
2340}
2341
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002342struct ReparseTranslationUnitInfo {
2343 CXTranslationUnit TU;
2344 unsigned num_unsaved_files;
2345 struct CXUnsavedFile *unsaved_files;
2346 unsigned options;
2347 int result;
2348};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002349
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002350static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002351 ReparseTranslationUnitInfo *RTUI =
2352 static_cast<ReparseTranslationUnitInfo*>(UserData);
2353 CXTranslationUnit TU = RTUI->TU;
2354 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2355 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2356 unsigned options = RTUI->options;
2357 (void) options;
2358 RTUI->result = 1;
2359
Douglas Gregorabc563f2010-07-19 21:46:24 +00002360 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002361 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002362
2363 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2364 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002365
2366 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2367 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2368 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2369 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002370 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002371 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2372 Buffer));
2373 }
2374
Douglas Gregor593b0c12010-09-23 18:47:53 +00002375 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2376 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002377}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002378
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002379int clang_reparseTranslationUnit(CXTranslationUnit TU,
2380 unsigned num_unsaved_files,
2381 struct CXUnsavedFile *unsaved_files,
2382 unsigned options) {
2383 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2384 options, 0 };
2385 llvm::CrashRecoveryContext CRC;
2386
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002387 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002388 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002389 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2390 return 1;
2391 }
2392
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002393
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002394 return RTUI.result;
2395}
2396
Douglas Gregordf95a132010-08-09 20:45:32 +00002397
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002398CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002399 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002400 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002401
Steve Naroff77accc12009-09-03 18:19:54 +00002402 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002403 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002404}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002405
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002406CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002407 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002408 return Result;
2409}
2410
Ted Kremenekfb480492010-01-13 21:46:36 +00002411} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002412
Ted Kremenekfb480492010-01-13 21:46:36 +00002413//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002414// CXSourceLocation and CXSourceRange Operations.
2415//===----------------------------------------------------------------------===//
2416
Douglas Gregorb9790342010-01-22 21:44:22 +00002417extern "C" {
2418CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002419 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002420 return Result;
2421}
2422
2423unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002424 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2425 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2426 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002427}
2428
2429CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2430 CXFile file,
2431 unsigned line,
2432 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002433 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002434 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002435
Douglas Gregorb9790342010-01-22 21:44:22 +00002436 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2437 SourceLocation SLoc
2438 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002439 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002440 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002441 if (SLoc.isInvalid()) return clang_getNullLocation();
2442
2443 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2444}
2445
2446CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2447 CXFile file,
2448 unsigned offset) {
2449 if (!tu || !file)
2450 return clang_getNullLocation();
2451
2452 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2453 SourceLocation Start
2454 = CXXUnit->getSourceManager().getLocation(
2455 static_cast<const FileEntry *>(file),
2456 1, 1);
2457 if (Start.isInvalid()) return clang_getNullLocation();
2458
2459 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2460
2461 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002462
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002463 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002464}
2465
Douglas Gregor5352ac02010-01-28 00:27:43 +00002466CXSourceRange clang_getNullRange() {
2467 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2468 return Result;
2469}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002470
Douglas Gregor5352ac02010-01-28 00:27:43 +00002471CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2472 if (begin.ptr_data[0] != end.ptr_data[0] ||
2473 begin.ptr_data[1] != end.ptr_data[1])
2474 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002475
2476 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002477 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002478 return Result;
2479}
2480
Douglas Gregor46766dc2010-01-26 19:19:08 +00002481void clang_getInstantiationLocation(CXSourceLocation location,
2482 CXFile *file,
2483 unsigned *line,
2484 unsigned *column,
2485 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002486 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2487
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002488 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002489 if (file)
2490 *file = 0;
2491 if (line)
2492 *line = 0;
2493 if (column)
2494 *column = 0;
2495 if (offset)
2496 *offset = 0;
2497 return;
2498 }
2499
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002500 const SourceManager &SM =
2501 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002502 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002503
2504 if (file)
2505 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2506 if (line)
2507 *line = SM.getInstantiationLineNumber(InstLoc);
2508 if (column)
2509 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002510 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002511 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002512}
2513
Douglas Gregora9b06d42010-11-09 06:24:54 +00002514void clang_getSpellingLocation(CXSourceLocation location,
2515 CXFile *file,
2516 unsigned *line,
2517 unsigned *column,
2518 unsigned *offset) {
2519 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2520
2521 if (!location.ptr_data[0] || Loc.isInvalid()) {
2522 if (file)
2523 *file = 0;
2524 if (line)
2525 *line = 0;
2526 if (column)
2527 *column = 0;
2528 if (offset)
2529 *offset = 0;
2530 return;
2531 }
2532
2533 const SourceManager &SM =
2534 *static_cast<const SourceManager*>(location.ptr_data[0]);
2535 SourceLocation SpellLoc = Loc;
2536 if (SpellLoc.isMacroID()) {
2537 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2538 if (SimpleSpellingLoc.isFileID() &&
2539 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2540 SpellLoc = SimpleSpellingLoc;
2541 else
2542 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2543 }
2544
2545 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2546 FileID FID = LocInfo.first;
2547 unsigned FileOffset = LocInfo.second;
2548
2549 if (file)
2550 *file = (void *)SM.getFileEntryForID(FID);
2551 if (line)
2552 *line = SM.getLineNumber(FID, FileOffset);
2553 if (column)
2554 *column = SM.getColumnNumber(FID, FileOffset);
2555 if (offset)
2556 *offset = FileOffset;
2557}
2558
Douglas Gregor1db19de2010-01-19 21:36:55 +00002559CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002560 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002561 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002562 return Result;
2563}
2564
2565CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002566 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002567 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002568 return Result;
2569}
2570
Douglas Gregorb9790342010-01-22 21:44:22 +00002571} // end: extern "C"
2572
Douglas Gregor1db19de2010-01-19 21:36:55 +00002573//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002574// CXFile Operations.
2575//===----------------------------------------------------------------------===//
2576
2577extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002578CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002579 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002580 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Steve Naroff88145032009-10-27 14:35:18 +00002582 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002583 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002584}
2585
2586time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002587 if (!SFile)
2588 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002589
Steve Naroff88145032009-10-27 14:35:18 +00002590 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2591 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002592}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002593
Douglas Gregorb9790342010-01-22 21:44:22 +00002594CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2595 if (!tu)
2596 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002597
Douglas Gregorb9790342010-01-22 21:44:22 +00002598 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002599
Douglas Gregorb9790342010-01-22 21:44:22 +00002600 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002601 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2602 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002603 return const_cast<FileEntry *>(File);
2604}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002605
Ted Kremenekfb480492010-01-13 21:46:36 +00002606} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002607
Ted Kremenekfb480492010-01-13 21:46:36 +00002608//===----------------------------------------------------------------------===//
2609// CXCursor Operations.
2610//===----------------------------------------------------------------------===//
2611
Ted Kremenekfb480492010-01-13 21:46:36 +00002612static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002613 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2614 return getDeclFromExpr(CE->getSubExpr());
2615
Ted Kremenekfb480492010-01-13 21:46:36 +00002616 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2617 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002618 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2619 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002620 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2621 return ME->getMemberDecl();
2622 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2623 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002624 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2625 return PRE->getProperty();
2626
Ted Kremenekfb480492010-01-13 21:46:36 +00002627 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2628 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002629 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2630 if (!CE->isElidable())
2631 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002632 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2633 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002634
Douglas Gregordb1314e2010-10-01 21:11:22 +00002635 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2636 return PE->getProtocol();
2637
Ted Kremenekfb480492010-01-13 21:46:36 +00002638 return 0;
2639}
2640
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002641static SourceLocation getLocationFromExpr(Expr *E) {
2642 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2643 return /*FIXME:*/Msg->getLeftLoc();
2644 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2645 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002646 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2647 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002648 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2649 return Member->getMemberLoc();
2650 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2651 return Ivar->getLocation();
2652 return E->getLocStart();
2653}
2654
Ted Kremenekfb480492010-01-13 21:46:36 +00002655extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002656
2657unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002658 CXCursorVisitor visitor,
2659 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002660 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002661
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002662 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2663 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002664 return CursorVis.VisitChildren(parent);
2665}
2666
David Chisnall3387c652010-11-03 14:12:26 +00002667#ifndef __has_feature
2668#define __has_feature(x) 0
2669#endif
2670#if __has_feature(blocks)
2671typedef enum CXChildVisitResult
2672 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2673
2674static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2675 CXClientData client_data) {
2676 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2677 return block(cursor, parent);
2678}
2679#else
2680// If we are compiled with a compiler that doesn't have native blocks support,
2681// define and call the block manually, so the
2682typedef struct _CXChildVisitResult
2683{
2684 void *isa;
2685 int flags;
2686 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002687 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2688 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002689} *CXCursorVisitorBlock;
2690
2691static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2692 CXClientData client_data) {
2693 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2694 return block->invoke(block, cursor, parent);
2695}
2696#endif
2697
2698
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002699unsigned clang_visitChildrenWithBlock(CXCursor parent,
2700 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002701 return clang_visitChildren(parent, visitWithBlock, block);
2702}
2703
Douglas Gregor78205d42010-01-20 21:45:58 +00002704static CXString getDeclSpelling(Decl *D) {
2705 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2706 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002707 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002708
Douglas Gregor78205d42010-01-20 21:45:58 +00002709 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002710 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002711
Douglas Gregor78205d42010-01-20 21:45:58 +00002712 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2713 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2714 // and returns different names. NamedDecl returns the class name and
2715 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002716 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002717
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002718 if (isa<UsingDirectiveDecl>(D))
2719 return createCXString("");
2720
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002721 llvm::SmallString<1024> S;
2722 llvm::raw_svector_ostream os(S);
2723 ND->printName(os);
2724
2725 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002726}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002727
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002728CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002729 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002730 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002731
Steve Narofff334b4e2009-09-02 18:26:48 +00002732 if (clang_isReference(C.kind)) {
2733 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002734 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002735 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002736 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002737 }
2738 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002739 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002740 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002741 }
2742 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002743 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002744 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002745 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002746 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002747 case CXCursor_CXXBaseSpecifier: {
2748 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2749 return createCXString(B->getType().getAsString());
2750 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002751 case CXCursor_TypeRef: {
2752 TypeDecl *Type = getCursorTypeRef(C).first;
2753 assert(Type && "Missing type decl");
2754
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002755 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2756 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002757 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002758 case CXCursor_TemplateRef: {
2759 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002760 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002761
2762 return createCXString(Template->getNameAsString());
2763 }
Douglas Gregor69319002010-08-31 23:48:11 +00002764
2765 case CXCursor_NamespaceRef: {
2766 NamedDecl *NS = getCursorNamespaceRef(C).first;
2767 assert(NS && "Missing namespace decl");
2768
2769 return createCXString(NS->getNameAsString());
2770 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002771
Douglas Gregora67e03f2010-09-09 21:42:20 +00002772 case CXCursor_MemberRef: {
2773 FieldDecl *Field = getCursorMemberRef(C).first;
2774 assert(Field && "Missing member decl");
2775
2776 return createCXString(Field->getNameAsString());
2777 }
2778
Douglas Gregor36897b02010-09-10 00:22:18 +00002779 case CXCursor_LabelRef: {
2780 LabelStmt *Label = getCursorLabelRef(C).first;
2781 assert(Label && "Missing label");
2782
2783 return createCXString(Label->getID()->getName());
2784 }
2785
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002786 case CXCursor_OverloadedDeclRef: {
2787 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2788 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2789 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2790 return createCXString(ND->getNameAsString());
2791 return createCXString("");
2792 }
2793 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2794 return createCXString(E->getName().getAsString());
2795 OverloadedTemplateStorage *Ovl
2796 = Storage.get<OverloadedTemplateStorage*>();
2797 if (Ovl->size() == 0)
2798 return createCXString("");
2799 return createCXString((*Ovl->begin())->getNameAsString());
2800 }
2801
Daniel Dunbaracca7252009-11-30 20:42:49 +00002802 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002803 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002804 }
2805 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002806
2807 if (clang_isExpression(C.kind)) {
2808 Decl *D = getDeclFromExpr(getCursorExpr(C));
2809 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002810 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002811 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002812 }
2813
Douglas Gregor36897b02010-09-10 00:22:18 +00002814 if (clang_isStatement(C.kind)) {
2815 Stmt *S = getCursorStmt(C);
2816 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2817 return createCXString(Label->getID()->getName());
2818
2819 return createCXString("");
2820 }
2821
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002822 if (C.kind == CXCursor_MacroInstantiation)
2823 return createCXString(getCursorMacroInstantiation(C)->getName()
2824 ->getNameStart());
2825
Douglas Gregor572feb22010-03-18 18:04:21 +00002826 if (C.kind == CXCursor_MacroDefinition)
2827 return createCXString(getCursorMacroDefinition(C)->getName()
2828 ->getNameStart());
2829
Douglas Gregorecdcb882010-10-20 22:00:55 +00002830 if (C.kind == CXCursor_InclusionDirective)
2831 return createCXString(getCursorInclusionDirective(C)->getFileName());
2832
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002833 if (clang_isDeclaration(C.kind))
2834 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002835
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002836 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002837}
2838
Douglas Gregor358559d2010-10-02 22:49:11 +00002839CXString clang_getCursorDisplayName(CXCursor C) {
2840 if (!clang_isDeclaration(C.kind))
2841 return clang_getCursorSpelling(C);
2842
2843 Decl *D = getCursorDecl(C);
2844 if (!D)
2845 return createCXString("");
2846
2847 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2848 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2849 D = FunTmpl->getTemplatedDecl();
2850
2851 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2852 llvm::SmallString<64> Str;
2853 llvm::raw_svector_ostream OS(Str);
2854 OS << Function->getNameAsString();
2855 if (Function->getPrimaryTemplate())
2856 OS << "<>";
2857 OS << "(";
2858 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2859 if (I)
2860 OS << ", ";
2861 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2862 }
2863
2864 if (Function->isVariadic()) {
2865 if (Function->getNumParams())
2866 OS << ", ";
2867 OS << "...";
2868 }
2869 OS << ")";
2870 return createCXString(OS.str());
2871 }
2872
2873 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2874 llvm::SmallString<64> Str;
2875 llvm::raw_svector_ostream OS(Str);
2876 OS << ClassTemplate->getNameAsString();
2877 OS << "<";
2878 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2879 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2880 if (I)
2881 OS << ", ";
2882
2883 NamedDecl *Param = Params->getParam(I);
2884 if (Param->getIdentifier()) {
2885 OS << Param->getIdentifier()->getName();
2886 continue;
2887 }
2888
2889 // There is no parameter name, which makes this tricky. Try to come up
2890 // with something useful that isn't too long.
2891 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2892 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2893 else if (NonTypeTemplateParmDecl *NTTP
2894 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2895 OS << NTTP->getType().getAsString(Policy);
2896 else
2897 OS << "template<...> class";
2898 }
2899
2900 OS << ">";
2901 return createCXString(OS.str());
2902 }
2903
2904 if (ClassTemplateSpecializationDecl *ClassSpec
2905 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2906 // If the type was explicitly written, use that.
2907 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2908 return createCXString(TSInfo->getType().getAsString(Policy));
2909
2910 llvm::SmallString<64> Str;
2911 llvm::raw_svector_ostream OS(Str);
2912 OS << ClassSpec->getNameAsString();
2913 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002914 ClassSpec->getTemplateArgs().data(),
2915 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002916 Policy);
2917 return createCXString(OS.str());
2918 }
2919
2920 return clang_getCursorSpelling(C);
2921}
2922
Ted Kremeneke68fff62010-02-17 00:41:32 +00002923CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002924 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002925 case CXCursor_FunctionDecl:
2926 return createCXString("FunctionDecl");
2927 case CXCursor_TypedefDecl:
2928 return createCXString("TypedefDecl");
2929 case CXCursor_EnumDecl:
2930 return createCXString("EnumDecl");
2931 case CXCursor_EnumConstantDecl:
2932 return createCXString("EnumConstantDecl");
2933 case CXCursor_StructDecl:
2934 return createCXString("StructDecl");
2935 case CXCursor_UnionDecl:
2936 return createCXString("UnionDecl");
2937 case CXCursor_ClassDecl:
2938 return createCXString("ClassDecl");
2939 case CXCursor_FieldDecl:
2940 return createCXString("FieldDecl");
2941 case CXCursor_VarDecl:
2942 return createCXString("VarDecl");
2943 case CXCursor_ParmDecl:
2944 return createCXString("ParmDecl");
2945 case CXCursor_ObjCInterfaceDecl:
2946 return createCXString("ObjCInterfaceDecl");
2947 case CXCursor_ObjCCategoryDecl:
2948 return createCXString("ObjCCategoryDecl");
2949 case CXCursor_ObjCProtocolDecl:
2950 return createCXString("ObjCProtocolDecl");
2951 case CXCursor_ObjCPropertyDecl:
2952 return createCXString("ObjCPropertyDecl");
2953 case CXCursor_ObjCIvarDecl:
2954 return createCXString("ObjCIvarDecl");
2955 case CXCursor_ObjCInstanceMethodDecl:
2956 return createCXString("ObjCInstanceMethodDecl");
2957 case CXCursor_ObjCClassMethodDecl:
2958 return createCXString("ObjCClassMethodDecl");
2959 case CXCursor_ObjCImplementationDecl:
2960 return createCXString("ObjCImplementationDecl");
2961 case CXCursor_ObjCCategoryImplDecl:
2962 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002963 case CXCursor_CXXMethod:
2964 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002965 case CXCursor_UnexposedDecl:
2966 return createCXString("UnexposedDecl");
2967 case CXCursor_ObjCSuperClassRef:
2968 return createCXString("ObjCSuperClassRef");
2969 case CXCursor_ObjCProtocolRef:
2970 return createCXString("ObjCProtocolRef");
2971 case CXCursor_ObjCClassRef:
2972 return createCXString("ObjCClassRef");
2973 case CXCursor_TypeRef:
2974 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002975 case CXCursor_TemplateRef:
2976 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002977 case CXCursor_NamespaceRef:
2978 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002979 case CXCursor_MemberRef:
2980 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002981 case CXCursor_LabelRef:
2982 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002983 case CXCursor_OverloadedDeclRef:
2984 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002985 case CXCursor_UnexposedExpr:
2986 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002987 case CXCursor_BlockExpr:
2988 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002989 case CXCursor_DeclRefExpr:
2990 return createCXString("DeclRefExpr");
2991 case CXCursor_MemberRefExpr:
2992 return createCXString("MemberRefExpr");
2993 case CXCursor_CallExpr:
2994 return createCXString("CallExpr");
2995 case CXCursor_ObjCMessageExpr:
2996 return createCXString("ObjCMessageExpr");
2997 case CXCursor_UnexposedStmt:
2998 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002999 case CXCursor_LabelStmt:
3000 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003001 case CXCursor_InvalidFile:
3002 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003003 case CXCursor_InvalidCode:
3004 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003005 case CXCursor_NoDeclFound:
3006 return createCXString("NoDeclFound");
3007 case CXCursor_NotImplemented:
3008 return createCXString("NotImplemented");
3009 case CXCursor_TranslationUnit:
3010 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003011 case CXCursor_UnexposedAttr:
3012 return createCXString("UnexposedAttr");
3013 case CXCursor_IBActionAttr:
3014 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003015 case CXCursor_IBOutletAttr:
3016 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003017 case CXCursor_IBOutletCollectionAttr:
3018 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003019 case CXCursor_PreprocessingDirective:
3020 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003021 case CXCursor_MacroDefinition:
3022 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003023 case CXCursor_MacroInstantiation:
3024 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003025 case CXCursor_InclusionDirective:
3026 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003027 case CXCursor_Namespace:
3028 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003029 case CXCursor_LinkageSpec:
3030 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003031 case CXCursor_CXXBaseSpecifier:
3032 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003033 case CXCursor_Constructor:
3034 return createCXString("CXXConstructor");
3035 case CXCursor_Destructor:
3036 return createCXString("CXXDestructor");
3037 case CXCursor_ConversionFunction:
3038 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003039 case CXCursor_TemplateTypeParameter:
3040 return createCXString("TemplateTypeParameter");
3041 case CXCursor_NonTypeTemplateParameter:
3042 return createCXString("NonTypeTemplateParameter");
3043 case CXCursor_TemplateTemplateParameter:
3044 return createCXString("TemplateTemplateParameter");
3045 case CXCursor_FunctionTemplate:
3046 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003047 case CXCursor_ClassTemplate:
3048 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003049 case CXCursor_ClassTemplatePartialSpecialization:
3050 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003051 case CXCursor_NamespaceAlias:
3052 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003053 case CXCursor_UsingDirective:
3054 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003055 case CXCursor_UsingDeclaration:
3056 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003057 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003058
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003059 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003060 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003061}
Steve Naroff89922f82009-08-31 00:59:03 +00003062
Ted Kremeneke68fff62010-02-17 00:41:32 +00003063enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3064 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003065 CXClientData client_data) {
3066 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003067
3068 // If our current best cursor is the construction of a temporary object,
3069 // don't replace that cursor with a type reference, because we want
3070 // clang_getCursor() to point at the constructor.
3071 if (clang_isExpression(BestCursor->kind) &&
3072 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3073 cursor.kind == CXCursor_TypeRef)
3074 return CXChildVisit_Recurse;
3075
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003076 *BestCursor = cursor;
3077 return CXChildVisit_Recurse;
3078}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003079
Douglas Gregorb9790342010-01-22 21:44:22 +00003080CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3081 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003082 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003083
Douglas Gregorb9790342010-01-22 21:44:22 +00003084 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003085 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3086
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003087 // Translate the given source location to make it point at the beginning of
3088 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003089 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003090
3091 // Guard against an invalid SourceLocation, or we may assert in one
3092 // of the following calls.
3093 if (SLoc.isInvalid())
3094 return clang_getNullCursor();
3095
Douglas Gregor40749ee2010-11-03 00:35:38 +00003096 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003097 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3098 CXXUnit->getASTContext().getLangOptions());
3099
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003100 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3101 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003102 // FIXME: Would be great to have a "hint" cursor, then walk from that
3103 // hint cursor upward until we find a cursor whose source range encloses
3104 // the region of interest, rather than starting from the translation unit.
3105 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003106 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003107 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003108 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003109 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003110
3111 if (Logging) {
3112 CXFile SearchFile;
3113 unsigned SearchLine, SearchColumn;
3114 CXFile ResultFile;
3115 unsigned ResultLine, ResultColumn;
3116 CXString SearchFileName, ResultFileName, KindSpelling;
3117 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3118
3119 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3120 0);
3121 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3122 &ResultColumn, 0);
3123 SearchFileName = clang_getFileName(SearchFile);
3124 ResultFileName = clang_getFileName(ResultFile);
3125 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3126 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3127 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3128 clang_getCString(KindSpelling),
3129 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3130 clang_disposeString(SearchFileName);
3131 clang_disposeString(ResultFileName);
3132 clang_disposeString(KindSpelling);
3133 }
3134
Ted Kremeneke68fff62010-02-17 00:41:32 +00003135 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003136}
3137
Ted Kremenek73885552009-11-17 19:28:59 +00003138CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003139 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003140}
3141
3142unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003143 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003144}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003145
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003146unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003147 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3148}
3149
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003150unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003151 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3152}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003153
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003154unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003155 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3156}
3157
Douglas Gregor97b98722010-01-19 23:20:36 +00003158unsigned clang_isExpression(enum CXCursorKind K) {
3159 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3160}
3161
3162unsigned clang_isStatement(enum CXCursorKind K) {
3163 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3164}
3165
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003166unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3167 return K == CXCursor_TranslationUnit;
3168}
3169
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003170unsigned clang_isPreprocessing(enum CXCursorKind K) {
3171 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3172}
3173
Ted Kremenekad6eff62010-03-08 21:17:29 +00003174unsigned clang_isUnexposed(enum CXCursorKind K) {
3175 switch (K) {
3176 case CXCursor_UnexposedDecl:
3177 case CXCursor_UnexposedExpr:
3178 case CXCursor_UnexposedStmt:
3179 case CXCursor_UnexposedAttr:
3180 return true;
3181 default:
3182 return false;
3183 }
3184}
3185
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003186CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003187 return C.kind;
3188}
3189
Douglas Gregor98258af2010-01-18 22:46:11 +00003190CXSourceLocation clang_getCursorLocation(CXCursor C) {
3191 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003192 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003193 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003194 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3195 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003196 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003197 }
3198
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003199 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003200 std::pair<ObjCProtocolDecl *, SourceLocation> P
3201 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003202 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003203 }
3204
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003205 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003206 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3207 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003208 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003209 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003210
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003211 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003212 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003213 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003214 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003215
3216 case CXCursor_TemplateRef: {
3217 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3218 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3219 }
3220
Douglas Gregor69319002010-08-31 23:48:11 +00003221 case CXCursor_NamespaceRef: {
3222 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3223 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3224 }
3225
Douglas Gregora67e03f2010-09-09 21:42:20 +00003226 case CXCursor_MemberRef: {
3227 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3228 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3229 }
3230
Ted Kremenek3064ef92010-08-27 21:34:58 +00003231 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003232 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3233 if (!BaseSpec)
3234 return clang_getNullLocation();
3235
3236 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3237 return cxloc::translateSourceLocation(getCursorContext(C),
3238 TSInfo->getTypeLoc().getBeginLoc());
3239
3240 return cxloc::translateSourceLocation(getCursorContext(C),
3241 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003242 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003243
Douglas Gregor36897b02010-09-10 00:22:18 +00003244 case CXCursor_LabelRef: {
3245 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3246 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3247 }
3248
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003249 case CXCursor_OverloadedDeclRef:
3250 return cxloc::translateSourceLocation(getCursorContext(C),
3251 getCursorOverloadedDeclRef(C).second);
3252
Douglas Gregorf46034a2010-01-18 23:41:10 +00003253 default:
3254 // FIXME: Need a way to enumerate all non-reference cases.
3255 llvm_unreachable("Missed a reference kind");
3256 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003257 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003258
3259 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003260 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003261 getLocationFromExpr(getCursorExpr(C)));
3262
Douglas Gregor36897b02010-09-10 00:22:18 +00003263 if (clang_isStatement(C.kind))
3264 return cxloc::translateSourceLocation(getCursorContext(C),
3265 getCursorStmt(C)->getLocStart());
3266
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003267 if (C.kind == CXCursor_PreprocessingDirective) {
3268 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3269 return cxloc::translateSourceLocation(getCursorContext(C), L);
3270 }
Douglas Gregor48072312010-03-18 15:23:44 +00003271
3272 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003273 SourceLocation L
3274 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003275 return cxloc::translateSourceLocation(getCursorContext(C), L);
3276 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003277
3278 if (C.kind == CXCursor_MacroDefinition) {
3279 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3280 return cxloc::translateSourceLocation(getCursorContext(C), L);
3281 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003282
3283 if (C.kind == CXCursor_InclusionDirective) {
3284 SourceLocation L
3285 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3286 return cxloc::translateSourceLocation(getCursorContext(C), L);
3287 }
3288
Ted Kremenek9a700d22010-05-12 06:16:13 +00003289 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003290 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003291
Douglas Gregorf46034a2010-01-18 23:41:10 +00003292 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003293 SourceLocation Loc = D->getLocation();
3294 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3295 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003296 // FIXME: Multiple variables declared in a single declaration
3297 // currently lack the information needed to correctly determine their
3298 // ranges when accounting for the type-specifier. We use context
3299 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3300 // and if so, whether it is the first decl.
3301 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3302 if (!cxcursor::isFirstInDeclGroup(C))
3303 Loc = VD->getLocation();
3304 }
3305
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003306 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003307}
Douglas Gregora7bde202010-01-19 00:34:46 +00003308
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003309} // end extern "C"
3310
3311static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003312 if (clang_isReference(C.kind)) {
3313 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003314 case CXCursor_ObjCSuperClassRef:
3315 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003316
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003317 case CXCursor_ObjCProtocolRef:
3318 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003319
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003320 case CXCursor_ObjCClassRef:
3321 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003322
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003323 case CXCursor_TypeRef:
3324 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003325
3326 case CXCursor_TemplateRef:
3327 return getCursorTemplateRef(C).second;
3328
Douglas Gregor69319002010-08-31 23:48:11 +00003329 case CXCursor_NamespaceRef:
3330 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003331
3332 case CXCursor_MemberRef:
3333 return getCursorMemberRef(C).second;
3334
Ted Kremenek3064ef92010-08-27 21:34:58 +00003335 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003336 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003337
Douglas Gregor36897b02010-09-10 00:22:18 +00003338 case CXCursor_LabelRef:
3339 return getCursorLabelRef(C).second;
3340
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003341 case CXCursor_OverloadedDeclRef:
3342 return getCursorOverloadedDeclRef(C).second;
3343
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003344 default:
3345 // FIXME: Need a way to enumerate all non-reference cases.
3346 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003347 }
3348 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003349
3350 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003351 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003352
3353 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003354 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003355
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003356 if (C.kind == CXCursor_PreprocessingDirective)
3357 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003358
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003359 if (C.kind == CXCursor_MacroInstantiation)
3360 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003361
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003362 if (C.kind == CXCursor_MacroDefinition)
3363 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003364
3365 if (C.kind == CXCursor_InclusionDirective)
3366 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3367
Ted Kremenek007a7c92010-11-01 23:26:51 +00003368 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3369 Decl *D = cxcursor::getCursorDecl(C);
3370 SourceRange R = D->getSourceRange();
3371 // FIXME: Multiple variables declared in a single declaration
3372 // currently lack the information needed to correctly determine their
3373 // ranges when accounting for the type-specifier. We use context
3374 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3375 // and if so, whether it is the first decl.
3376 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3377 if (!cxcursor::isFirstInDeclGroup(C))
3378 R.setBegin(VD->getLocation());
3379 }
3380 return R;
3381 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003382 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003383
3384extern "C" {
3385
3386CXSourceRange clang_getCursorExtent(CXCursor C) {
3387 SourceRange R = getRawCursorExtent(C);
3388 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003389 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003390
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003391 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003392}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003393
3394CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003395 if (clang_isInvalid(C.kind))
3396 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003397
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003398 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003399 if (clang_isDeclaration(C.kind)) {
3400 Decl *D = getCursorDecl(C);
3401 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3402 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3403 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3404 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3405 if (ObjCForwardProtocolDecl *Protocols
3406 = dyn_cast<ObjCForwardProtocolDecl>(D))
3407 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3408
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003409 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003410 }
3411
Douglas Gregor97b98722010-01-19 23:20:36 +00003412 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003413 Expr *E = getCursorExpr(C);
3414 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003415 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003416 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003417
3418 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3419 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3420
Douglas Gregor97b98722010-01-19 23:20:36 +00003421 return clang_getNullCursor();
3422 }
3423
Douglas Gregor36897b02010-09-10 00:22:18 +00003424 if (clang_isStatement(C.kind)) {
3425 Stmt *S = getCursorStmt(C);
3426 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3427 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3428 getCursorASTUnit(C));
3429
3430 return clang_getNullCursor();
3431 }
3432
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003433 if (C.kind == CXCursor_MacroInstantiation) {
3434 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3435 return MakeMacroDefinitionCursor(Def, CXXUnit);
3436 }
3437
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003438 if (!clang_isReference(C.kind))
3439 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003440
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003441 switch (C.kind) {
3442 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003443 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003444
3445 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003446 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003447
3448 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003449 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003450
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003451 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003452 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003453
3454 case CXCursor_TemplateRef:
3455 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3456
Douglas Gregor69319002010-08-31 23:48:11 +00003457 case CXCursor_NamespaceRef:
3458 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3459
Douglas Gregora67e03f2010-09-09 21:42:20 +00003460 case CXCursor_MemberRef:
3461 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3462
Ted Kremenek3064ef92010-08-27 21:34:58 +00003463 case CXCursor_CXXBaseSpecifier: {
3464 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3465 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3466 CXXUnit));
3467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003468
Douglas Gregor36897b02010-09-10 00:22:18 +00003469 case CXCursor_LabelRef:
3470 // FIXME: We end up faking the "parent" declaration here because we
3471 // don't want to make CXCursor larger.
3472 return MakeCXCursor(getCursorLabelRef(C).first,
3473 CXXUnit->getASTContext().getTranslationUnitDecl(),
3474 CXXUnit);
3475
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003476 case CXCursor_OverloadedDeclRef:
3477 return C;
3478
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003479 default:
3480 // We would prefer to enumerate all non-reference cursor kinds here.
3481 llvm_unreachable("Unhandled reference cursor kind");
3482 break;
3483 }
3484 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003485
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003486 return clang_getNullCursor();
3487}
3488
Douglas Gregorb6998662010-01-19 19:34:47 +00003489CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003490 if (clang_isInvalid(C.kind))
3491 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003492
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003493 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003494
Douglas Gregorb6998662010-01-19 19:34:47 +00003495 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003496 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003497 C = clang_getCursorReferenced(C);
3498 WasReference = true;
3499 }
3500
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003501 if (C.kind == CXCursor_MacroInstantiation)
3502 return clang_getCursorReferenced(C);
3503
Douglas Gregorb6998662010-01-19 19:34:47 +00003504 if (!clang_isDeclaration(C.kind))
3505 return clang_getNullCursor();
3506
3507 Decl *D = getCursorDecl(C);
3508 if (!D)
3509 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003510
Douglas Gregorb6998662010-01-19 19:34:47 +00003511 switch (D->getKind()) {
3512 // Declaration kinds that don't really separate the notions of
3513 // declaration and definition.
3514 case Decl::Namespace:
3515 case Decl::Typedef:
3516 case Decl::TemplateTypeParm:
3517 case Decl::EnumConstant:
3518 case Decl::Field:
3519 case Decl::ObjCIvar:
3520 case Decl::ObjCAtDefsField:
3521 case Decl::ImplicitParam:
3522 case Decl::ParmVar:
3523 case Decl::NonTypeTemplateParm:
3524 case Decl::TemplateTemplateParm:
3525 case Decl::ObjCCategoryImpl:
3526 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003527 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003528 case Decl::LinkageSpec:
3529 case Decl::ObjCPropertyImpl:
3530 case Decl::FileScopeAsm:
3531 case Decl::StaticAssert:
3532 case Decl::Block:
3533 return C;
3534
3535 // Declaration kinds that don't make any sense here, but are
3536 // nonetheless harmless.
3537 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003538 break;
3539
3540 // Declaration kinds for which the definition is not resolvable.
3541 case Decl::UnresolvedUsingTypename:
3542 case Decl::UnresolvedUsingValue:
3543 break;
3544
3545 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003546 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3547 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003548
3549 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003550 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003551
3552 case Decl::Enum:
3553 case Decl::Record:
3554 case Decl::CXXRecord:
3555 case Decl::ClassTemplateSpecialization:
3556 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003557 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003558 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003559 return clang_getNullCursor();
3560
3561 case Decl::Function:
3562 case Decl::CXXMethod:
3563 case Decl::CXXConstructor:
3564 case Decl::CXXDestructor:
3565 case Decl::CXXConversion: {
3566 const FunctionDecl *Def = 0;
3567 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003568 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003569 return clang_getNullCursor();
3570 }
3571
3572 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003573 // Ask the variable if it has a definition.
3574 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3575 return MakeCXCursor(Def, CXXUnit);
3576 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003577 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003578
Douglas Gregorb6998662010-01-19 19:34:47 +00003579 case Decl::FunctionTemplate: {
3580 const FunctionDecl *Def = 0;
3581 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003582 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003583 return clang_getNullCursor();
3584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585
Douglas Gregorb6998662010-01-19 19:34:47 +00003586 case Decl::ClassTemplate: {
3587 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003588 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003589 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003590 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003591 return clang_getNullCursor();
3592 }
3593
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003594 case Decl::Using:
3595 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3596 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003597
3598 case Decl::UsingShadow:
3599 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003600 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003601 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003602
3603 case Decl::ObjCMethod: {
3604 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3605 if (Method->isThisDeclarationADefinition())
3606 return C;
3607
3608 // Dig out the method definition in the associated
3609 // @implementation, if we have it.
3610 // FIXME: The ASTs should make finding the definition easier.
3611 if (ObjCInterfaceDecl *Class
3612 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3613 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3614 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3615 Method->isInstanceMethod()))
3616 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003617 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003618
3619 return clang_getNullCursor();
3620 }
3621
3622 case Decl::ObjCCategory:
3623 if (ObjCCategoryImplDecl *Impl
3624 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003625 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003626 return clang_getNullCursor();
3627
3628 case Decl::ObjCProtocol:
3629 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3630 return C;
3631 return clang_getNullCursor();
3632
3633 case Decl::ObjCInterface:
3634 // There are two notions of a "definition" for an Objective-C
3635 // class: the interface and its implementation. When we resolved a
3636 // reference to an Objective-C class, produce the @interface as
3637 // the definition; when we were provided with the interface,
3638 // produce the @implementation as the definition.
3639 if (WasReference) {
3640 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3641 return C;
3642 } else if (ObjCImplementationDecl *Impl
3643 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003644 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003645 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003646
Douglas Gregorb6998662010-01-19 19:34:47 +00003647 case Decl::ObjCProperty:
3648 // FIXME: We don't really know where to find the
3649 // ObjCPropertyImplDecls that implement this property.
3650 return clang_getNullCursor();
3651
3652 case Decl::ObjCCompatibleAlias:
3653 if (ObjCInterfaceDecl *Class
3654 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3655 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003656 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003657
Douglas Gregorb6998662010-01-19 19:34:47 +00003658 return clang_getNullCursor();
3659
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003660 case Decl::ObjCForwardProtocol:
3661 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3662 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003663
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003664 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003665 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003666 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003667
3668 case Decl::Friend:
3669 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003670 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003671 return clang_getNullCursor();
3672
3673 case Decl::FriendTemplate:
3674 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003675 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003676 return clang_getNullCursor();
3677 }
3678
3679 return clang_getNullCursor();
3680}
3681
3682unsigned clang_isCursorDefinition(CXCursor C) {
3683 if (!clang_isDeclaration(C.kind))
3684 return 0;
3685
3686 return clang_getCursorDefinition(C) == C;
3687}
3688
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003689unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003690 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003691 return 0;
3692
3693 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3694 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3695 return E->getNumDecls();
3696
3697 if (OverloadedTemplateStorage *S
3698 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3699 return S->size();
3700
3701 Decl *D = Storage.get<Decl*>();
3702 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003703 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003704 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3705 return Classes->size();
3706 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3707 return Protocols->protocol_size();
3708
3709 return 0;
3710}
3711
3712CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003713 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003714 return clang_getNullCursor();
3715
3716 if (index >= clang_getNumOverloadedDecls(cursor))
3717 return clang_getNullCursor();
3718
3719 ASTUnit *Unit = getCursorASTUnit(cursor);
3720 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3721 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3722 return MakeCXCursor(E->decls_begin()[index], Unit);
3723
3724 if (OverloadedTemplateStorage *S
3725 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3726 return MakeCXCursor(S->begin()[index], Unit);
3727
3728 Decl *D = Storage.get<Decl*>();
3729 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3730 // FIXME: This is, unfortunately, linear time.
3731 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3732 std::advance(Pos, index);
3733 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3734 }
3735
3736 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3737 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3738
3739 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3740 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3741
3742 return clang_getNullCursor();
3743}
3744
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003745void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003746 const char **startBuf,
3747 const char **endBuf,
3748 unsigned *startLine,
3749 unsigned *startColumn,
3750 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003751 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003752 assert(getCursorDecl(C) && "CXCursor has null decl");
3753 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003754 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3755 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003756
Steve Naroff4ade6d62009-09-23 17:52:52 +00003757 SourceManager &SM = FD->getASTContext().getSourceManager();
3758 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3759 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3760 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3761 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3762 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3763 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3764}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003765
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003766void clang_enableStackTraces(void) {
3767 llvm::sys::PrintStackTraceOnErrorSignal();
3768}
3769
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003770void clang_executeOnThread(void (*fn)(void*), void *user_data,
3771 unsigned stack_size) {
3772 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3773}
3774
Ted Kremenekfb480492010-01-13 21:46:36 +00003775} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003776
Ted Kremenekfb480492010-01-13 21:46:36 +00003777//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003778// Token-based Operations.
3779//===----------------------------------------------------------------------===//
3780
3781/* CXToken layout:
3782 * int_data[0]: a CXTokenKind
3783 * int_data[1]: starting token location
3784 * int_data[2]: token length
3785 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003786 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003787 * otherwise unused.
3788 */
3789extern "C" {
3790
3791CXTokenKind clang_getTokenKind(CXToken CXTok) {
3792 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3793}
3794
3795CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3796 switch (clang_getTokenKind(CXTok)) {
3797 case CXToken_Identifier:
3798 case CXToken_Keyword:
3799 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003800 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3801 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802
3803 case CXToken_Literal: {
3804 // We have stashed the starting pointer in the ptr_data field. Use it.
3805 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003806 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003808
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003809 case CXToken_Punctuation:
3810 case CXToken_Comment:
3811 break;
3812 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003813
3814 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003815 // deconstructing the source location.
3816 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3817 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003818 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003819
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3821 std::pair<FileID, unsigned> LocInfo
3822 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003823 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003824 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003825 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3826 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003827 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003828
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003829 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003830}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003831
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003832CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3833 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3834 if (!CXXUnit)
3835 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3838 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3839}
3840
3841CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3842 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003843 if (!CXXUnit)
3844 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003845
3846 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003847 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3848}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003849
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003850void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3851 CXToken **Tokens, unsigned *NumTokens) {
3852 if (Tokens)
3853 *Tokens = 0;
3854 if (NumTokens)
3855 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003856
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003857 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3858 if (!CXXUnit || !Tokens || !NumTokens)
3859 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003860
Douglas Gregorbdf60622010-03-05 21:16:25 +00003861 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3862
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003863 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 if (R.isInvalid())
3865 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003866
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003867 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3868 std::pair<FileID, unsigned> BeginLocInfo
3869 = SourceMgr.getDecomposedLoc(R.getBegin());
3870 std::pair<FileID, unsigned> EndLocInfo
3871 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003872
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003873 // Cannot tokenize across files.
3874 if (BeginLocInfo.first != EndLocInfo.first)
3875 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003876
3877 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003878 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003879 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003880 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003881 if (Invalid)
3882 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003883
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003884 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3885 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003886 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003887 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003888
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003889 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003890 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891 llvm::SmallVector<CXToken, 32> CXTokens;
3892 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003893 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 do {
3895 // Lex the next token
3896 Lex.LexFromRawLexer(Tok);
3897 if (Tok.is(tok::eof))
3898 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003899
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003900 // Initialize the CXToken.
3901 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003902
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003903 // - Common fields
3904 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3905 CXTok.int_data[2] = Tok.getLength();
3906 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003907
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003908 // - Kind-specific fields
3909 if (Tok.isLiteral()) {
3910 CXTok.int_data[0] = CXToken_Literal;
3911 CXTok.ptr_data = (void *)Tok.getLiteralData();
3912 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003913 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003914 std::pair<FileID, unsigned> LocInfo
3915 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003916 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003917 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003918 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3919 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003920 return;
3921
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003922 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003923 IdentifierInfo *II
3924 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003925
David Chisnall096428b2010-10-13 21:44:48 +00003926 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003927 CXTok.int_data[0] = CXToken_Keyword;
3928 }
3929 else {
3930 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3931 CXToken_Identifier
3932 : CXToken_Keyword;
3933 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003934 CXTok.ptr_data = II;
3935 } else if (Tok.is(tok::comment)) {
3936 CXTok.int_data[0] = CXToken_Comment;
3937 CXTok.ptr_data = 0;
3938 } else {
3939 CXTok.int_data[0] = CXToken_Punctuation;
3940 CXTok.ptr_data = 0;
3941 }
3942 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003943 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003944 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003945
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003946 if (CXTokens.empty())
3947 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003948
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003949 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3950 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3951 *NumTokens = CXTokens.size();
3952}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003953
Ted Kremenek6db61092010-05-05 00:55:15 +00003954void clang_disposeTokens(CXTranslationUnit TU,
3955 CXToken *Tokens, unsigned NumTokens) {
3956 free(Tokens);
3957}
3958
3959} // end: extern "C"
3960
3961//===----------------------------------------------------------------------===//
3962// Token annotation APIs.
3963//===----------------------------------------------------------------------===//
3964
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003965typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003966static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3967 CXCursor parent,
3968 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003969namespace {
3970class AnnotateTokensWorker {
3971 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003972 CXToken *Tokens;
3973 CXCursor *Cursors;
3974 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003975 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003976 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003977 CursorVisitor AnnotateVis;
3978 SourceManager &SrcMgr;
3979
3980 bool MoreTokens() const { return TokIdx < NumTokens; }
3981 unsigned NextToken() const { return TokIdx; }
3982 void AdvanceToken() { ++TokIdx; }
3983 SourceLocation GetTokenLoc(unsigned tokI) {
3984 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3985 }
3986
Ted Kremenek6db61092010-05-05 00:55:15 +00003987public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003988 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003989 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3990 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003991 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003992 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003993 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3994 Decl::MaxPCHLevel, RegionOfInterest),
3995 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003996
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003997 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003998 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003999 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004000 void AnnotateTokens() {
4001 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
4002 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004003};
4004}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004005
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004006void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4007 // Walk the AST within the region of interest, annotating tokens
4008 // along the way.
4009 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004010
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004011 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4012 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004013 if (Pos != Annotated.end() &&
4014 (clang_isInvalid(Cursors[I].kind) ||
4015 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004016 Cursors[I] = Pos->second;
4017 }
4018
4019 // Finish up annotating any tokens left.
4020 if (!MoreTokens())
4021 return;
4022
4023 const CXCursor &C = clang_getNullCursor();
4024 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4025 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4026 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004027 }
4028}
4029
Ted Kremenek6db61092010-05-05 00:55:15 +00004030enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004031AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004032 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004033 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004034 if (cursorRange.isInvalid())
4035 return CXChildVisit_Recurse;
4036
Douglas Gregor4419b672010-10-21 06:10:04 +00004037 if (clang_isPreprocessing(cursor.kind)) {
4038 // For macro instantiations, just note where the beginning of the macro
4039 // instantiation occurs.
4040 if (cursor.kind == CXCursor_MacroInstantiation) {
4041 Annotated[Loc.int_data] = cursor;
4042 return CXChildVisit_Recurse;
4043 }
4044
Douglas Gregor4419b672010-10-21 06:10:04 +00004045 // Items in the preprocessing record are kept separate from items in
4046 // declarations, so we keep a separate token index.
4047 unsigned SavedTokIdx = TokIdx;
4048 TokIdx = PreprocessingTokIdx;
4049
4050 // Skip tokens up until we catch up to the beginning of the preprocessing
4051 // entry.
4052 while (MoreTokens()) {
4053 const unsigned I = NextToken();
4054 SourceLocation TokLoc = GetTokenLoc(I);
4055 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4056 case RangeBefore:
4057 AdvanceToken();
4058 continue;
4059 case RangeAfter:
4060 case RangeOverlap:
4061 break;
4062 }
4063 break;
4064 }
4065
4066 // Look at all of the tokens within this range.
4067 while (MoreTokens()) {
4068 const unsigned I = NextToken();
4069 SourceLocation TokLoc = GetTokenLoc(I);
4070 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4071 case RangeBefore:
4072 assert(0 && "Infeasible");
4073 case RangeAfter:
4074 break;
4075 case RangeOverlap:
4076 Cursors[I] = cursor;
4077 AdvanceToken();
4078 continue;
4079 }
4080 break;
4081 }
4082
4083 // Save the preprocessing token index; restore the non-preprocessing
4084 // token index.
4085 PreprocessingTokIdx = TokIdx;
4086 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004087 return CXChildVisit_Recurse;
4088 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004089
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004090 if (cursorRange.isInvalid())
4091 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004092
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004093 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4094
Ted Kremeneka333c662010-05-12 05:29:33 +00004095 // Adjust the annotated range based specific declarations.
4096 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4097 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004098 Decl *D = cxcursor::getCursorDecl(cursor);
4099 // Don't visit synthesized ObjC methods, since they have no syntatic
4100 // representation in the source.
4101 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4102 if (MD->isSynthesized())
4103 return CXChildVisit_Continue;
4104 }
4105 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004106 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4107 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004108 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004109 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004110 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004111 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004112 }
4113 }
4114 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004115
Ted Kremenek3f404602010-08-14 01:14:06 +00004116 // If the location of the cursor occurs within a macro instantiation, record
4117 // the spelling location of the cursor in our annotation map. We can then
4118 // paper over the token labelings during a post-processing step to try and
4119 // get cursor mappings for tokens that are the *arguments* of a macro
4120 // instantiation.
4121 if (L.isMacroID()) {
4122 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4123 // Only invalidate the old annotation if it isn't part of a preprocessing
4124 // directive. Here we assume that the default construction of CXCursor
4125 // results in CXCursor.kind being an initialized value (i.e., 0). If
4126 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004127
Ted Kremenek3f404602010-08-14 01:14:06 +00004128 CXCursor &oldC = Annotated[rawEncoding];
4129 if (!clang_isPreprocessing(oldC.kind))
4130 oldC = cursor;
4131 }
4132
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004133 const enum CXCursorKind K = clang_getCursorKind(parent);
4134 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004135 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4136 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004137
4138 while (MoreTokens()) {
4139 const unsigned I = NextToken();
4140 SourceLocation TokLoc = GetTokenLoc(I);
4141 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4142 case RangeBefore:
4143 Cursors[I] = updateC;
4144 AdvanceToken();
4145 continue;
4146 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004147 case RangeOverlap:
4148 break;
4149 }
4150 break;
4151 }
4152
4153 // Visit children to get their cursor information.
4154 const unsigned BeforeChildren = NextToken();
4155 VisitChildren(cursor);
4156 const unsigned AfterChildren = NextToken();
4157
4158 // Adjust 'Last' to the last token within the extent of the cursor.
4159 while (MoreTokens()) {
4160 const unsigned I = NextToken();
4161 SourceLocation TokLoc = GetTokenLoc(I);
4162 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4163 case RangeBefore:
4164 assert(0 && "Infeasible");
4165 case RangeAfter:
4166 break;
4167 case RangeOverlap:
4168 Cursors[I] = updateC;
4169 AdvanceToken();
4170 continue;
4171 }
4172 break;
4173 }
4174 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004175
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004176 // Scan the tokens that are at the beginning of the cursor, but are not
4177 // capture by the child cursors.
4178
4179 // For AST elements within macros, rely on a post-annotate pass to
4180 // to correctly annotate the tokens with cursors. Otherwise we can
4181 // get confusing results of having tokens that map to cursors that really
4182 // are expanded by an instantiation.
4183 if (L.isMacroID())
4184 cursor = clang_getNullCursor();
4185
4186 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4187 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4188 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004189
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004190 Cursors[I] = cursor;
4191 }
4192 // Scan the tokens that are at the end of the cursor, but are not captured
4193 // but the child cursors.
4194 for (unsigned I = AfterChildren; I != Last; ++I)
4195 Cursors[I] = cursor;
4196
4197 TokIdx = Last;
4198 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004199}
4200
Ted Kremenek6db61092010-05-05 00:55:15 +00004201static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4202 CXCursor parent,
4203 CXClientData client_data) {
4204 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4205}
4206
Ted Kremenekab979612010-11-11 08:05:23 +00004207// This gets run a separate thread to avoid stack blowout.
4208static void runAnnotateTokensWorker(void *UserData) {
4209 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4210}
4211
Ted Kremenek6db61092010-05-05 00:55:15 +00004212extern "C" {
4213
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004214void clang_annotateTokens(CXTranslationUnit TU,
4215 CXToken *Tokens, unsigned NumTokens,
4216 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004217
4218 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004219 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004220
Douglas Gregor4419b672010-10-21 06:10:04 +00004221 // Any token we don't specifically annotate will have a NULL cursor.
4222 CXCursor C = clang_getNullCursor();
4223 for (unsigned I = 0; I != NumTokens; ++I)
4224 Cursors[I] = C;
4225
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004226 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004227 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004228 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229
Douglas Gregorbdf60622010-03-05 21:16:25 +00004230 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004231
Douglas Gregor0396f462010-03-19 05:22:59 +00004232 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004233 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004234 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4235 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004236 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4237 clang_getTokenLocation(TU,
4238 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Douglas Gregor0396f462010-03-19 05:22:59 +00004240 // A mapping from the source locations found when re-lexing or traversing the
4241 // region of interest to the corresponding cursors.
4242 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004243
4244 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004245 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004246 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4247 std::pair<FileID, unsigned> BeginLocInfo
4248 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4249 std::pair<FileID, unsigned> EndLocInfo
4250 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004251
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004252 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004253 bool Invalid = false;
4254 if (BeginLocInfo.first == EndLocInfo.first &&
4255 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4256 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004257 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4258 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004259 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004260 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004261 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004262
4263 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004264 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004265 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004266 Token Tok;
4267 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004268
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004269 reprocess:
4270 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4271 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004272 // don't see it while preprocessing these tokens later, but keep track
4273 // of all of the token locations inside this preprocessing directive so
4274 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004275 //
4276 // FIXME: Some simple tests here could identify macro definitions and
4277 // #undefs, to provide specific cursor kinds for those.
4278 std::vector<SourceLocation> Locations;
4279 do {
4280 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004281 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004282 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004283
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004284 using namespace cxcursor;
4285 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004286 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4287 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004288 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004289 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4290 Annotated[Locations[I].getRawEncoding()] = Cursor;
4291 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004292
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004293 if (Tok.isAtStartOfLine())
4294 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004295
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004296 continue;
4297 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004298
Douglas Gregor48072312010-03-18 15:23:44 +00004299 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004300 break;
4301 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004302 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004303
Douglas Gregor0396f462010-03-19 05:22:59 +00004304 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004305 // a specific cursor.
4306 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4307 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004308
4309 // Run the worker within a CrashRecoveryContext.
4310 llvm::CrashRecoveryContext CRC;
4311 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4312 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4313 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004314}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004315} // end: extern "C"
4316
4317//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004318// Operations for querying linkage of a cursor.
4319//===----------------------------------------------------------------------===//
4320
4321extern "C" {
4322CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004323 if (!clang_isDeclaration(cursor.kind))
4324 return CXLinkage_Invalid;
4325
Ted Kremenek16b42592010-03-03 06:36:57 +00004326 Decl *D = cxcursor::getCursorDecl(cursor);
4327 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4328 switch (ND->getLinkage()) {
4329 case NoLinkage: return CXLinkage_NoLinkage;
4330 case InternalLinkage: return CXLinkage_Internal;
4331 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4332 case ExternalLinkage: return CXLinkage_External;
4333 };
4334
4335 return CXLinkage_Invalid;
4336}
4337} // end: extern "C"
4338
4339//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004340// Operations for querying language of a cursor.
4341//===----------------------------------------------------------------------===//
4342
4343static CXLanguageKind getDeclLanguage(const Decl *D) {
4344 switch (D->getKind()) {
4345 default:
4346 break;
4347 case Decl::ImplicitParam:
4348 case Decl::ObjCAtDefsField:
4349 case Decl::ObjCCategory:
4350 case Decl::ObjCCategoryImpl:
4351 case Decl::ObjCClass:
4352 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004353 case Decl::ObjCForwardProtocol:
4354 case Decl::ObjCImplementation:
4355 case Decl::ObjCInterface:
4356 case Decl::ObjCIvar:
4357 case Decl::ObjCMethod:
4358 case Decl::ObjCProperty:
4359 case Decl::ObjCPropertyImpl:
4360 case Decl::ObjCProtocol:
4361 return CXLanguage_ObjC;
4362 case Decl::CXXConstructor:
4363 case Decl::CXXConversion:
4364 case Decl::CXXDestructor:
4365 case Decl::CXXMethod:
4366 case Decl::CXXRecord:
4367 case Decl::ClassTemplate:
4368 case Decl::ClassTemplatePartialSpecialization:
4369 case Decl::ClassTemplateSpecialization:
4370 case Decl::Friend:
4371 case Decl::FriendTemplate:
4372 case Decl::FunctionTemplate:
4373 case Decl::LinkageSpec:
4374 case Decl::Namespace:
4375 case Decl::NamespaceAlias:
4376 case Decl::NonTypeTemplateParm:
4377 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004378 case Decl::TemplateTemplateParm:
4379 case Decl::TemplateTypeParm:
4380 case Decl::UnresolvedUsingTypename:
4381 case Decl::UnresolvedUsingValue:
4382 case Decl::Using:
4383 case Decl::UsingDirective:
4384 case Decl::UsingShadow:
4385 return CXLanguage_CPlusPlus;
4386 }
4387
4388 return CXLanguage_C;
4389}
4390
4391extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004392
4393enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4394 if (clang_isDeclaration(cursor.kind))
4395 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4396 if (D->hasAttr<UnavailableAttr>() ||
4397 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4398 return CXAvailability_Available;
4399
4400 if (D->hasAttr<DeprecatedAttr>())
4401 return CXAvailability_Deprecated;
4402 }
4403
4404 return CXAvailability_Available;
4405}
4406
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004407CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4408 if (clang_isDeclaration(cursor.kind))
4409 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4410
4411 return CXLanguage_Invalid;
4412}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004413
4414CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4415 if (clang_isDeclaration(cursor.kind)) {
4416 if (Decl *D = getCursorDecl(cursor)) {
4417 DeclContext *DC = D->getDeclContext();
4418 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4419 }
4420 }
4421
4422 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4423 if (Decl *D = getCursorDecl(cursor))
4424 return MakeCXCursor(D, getCursorASTUnit(cursor));
4425 }
4426
4427 return clang_getNullCursor();
4428}
4429
4430CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4431 if (clang_isDeclaration(cursor.kind)) {
4432 if (Decl *D = getCursorDecl(cursor)) {
4433 DeclContext *DC = D->getLexicalDeclContext();
4434 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4435 }
4436 }
4437
4438 // FIXME: Note that we can't easily compute the lexical context of a
4439 // statement or expression, so we return nothing.
4440 return clang_getNullCursor();
4441}
4442
Douglas Gregor9f592342010-10-01 20:25:15 +00004443static void CollectOverriddenMethods(DeclContext *Ctx,
4444 ObjCMethodDecl *Method,
4445 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4446 if (!Ctx)
4447 return;
4448
4449 // If we have a class or category implementation, jump straight to the
4450 // interface.
4451 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4452 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4453
4454 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4455 if (!Container)
4456 return;
4457
4458 // Check whether we have a matching method at this level.
4459 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4460 Method->isInstanceMethod()))
4461 if (Method != Overridden) {
4462 // We found an override at this level; there is no need to look
4463 // into other protocols or categories.
4464 Methods.push_back(Overridden);
4465 return;
4466 }
4467
4468 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4469 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4470 PEnd = Protocol->protocol_end();
4471 P != PEnd; ++P)
4472 CollectOverriddenMethods(*P, Method, Methods);
4473 }
4474
4475 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4476 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4477 PEnd = Category->protocol_end();
4478 P != PEnd; ++P)
4479 CollectOverriddenMethods(*P, Method, Methods);
4480 }
4481
4482 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4483 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4484 PEnd = Interface->protocol_end();
4485 P != PEnd; ++P)
4486 CollectOverriddenMethods(*P, Method, Methods);
4487
4488 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4489 Category; Category = Category->getNextClassCategory())
4490 CollectOverriddenMethods(Category, Method, Methods);
4491
4492 // We only look into the superclass if we haven't found anything yet.
4493 if (Methods.empty())
4494 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4495 return CollectOverriddenMethods(Super, Method, Methods);
4496 }
4497}
4498
4499void clang_getOverriddenCursors(CXCursor cursor,
4500 CXCursor **overridden,
4501 unsigned *num_overridden) {
4502 if (overridden)
4503 *overridden = 0;
4504 if (num_overridden)
4505 *num_overridden = 0;
4506 if (!overridden || !num_overridden)
4507 return;
4508
4509 if (!clang_isDeclaration(cursor.kind))
4510 return;
4511
4512 Decl *D = getCursorDecl(cursor);
4513 if (!D)
4514 return;
4515
4516 // Handle C++ member functions.
4517 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4518 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4519 *num_overridden = CXXMethod->size_overridden_methods();
4520 if (!*num_overridden)
4521 return;
4522
4523 *overridden = new CXCursor [*num_overridden];
4524 unsigned I = 0;
4525 for (CXXMethodDecl::method_iterator
4526 M = CXXMethod->begin_overridden_methods(),
4527 MEnd = CXXMethod->end_overridden_methods();
4528 M != MEnd; (void)++M, ++I)
4529 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4530 return;
4531 }
4532
4533 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4534 if (!Method)
4535 return;
4536
4537 // Handle Objective-C methods.
4538 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4539 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4540
4541 if (Methods.empty())
4542 return;
4543
4544 *num_overridden = Methods.size();
4545 *overridden = new CXCursor [Methods.size()];
4546 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4547 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4548}
4549
4550void clang_disposeOverriddenCursors(CXCursor *overridden) {
4551 delete [] overridden;
4552}
4553
Douglas Gregorecdcb882010-10-20 22:00:55 +00004554CXFile clang_getIncludedFile(CXCursor cursor) {
4555 if (cursor.kind != CXCursor_InclusionDirective)
4556 return 0;
4557
4558 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4559 return (void *)ID->getFile();
4560}
4561
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004562} // end: extern "C"
4563
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004564
4565//===----------------------------------------------------------------------===//
4566// C++ AST instrospection.
4567//===----------------------------------------------------------------------===//
4568
4569extern "C" {
4570unsigned clang_CXXMethod_isStatic(CXCursor C) {
4571 if (!clang_isDeclaration(C.kind))
4572 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004573
4574 CXXMethodDecl *Method = 0;
4575 Decl *D = cxcursor::getCursorDecl(C);
4576 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4577 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4578 else
4579 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4580 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004581}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004582
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004583} // end: extern "C"
4584
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004585//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004586// Attribute introspection.
4587//===----------------------------------------------------------------------===//
4588
4589extern "C" {
4590CXType clang_getIBOutletCollectionType(CXCursor C) {
4591 if (C.kind != CXCursor_IBOutletCollectionAttr)
4592 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4593
4594 IBOutletCollectionAttr *A =
4595 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4596
4597 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4598}
4599} // end: extern "C"
4600
4601//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004602// CXString Operations.
4603//===----------------------------------------------------------------------===//
4604
4605extern "C" {
4606const char *clang_getCString(CXString string) {
4607 return string.Spelling;
4608}
4609
4610void clang_disposeString(CXString string) {
4611 if (string.MustFreeString && string.Spelling)
4612 free((void*)string.Spelling);
4613}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004614
Ted Kremenekfb480492010-01-13 21:46:36 +00004615} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004616
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004617namespace clang { namespace cxstring {
4618CXString createCXString(const char *String, bool DupString){
4619 CXString Str;
4620 if (DupString) {
4621 Str.Spelling = strdup(String);
4622 Str.MustFreeString = 1;
4623 } else {
4624 Str.Spelling = String;
4625 Str.MustFreeString = 0;
4626 }
4627 return Str;
4628}
4629
4630CXString createCXString(llvm::StringRef String, bool DupString) {
4631 CXString Result;
4632 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4633 char *Spelling = (char *)malloc(String.size() + 1);
4634 memmove(Spelling, String.data(), String.size());
4635 Spelling[String.size()] = 0;
4636 Result.Spelling = Spelling;
4637 Result.MustFreeString = 1;
4638 } else {
4639 Result.Spelling = String.data();
4640 Result.MustFreeString = 0;
4641 }
4642 return Result;
4643}
4644}}
4645
Ted Kremenek04bb7162010-01-22 22:44:15 +00004646//===----------------------------------------------------------------------===//
4647// Misc. utility functions.
4648//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004649
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004650/// Default to using an 8 MB stack size on "safety" threads.
4651static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004652
4653namespace clang {
4654
4655bool RunSafely(llvm::CrashRecoveryContext &CRC,
4656 void (*Fn)(void*), void *UserData) {
4657 if (unsigned Size = GetSafetyThreadStackSize())
4658 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4659 return CRC.RunSafely(Fn, UserData);
4660}
4661
4662unsigned GetSafetyThreadStackSize() {
4663 return SafetyStackThreadSize;
4664}
4665
4666void SetSafetyThreadStackSize(unsigned Value) {
4667 SafetyStackThreadSize = Value;
4668}
4669
4670}
4671
Ted Kremenek04bb7162010-01-22 22:44:15 +00004672extern "C" {
4673
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004674CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004675 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004676}
4677
4678} // end: extern "C"