blob: b903832c37ad778fda94a051004848ee910336c0 [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
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000315 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor81d34662010-04-20 15:39:42 +0000316 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000317 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000318 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000319 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000320 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
321 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000322 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000323 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000324 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000325 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000326 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
327 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000328 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000329 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000330 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000331 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000332 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000333 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000334
335#define DATA_RECURSIVE_VISIT(NAME)\
336bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
337 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000338 DATA_RECURSIVE_VISIT(CompoundLiteralExpr)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000339 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000340 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000341 DATA_RECURSIVE_VISIT(DeclRefExpr)
Ted Kremenek035dc412010-11-13 00:36:50 +0000342 DATA_RECURSIVE_VISIT(DeclStmt)
Ted Kremenek99394242010-11-12 22:24:57 +0000343 DATA_RECURSIVE_VISIT(ExplicitCastExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000344 DATA_RECURSIVE_VISIT(DoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000345 DATA_RECURSIVE_VISIT(IfStmt)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000346 DATA_RECURSIVE_VISIT(InitListExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000347 DATA_RECURSIVE_VISIT(ForStmt)
Ted Kremenek1876bf62010-11-13 00:58:15 +0000348 DATA_RECURSIVE_VISIT(GotoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000349 DATA_RECURSIVE_VISIT(MemberExpr)
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
1454
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001455bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1456 return Visit(B->getBlockDecl());
1457}
1458
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001459bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001460 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001461 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1462 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001463
1464 // Visit the components of the offsetof expression.
1465 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1466 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1467 const OffsetOfNode &Node = E->getComponent(I);
1468 switch (Node.getKind()) {
1469 case OffsetOfNode::Array:
1470 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1471 StmtParent, TU)))
1472 return true;
1473 break;
1474
1475 case OffsetOfNode::Field:
1476 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1477 TU)))
1478 return true;
1479 break;
1480
1481 case OffsetOfNode::Identifier:
1482 case OffsetOfNode::Base:
1483 continue;
1484 }
1485 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001486
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001487 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001488}
1489
Douglas Gregor336fd812010-01-23 00:40:08 +00001490bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1491 if (E->isArgumentType()) {
1492 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1493 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001494
Douglas Gregor336fd812010-01-23 00:40:08 +00001495 return false;
1496 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001497
Douglas Gregor336fd812010-01-23 00:40:08 +00001498 return VisitExpr(E);
1499}
1500
Douglas Gregor36897b02010-09-10 00:22:18 +00001501bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1502 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1503}
1504
Douglas Gregor648220e2010-08-10 15:02:34 +00001505bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1506 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1507 Visit(E->getArgTInfo2()->getTypeLoc());
1508}
1509
1510bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1511 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1512 return true;
1513
1514 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1515}
1516
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001517bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1518 // Visit the designators.
1519 typedef DesignatedInitExpr::Designator Designator;
1520 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1521 DEnd = E->designators_end();
1522 D != DEnd; ++D) {
1523 if (D->isFieldDesignator()) {
1524 if (FieldDecl *Field = D->getField())
1525 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1526 return true;
1527
1528 continue;
1529 }
1530
1531 if (D->isArrayDesignator()) {
1532 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1533 return true;
1534
1535 continue;
1536 }
1537
1538 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1539 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1540 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1541 return true;
1542 }
1543
1544 // Visit the initializer value itself.
1545 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1546}
1547
Douglas Gregor94802292010-09-02 21:20:16 +00001548bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1549 if (E->isTypeOperand()) {
1550 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1551 return Visit(TSInfo->getTypeLoc());
1552
1553 return false;
1554 }
1555
1556 return VisitExpr(E);
1557}
1558
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001559bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1560 if (E->isTypeOperand()) {
1561 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1562 return Visit(TSInfo->getTypeLoc());
1563
1564 return false;
1565 }
1566
1567 return VisitExpr(E);
1568}
1569
Douglas Gregorab6677e2010-09-08 00:15:04 +00001570bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1571 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001572 if (Visit(TSInfo->getTypeLoc()))
1573 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001574
1575 return VisitExpr(E);
1576}
1577
1578bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1579 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1580 return Visit(TSInfo->getTypeLoc());
1581
1582 return false;
1583}
1584
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001585bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1586 // Visit placement arguments.
1587 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1588 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1589 return true;
1590
1591 // Visit the allocated type.
1592 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1593 if (Visit(TSInfo->getTypeLoc()))
1594 return true;
1595
1596 // Visit the array size, if any.
1597 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1598 return true;
1599
1600 // Visit the initializer or constructor arguments.
1601 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1602 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1603 return true;
1604
1605 return false;
1606}
1607
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001608bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1609 // Visit base expression.
1610 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1611 return true;
1612
1613 // Visit the nested-name-specifier.
1614 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1615 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1616 return true;
1617
1618 // Visit the scope type that looks disturbingly like the nested-name-specifier
1619 // but isn't.
1620 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1621 if (Visit(TSInfo->getTypeLoc()))
1622 return true;
1623
1624 // Visit the name of the type being destroyed.
1625 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1626 if (Visit(TSInfo->getTypeLoc()))
1627 return true;
1628
1629 return false;
1630}
1631
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001632bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1633 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1634}
1635
Douglas Gregorbfebed22010-09-03 17:24:10 +00001636bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1637 DependentScopeDeclRefExpr *E) {
1638 // Visit the nested-name-specifier.
1639 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1640 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1641 return true;
1642
1643 // Visit the declaration name.
1644 if (VisitDeclarationNameInfo(E->getNameInfo()))
1645 return true;
1646
1647 // Visit the explicitly-specified template arguments.
1648 if (const ExplicitTemplateArgumentList *ArgList
1649 = E->getOptionalExplicitTemplateArgs()) {
1650 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1651 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1652 Arg != ArgEnd; ++Arg) {
1653 if (VisitTemplateArgumentLoc(*Arg))
1654 return true;
1655 }
1656 }
1657
1658 return false;
1659}
1660
Douglas Gregorab6677e2010-09-08 00:15:04 +00001661bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1662 CXXUnresolvedConstructExpr *E) {
1663 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1664 if (Visit(TSInfo->getTypeLoc()))
1665 return true;
1666
1667 return VisitExpr(E);
1668}
1669
Douglas Gregor25d63622010-09-03 17:35:34 +00001670bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1671 CXXDependentScopeMemberExpr *E) {
1672 // Visit the base expression, if there is one.
1673 if (!E->isImplicitAccess() &&
1674 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1675 return true;
1676
1677 // Visit the nested-name-specifier.
1678 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1679 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1680 return true;
1681
1682 // Visit the declaration name.
1683 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1684 return true;
1685
1686 // Visit the explicitly-specified template arguments.
1687 if (const ExplicitTemplateArgumentList *ArgList
1688 = E->getOptionalExplicitTemplateArgs()) {
1689 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1690 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1691 Arg != ArgEnd; ++Arg) {
1692 if (VisitTemplateArgumentLoc(*Arg))
1693 return true;
1694 }
1695 }
1696
1697 return false;
1698}
1699
Douglas Gregor81d34662010-04-20 15:39:42 +00001700bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1701 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1702}
1703
1704
Ted Kremenek09dfa372010-02-18 05:46:33 +00001705bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001706 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1707 i != e; ++i)
1708 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001709 return true;
1710
1711 return false;
1712}
1713
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001714//===----------------------------------------------------------------------===//
1715// Data-recursive visitor methods.
1716//===----------------------------------------------------------------------===//
1717
Ted Kremenek28a71942010-11-13 00:36:47 +00001718namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001719#define DEF_JOB(NAME, DATA, KIND)\
1720class NAME : public VisitorJob {\
1721public:\
1722 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1723 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1724 DATA *get() const { return static_cast<DATA*>(dataA); }\
1725};
1726
1727DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1728DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001729DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001730DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1731#undef DEF_JOB
1732
1733class DeclVisit : public VisitorJob {
1734public:
1735 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1736 VisitorJob(parent, VisitorJob::DeclVisitKind,
1737 d, isFirst ? (void*) 1 : (void*) 0) {}
1738 static bool classof(const VisitorJob *VJ) {
1739 return VJ->getKind () == DeclVisitKind;
1740 }
1741 Decl *get() { return static_cast<Decl*>(dataA);}
1742 bool isFirst() const { return dataB ? true : false; }
1743};
1744
1745class TypeLocVisit : public VisitorJob {
1746public:
1747 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1748 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1749 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1750
1751 static bool classof(const VisitorJob *VJ) {
1752 return VJ->getKind() == TypeLocVisitKind;
1753 }
1754
1755 TypeLoc get() {
1756 QualType T = QualType::getFromOpaquePtr(dataA);
1757 return TypeLoc(T, dataB);
1758 }
1759};
1760
Ted Kremenek28a71942010-11-13 00:36:47 +00001761class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1762 VisitorWorkList &WL;
1763 CXCursor Parent;
1764public:
1765 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1766 : WL(wl), Parent(parent) {}
1767
1768 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1769 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001770 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001771 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001772 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1773 void VisitForStmt(ForStmt *FS);
1774 void VisitIfStmt(IfStmt *If);
1775 void VisitInitListExpr(InitListExpr *IE);
1776 void VisitMemberExpr(MemberExpr *M);
1777 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1778 void VisitOverloadExpr(OverloadExpr *E);
1779 void VisitStmt(Stmt *S);
1780 void VisitSwitchStmt(SwitchStmt *S);
1781 void VisitWhileStmt(WhileStmt *W);
1782 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1783
1784private:
1785 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001786 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001787 void AddTypeLoc(TypeSourceInfo *TI);
1788 void EnqueueChildren(Stmt *S);
1789};
1790} // end anonyous namespace
1791
1792void EnqueueVisitor::AddStmt(Stmt *S) {
1793 if (S)
1794 WL.push_back(StmtVisit(S, Parent));
1795}
Ted Kremenek035dc412010-11-13 00:36:50 +00001796void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001797 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001798 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001799}
1800void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1801 if (TI)
1802 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1803 }
1804void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001805 unsigned size = WL.size();
1806 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1807 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001808 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001809 }
1810 if (size == WL.size())
1811 return;
1812 // Now reverse the entries we just added. This will match the DFS
1813 // ordering performed by the worklist.
1814 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1815 std::reverse(I, E);
1816}
Ted Kremenek28a71942010-11-13 00:36:47 +00001817void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1818 EnqueueChildren(E);
1819 AddTypeLoc(E->getTypeSourceInfo());
1820}
1821void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1822 // Note that we enqueue things in reverse order so that
1823 // they are visited correctly by the DFS.
1824 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
1825 AddStmt(CE->getArg(N-I));
1826 AddStmt(CE->getCallee());
1827 AddStmt(CE->getArg(0));
1828}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001829void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1830 WL.push_back(DeclRefExprParts(DR, Parent));
1831}
Ted Kremenek035dc412010-11-13 00:36:50 +00001832void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1833 unsigned size = WL.size();
1834 bool isFirst = true;
1835 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1836 D != DEnd; ++D) {
1837 AddDecl(*D, isFirst);
1838 isFirst = false;
1839 }
1840 if (size == WL.size())
1841 return;
1842 // Now reverse the entries we just added. This will match the DFS
1843 // ordering performed by the worklist.
1844 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1845 std::reverse(I, E);
1846}
Ted Kremenek28a71942010-11-13 00:36:47 +00001847void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1848 EnqueueChildren(E);
1849 AddTypeLoc(E->getTypeInfoAsWritten());
1850}
1851void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1852 AddStmt(FS->getBody());
1853 AddStmt(FS->getInc());
1854 AddStmt(FS->getCond());
1855 AddDecl(FS->getConditionVariable());
1856 AddStmt(FS->getInit());
1857}
1858void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1859 AddStmt(If->getElse());
1860 AddStmt(If->getThen());
1861 AddStmt(If->getCond());
1862 AddDecl(If->getConditionVariable());
1863}
1864void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1865 // We care about the syntactic form of the initializer list, only.
1866 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1867 IE = Syntactic;
1868 EnqueueChildren(IE);
1869}
1870void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1871 WL.push_back(MemberExprParts(M, Parent));
1872 AddStmt(M->getBase());
1873}
1874void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1875 EnqueueChildren(M);
1876 AddTypeLoc(M->getClassReceiverTypeInfo());
1877}
1878void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001879 WL.push_back(OverloadExprParts(E, Parent));
1880}
Ted Kremenek28a71942010-11-13 00:36:47 +00001881void EnqueueVisitor::VisitStmt(Stmt *S) {
1882 EnqueueChildren(S);
1883}
1884void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1885 AddStmt(S->getBody());
1886 AddStmt(S->getCond());
1887 AddDecl(S->getConditionVariable());
1888}
1889void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1890 AddStmt(W->getBody());
1891 AddStmt(W->getCond());
1892 AddDecl(W->getConditionVariable());
1893}
1894void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1895 VisitOverloadExpr(U);
1896 if (!U->isImplicitAccess())
1897 AddStmt(U->getBase());
1898}
Ted Kremenek60458782010-11-12 21:34:16 +00001899
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001900void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001901 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001902}
1903
1904bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1905 if (RegionOfInterest.isValid()) {
1906 SourceRange Range = getRawCursorExtent(C);
1907 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1908 return false;
1909 }
1910 return true;
1911}
1912
1913bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1914 while (!WL.empty()) {
1915 // Dequeue the worklist item.
1916 VisitorJob LI = WL.back(); WL.pop_back();
1917
1918 // Set the Parent field, then back to its old value once we're done.
1919 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1920
1921 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001922 case VisitorJob::DeclVisitKind: {
1923 Decl *D = cast<DeclVisit>(LI).get();
1924 if (!D)
1925 continue;
1926
1927 // For now, perform default visitation for Decls.
Ted Kremenek035dc412010-11-13 00:36:50 +00001928 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(LI).isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001929 return true;
1930
1931 continue;
1932 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001933 case VisitorJob::TypeLocVisitKind: {
1934 // Perform default visitation for TypeLocs.
1935 if (Visit(cast<TypeLocVisit>(LI).get()))
1936 return true;
1937 continue;
1938 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001939 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001940 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001941 if (!S)
1942 continue;
1943
Ted Kremenekf1107452010-11-12 18:26:56 +00001944 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001945 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1946
1947 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001948 case Stmt::GotoStmtClass: {
1949 GotoStmt *GS = cast<GotoStmt>(S);
1950 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1951 GS->getLabelLoc(), TU))) {
1952 return true;
1953 }
1954 continue;
1955 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001956 default: {
Ted Kremenek99394242010-11-12 22:24:57 +00001957 // FIXME: this entire switch stmt will eventually
1958 // go away.
1959 if (!isa<ExplicitCastExpr>(S)) {
1960 // Perform default visitation for other cases.
1961 if (Visit(Cursor))
1962 return true;
1963 continue;
1964 }
1965 // Fall-through.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001966 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001967 case Stmt::BinaryOperatorClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001968 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001969 case Stmt::CaseStmtClass:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001970 case Stmt::CompoundLiteralExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001971 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001972 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001973 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001974 case Stmt::DefaultStmtClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001975 case Stmt::DoStmtClass:
1976 case Stmt::ForStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001977 case Stmt::IfStmtClass:
Ted Kremeneka6b70432010-11-12 21:34:09 +00001978 case Stmt::InitListExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001979 case Stmt::MemberExprClass:
Ted Kremenekc373e3c2010-11-12 22:24:55 +00001980 case Stmt::ObjCMessageExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001981 case Stmt::ParenExprClass:
1982 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00001983 case Stmt::UnaryOperatorClass:
Ted Kremenek60458782010-11-12 21:34:16 +00001984 case Stmt::UnresolvedLookupExprClass:
1985 case Stmt::UnresolvedMemberExprClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001986 case Stmt::WhileStmtClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001987 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001988 if (!IsInRegionOfInterest(Cursor))
1989 continue;
1990 switch (Visitor(Cursor, Parent, ClientData)) {
1991 case CXChildVisit_Break:
1992 return true;
1993 case CXChildVisit_Continue:
1994 break;
1995 case CXChildVisit_Recurse:
1996 EnqueueWorkList(WL, S);
1997 break;
1998 }
1999 }
2000 }
2001 continue;
2002 }
2003 case VisitorJob::MemberExprPartsKind: {
2004 // Handle the other pieces in the MemberExpr besides the base.
2005 MemberExpr *M = cast<MemberExprParts>(LI).get();
2006
2007 // Visit the nested-name-specifier
2008 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2009 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2010 return true;
2011
2012 // Visit the declaration name.
2013 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2014 return true;
2015
2016 // Visit the explicitly-specified template arguments, if any.
2017 if (M->hasExplicitTemplateArgs()) {
2018 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2019 *ArgEnd = Arg + M->getNumTemplateArgs();
2020 Arg != ArgEnd; ++Arg) {
2021 if (VisitTemplateArgumentLoc(*Arg))
2022 return true;
2023 }
2024 }
2025 continue;
2026 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002027 case VisitorJob::DeclRefExprPartsKind: {
2028 DeclRefExpr *DR = cast<DeclRefExprParts>(LI).get();
2029 // Visit nested-name-specifier, if present.
2030 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2031 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2032 return true;
2033 // Visit declaration name.
2034 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2035 return true;
2036 // Visit explicitly-specified template arguments.
2037 if (DR->hasExplicitTemplateArgs()) {
2038 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2039 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2040 *ArgEnd = Arg + Args.NumTemplateArgs;
2041 Arg != ArgEnd; ++Arg)
2042 if (VisitTemplateArgumentLoc(*Arg))
2043 return true;
2044 }
2045 continue;
2046 }
Ted Kremenek60458782010-11-12 21:34:16 +00002047 case VisitorJob::OverloadExprPartsKind: {
2048 OverloadExpr *O = cast<OverloadExprParts>(LI).get();
2049 // Visit the nested-name-specifier.
2050 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2051 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2052 return true;
2053 // Visit the declaration name.
2054 if (VisitDeclarationNameInfo(O->getNameInfo()))
2055 return true;
2056 // Visit the overloaded declaration reference.
2057 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2058 return true;
2059 // Visit the explicitly-specified template arguments.
2060 if (const ExplicitTemplateArgumentList *ArgList
2061 = O->getOptionalExplicitTemplateArgs()) {
2062 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2063 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2064 Arg != ArgEnd; ++Arg) {
2065 if (VisitTemplateArgumentLoc(*Arg))
2066 return true;
2067 }
2068 }
2069 continue;
2070 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002071 }
2072 }
2073 return false;
2074}
2075
2076bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2077 VisitorWorkList WL;
2078 EnqueueWorkList(WL, S);
2079 return RunVisitorWorkList(WL);
2080}
2081
2082//===----------------------------------------------------------------------===//
2083// Misc. API hooks.
2084//===----------------------------------------------------------------------===//
2085
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002086static llvm::sys::Mutex EnableMultithreadingMutex;
2087static bool EnabledMultithreading;
2088
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002089extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002090CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2091 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002092 // Disable pretty stack trace functionality, which will otherwise be a very
2093 // poor citizen of the world and set up all sorts of signal handlers.
2094 llvm::DisablePrettyStackTrace = true;
2095
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002096 // We use crash recovery to make some of our APIs more reliable, implicitly
2097 // enable it.
2098 llvm::CrashRecoveryContext::Enable();
2099
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002100 // Enable support for multithreading in LLVM.
2101 {
2102 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2103 if (!EnabledMultithreading) {
2104 llvm::llvm_start_multithreaded();
2105 EnabledMultithreading = true;
2106 }
2107 }
2108
Douglas Gregora030b7c2010-01-22 20:35:53 +00002109 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002110 if (excludeDeclarationsFromPCH)
2111 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002112 if (displayDiagnostics)
2113 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002114 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002115}
2116
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002117void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002118 if (CIdx)
2119 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002120}
2121
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002122CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002123 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002124 if (!CIdx)
2125 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002126
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002127 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002128 FileSystemOptions FileSystemOpts;
2129 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002130
Douglas Gregor28019772010-04-05 23:52:57 +00002131 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002132 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002133 CXXIdx->getOnlyLocalDecls(),
2134 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002135}
2136
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002137unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002138 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002139 CXTranslationUnit_CacheCompletionResults |
2140 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002141}
2142
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002143CXTranslationUnit
2144clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2145 const char *source_filename,
2146 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002147 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002148 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002149 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002150 return clang_parseTranslationUnit(CIdx, source_filename,
2151 command_line_args, num_command_line_args,
2152 unsaved_files, num_unsaved_files,
2153 CXTranslationUnit_DetailedPreprocessingRecord);
2154}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002155
2156struct ParseTranslationUnitInfo {
2157 CXIndex CIdx;
2158 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002159 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002160 int num_command_line_args;
2161 struct CXUnsavedFile *unsaved_files;
2162 unsigned num_unsaved_files;
2163 unsigned options;
2164 CXTranslationUnit result;
2165};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002166static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002167 ParseTranslationUnitInfo *PTUI =
2168 static_cast<ParseTranslationUnitInfo*>(UserData);
2169 CXIndex CIdx = PTUI->CIdx;
2170 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002171 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002172 int num_command_line_args = PTUI->num_command_line_args;
2173 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2174 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2175 unsigned options = PTUI->options;
2176 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002177
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002178 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002179 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002180
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002181 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2182
Douglas Gregor44c181a2010-07-23 00:33:23 +00002183 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002184 bool CompleteTranslationUnit
2185 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002186 bool CacheCodeCompetionResults
2187 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002188 bool CXXPrecompilePreamble
2189 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2190 bool CXXChainedPCH
2191 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002192
Douglas Gregor5352ac02010-01-28 00:27:43 +00002193 // Configure the diagnostics.
2194 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002195 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2196 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002197
Douglas Gregor4db64a42010-01-23 00:14:00 +00002198 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2199 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002200 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002201 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002202 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002203 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2204 Buffer));
2205 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002206
Douglas Gregorb10daed2010-10-11 16:52:23 +00002207 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002208
Ted Kremenek139ba862009-10-22 00:03:57 +00002209 // The 'source_filename' argument is optional. If the caller does not
2210 // specify it then it is assumed that the source file is specified
2211 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002212 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002213 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002214
2215 // Since the Clang C library is primarily used by batch tools dealing with
2216 // (often very broken) source code, where spell-checking can have a
2217 // significant negative impact on performance (particularly when
2218 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002219 // Only do this if we haven't found a spell-checking-related argument.
2220 bool FoundSpellCheckingArgument = false;
2221 for (int I = 0; I != num_command_line_args; ++I) {
2222 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2223 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2224 FoundSpellCheckingArgument = true;
2225 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002226 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002227 }
2228 if (!FoundSpellCheckingArgument)
2229 Args.push_back("-fno-spell-checking");
2230
2231 Args.insert(Args.end(), command_line_args,
2232 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002233
Douglas Gregor44c181a2010-07-23 00:33:23 +00002234 // Do we need the detailed preprocessing record?
2235 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002236 Args.push_back("-Xclang");
2237 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002238 }
2239
Douglas Gregorb10daed2010-10-11 16:52:23 +00002240 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002241 llvm::OwningPtr<ASTUnit> Unit(
2242 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2243 Diags,
2244 CXXIdx->getClangResourcesPath(),
2245 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002246 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002247 RemappedFiles.data(),
2248 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002249 PrecompilePreamble,
2250 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002251 CacheCodeCompetionResults,
2252 CXXPrecompilePreamble,
2253 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002254
Douglas Gregorb10daed2010-10-11 16:52:23 +00002255 if (NumErrors != Diags->getNumErrors()) {
2256 // Make sure to check that 'Unit' is non-NULL.
2257 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2258 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2259 DEnd = Unit->stored_diag_end();
2260 D != DEnd; ++D) {
2261 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2262 CXString Msg = clang_formatDiagnostic(&Diag,
2263 clang_defaultDiagnosticDisplayOptions());
2264 fprintf(stderr, "%s\n", clang_getCString(Msg));
2265 clang_disposeString(Msg);
2266 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002267#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002268 // On Windows, force a flush, since there may be multiple copies of
2269 // stderr and stdout in the file system, all with different buffers
2270 // but writing to the same device.
2271 fflush(stderr);
2272#endif
2273 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002274 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002275
Douglas Gregorb10daed2010-10-11 16:52:23 +00002276 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002277}
2278CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2279 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002280 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002281 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002282 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002283 unsigned num_unsaved_files,
2284 unsigned options) {
2285 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002286 num_command_line_args, unsaved_files,
2287 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002288 llvm::CrashRecoveryContext CRC;
2289
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002290 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002291 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2292 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2293 fprintf(stderr, " 'command_line_args' : [");
2294 for (int i = 0; i != num_command_line_args; ++i) {
2295 if (i)
2296 fprintf(stderr, ", ");
2297 fprintf(stderr, "'%s'", command_line_args[i]);
2298 }
2299 fprintf(stderr, "],\n");
2300 fprintf(stderr, " 'unsaved_files' : [");
2301 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2302 if (i)
2303 fprintf(stderr, ", ");
2304 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2305 unsaved_files[i].Length);
2306 }
2307 fprintf(stderr, "],\n");
2308 fprintf(stderr, " 'options' : %d,\n", options);
2309 fprintf(stderr, "}\n");
2310
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002311 return 0;
2312 }
2313
2314 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002315}
2316
Douglas Gregor19998442010-08-13 15:35:05 +00002317unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2318 return CXSaveTranslationUnit_None;
2319}
2320
2321int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2322 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002323 if (!TU)
2324 return 1;
2325
2326 return static_cast<ASTUnit *>(TU)->Save(FileName);
2327}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002328
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002329void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002330 if (CTUnit) {
2331 // If the translation unit has been marked as unsafe to free, just discard
2332 // it.
2333 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2334 return;
2335
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002336 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002337 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002338}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002339
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002340unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2341 return CXReparse_None;
2342}
2343
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002344struct ReparseTranslationUnitInfo {
2345 CXTranslationUnit TU;
2346 unsigned num_unsaved_files;
2347 struct CXUnsavedFile *unsaved_files;
2348 unsigned options;
2349 int result;
2350};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002351
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002352static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002353 ReparseTranslationUnitInfo *RTUI =
2354 static_cast<ReparseTranslationUnitInfo*>(UserData);
2355 CXTranslationUnit TU = RTUI->TU;
2356 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2357 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2358 unsigned options = RTUI->options;
2359 (void) options;
2360 RTUI->result = 1;
2361
Douglas Gregorabc563f2010-07-19 21:46:24 +00002362 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002363 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002364
2365 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2366 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002367
2368 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2369 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2370 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2371 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002372 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002373 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2374 Buffer));
2375 }
2376
Douglas Gregor593b0c12010-09-23 18:47:53 +00002377 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2378 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002379}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002380
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002381int clang_reparseTranslationUnit(CXTranslationUnit TU,
2382 unsigned num_unsaved_files,
2383 struct CXUnsavedFile *unsaved_files,
2384 unsigned options) {
2385 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2386 options, 0 };
2387 llvm::CrashRecoveryContext CRC;
2388
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002389 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002390 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002391 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2392 return 1;
2393 }
2394
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002395
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002396 return RTUI.result;
2397}
2398
Douglas Gregordf95a132010-08-09 20:45:32 +00002399
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002400CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002401 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002402 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002403
Steve Naroff77accc12009-09-03 18:19:54 +00002404 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002405 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002406}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002407
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002408CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002409 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002410 return Result;
2411}
2412
Ted Kremenekfb480492010-01-13 21:46:36 +00002413} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002414
Ted Kremenekfb480492010-01-13 21:46:36 +00002415//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002416// CXSourceLocation and CXSourceRange Operations.
2417//===----------------------------------------------------------------------===//
2418
Douglas Gregorb9790342010-01-22 21:44:22 +00002419extern "C" {
2420CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002421 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002422 return Result;
2423}
2424
2425unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002426 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2427 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2428 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002429}
2430
2431CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2432 CXFile file,
2433 unsigned line,
2434 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002435 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002436 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002437
Douglas Gregorb9790342010-01-22 21:44:22 +00002438 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2439 SourceLocation SLoc
2440 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002442 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002443 if (SLoc.isInvalid()) return clang_getNullLocation();
2444
2445 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2446}
2447
2448CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2449 CXFile file,
2450 unsigned offset) {
2451 if (!tu || !file)
2452 return clang_getNullLocation();
2453
2454 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2455 SourceLocation Start
2456 = CXXUnit->getSourceManager().getLocation(
2457 static_cast<const FileEntry *>(file),
2458 1, 1);
2459 if (Start.isInvalid()) return clang_getNullLocation();
2460
2461 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2462
2463 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002464
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002465 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002466}
2467
Douglas Gregor5352ac02010-01-28 00:27:43 +00002468CXSourceRange clang_getNullRange() {
2469 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2470 return Result;
2471}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002472
Douglas Gregor5352ac02010-01-28 00:27:43 +00002473CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2474 if (begin.ptr_data[0] != end.ptr_data[0] ||
2475 begin.ptr_data[1] != end.ptr_data[1])
2476 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002477
2478 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002479 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002480 return Result;
2481}
2482
Douglas Gregor46766dc2010-01-26 19:19:08 +00002483void clang_getInstantiationLocation(CXSourceLocation location,
2484 CXFile *file,
2485 unsigned *line,
2486 unsigned *column,
2487 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002488 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2489
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002490 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002491 if (file)
2492 *file = 0;
2493 if (line)
2494 *line = 0;
2495 if (column)
2496 *column = 0;
2497 if (offset)
2498 *offset = 0;
2499 return;
2500 }
2501
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002502 const SourceManager &SM =
2503 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002504 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002505
2506 if (file)
2507 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2508 if (line)
2509 *line = SM.getInstantiationLineNumber(InstLoc);
2510 if (column)
2511 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002512 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002513 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002514}
2515
Douglas Gregora9b06d42010-11-09 06:24:54 +00002516void clang_getSpellingLocation(CXSourceLocation location,
2517 CXFile *file,
2518 unsigned *line,
2519 unsigned *column,
2520 unsigned *offset) {
2521 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2522
2523 if (!location.ptr_data[0] || Loc.isInvalid()) {
2524 if (file)
2525 *file = 0;
2526 if (line)
2527 *line = 0;
2528 if (column)
2529 *column = 0;
2530 if (offset)
2531 *offset = 0;
2532 return;
2533 }
2534
2535 const SourceManager &SM =
2536 *static_cast<const SourceManager*>(location.ptr_data[0]);
2537 SourceLocation SpellLoc = Loc;
2538 if (SpellLoc.isMacroID()) {
2539 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2540 if (SimpleSpellingLoc.isFileID() &&
2541 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2542 SpellLoc = SimpleSpellingLoc;
2543 else
2544 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2545 }
2546
2547 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2548 FileID FID = LocInfo.first;
2549 unsigned FileOffset = LocInfo.second;
2550
2551 if (file)
2552 *file = (void *)SM.getFileEntryForID(FID);
2553 if (line)
2554 *line = SM.getLineNumber(FID, FileOffset);
2555 if (column)
2556 *column = SM.getColumnNumber(FID, FileOffset);
2557 if (offset)
2558 *offset = FileOffset;
2559}
2560
Douglas Gregor1db19de2010-01-19 21:36:55 +00002561CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002562 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002563 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002564 return Result;
2565}
2566
2567CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002568 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002569 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002570 return Result;
2571}
2572
Douglas Gregorb9790342010-01-22 21:44:22 +00002573} // end: extern "C"
2574
Douglas Gregor1db19de2010-01-19 21:36:55 +00002575//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002576// CXFile Operations.
2577//===----------------------------------------------------------------------===//
2578
2579extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002580CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002581 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002582 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002583
Steve Naroff88145032009-10-27 14:35:18 +00002584 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002585 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002586}
2587
2588time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002589 if (!SFile)
2590 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002591
Steve Naroff88145032009-10-27 14:35:18 +00002592 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2593 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002594}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002595
Douglas Gregorb9790342010-01-22 21:44:22 +00002596CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2597 if (!tu)
2598 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002599
Douglas Gregorb9790342010-01-22 21:44:22 +00002600 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002601
Douglas Gregorb9790342010-01-22 21:44:22 +00002602 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002603 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2604 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002605 return const_cast<FileEntry *>(File);
2606}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002607
Ted Kremenekfb480492010-01-13 21:46:36 +00002608} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002609
Ted Kremenekfb480492010-01-13 21:46:36 +00002610//===----------------------------------------------------------------------===//
2611// CXCursor Operations.
2612//===----------------------------------------------------------------------===//
2613
Ted Kremenekfb480492010-01-13 21:46:36 +00002614static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002615 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2616 return getDeclFromExpr(CE->getSubExpr());
2617
Ted Kremenekfb480492010-01-13 21:46:36 +00002618 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2619 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002620 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2621 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002622 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2623 return ME->getMemberDecl();
2624 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2625 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002626 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2627 return PRE->getProperty();
2628
Ted Kremenekfb480492010-01-13 21:46:36 +00002629 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2630 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002631 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2632 if (!CE->isElidable())
2633 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002634 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2635 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002636
Douglas Gregordb1314e2010-10-01 21:11:22 +00002637 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2638 return PE->getProtocol();
2639
Ted Kremenekfb480492010-01-13 21:46:36 +00002640 return 0;
2641}
2642
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002643static SourceLocation getLocationFromExpr(Expr *E) {
2644 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2645 return /*FIXME:*/Msg->getLeftLoc();
2646 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2647 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002648 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2649 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002650 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2651 return Member->getMemberLoc();
2652 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2653 return Ivar->getLocation();
2654 return E->getLocStart();
2655}
2656
Ted Kremenekfb480492010-01-13 21:46:36 +00002657extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002658
2659unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002660 CXCursorVisitor visitor,
2661 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002662 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002663
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002664 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2665 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002666 return CursorVis.VisitChildren(parent);
2667}
2668
David Chisnall3387c652010-11-03 14:12:26 +00002669#ifndef __has_feature
2670#define __has_feature(x) 0
2671#endif
2672#if __has_feature(blocks)
2673typedef enum CXChildVisitResult
2674 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2675
2676static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2677 CXClientData client_data) {
2678 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2679 return block(cursor, parent);
2680}
2681#else
2682// If we are compiled with a compiler that doesn't have native blocks support,
2683// define and call the block manually, so the
2684typedef struct _CXChildVisitResult
2685{
2686 void *isa;
2687 int flags;
2688 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002689 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2690 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002691} *CXCursorVisitorBlock;
2692
2693static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2694 CXClientData client_data) {
2695 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2696 return block->invoke(block, cursor, parent);
2697}
2698#endif
2699
2700
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002701unsigned clang_visitChildrenWithBlock(CXCursor parent,
2702 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002703 return clang_visitChildren(parent, visitWithBlock, block);
2704}
2705
Douglas Gregor78205d42010-01-20 21:45:58 +00002706static CXString getDeclSpelling(Decl *D) {
2707 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2708 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002709 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002710
Douglas Gregor78205d42010-01-20 21:45:58 +00002711 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002712 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002713
Douglas Gregor78205d42010-01-20 21:45:58 +00002714 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2715 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2716 // and returns different names. NamedDecl returns the class name and
2717 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002718 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002719
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002720 if (isa<UsingDirectiveDecl>(D))
2721 return createCXString("");
2722
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002723 llvm::SmallString<1024> S;
2724 llvm::raw_svector_ostream os(S);
2725 ND->printName(os);
2726
2727 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002728}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002729
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002730CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002731 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002732 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002733
Steve Narofff334b4e2009-09-02 18:26:48 +00002734 if (clang_isReference(C.kind)) {
2735 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002736 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002737 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002738 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002739 }
2740 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002741 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002742 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002743 }
2744 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002745 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002746 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002747 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002748 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002749 case CXCursor_CXXBaseSpecifier: {
2750 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2751 return createCXString(B->getType().getAsString());
2752 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002753 case CXCursor_TypeRef: {
2754 TypeDecl *Type = getCursorTypeRef(C).first;
2755 assert(Type && "Missing type decl");
2756
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002757 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2758 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002759 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002760 case CXCursor_TemplateRef: {
2761 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002762 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002763
2764 return createCXString(Template->getNameAsString());
2765 }
Douglas Gregor69319002010-08-31 23:48:11 +00002766
2767 case CXCursor_NamespaceRef: {
2768 NamedDecl *NS = getCursorNamespaceRef(C).first;
2769 assert(NS && "Missing namespace decl");
2770
2771 return createCXString(NS->getNameAsString());
2772 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002773
Douglas Gregora67e03f2010-09-09 21:42:20 +00002774 case CXCursor_MemberRef: {
2775 FieldDecl *Field = getCursorMemberRef(C).first;
2776 assert(Field && "Missing member decl");
2777
2778 return createCXString(Field->getNameAsString());
2779 }
2780
Douglas Gregor36897b02010-09-10 00:22:18 +00002781 case CXCursor_LabelRef: {
2782 LabelStmt *Label = getCursorLabelRef(C).first;
2783 assert(Label && "Missing label");
2784
2785 return createCXString(Label->getID()->getName());
2786 }
2787
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002788 case CXCursor_OverloadedDeclRef: {
2789 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2790 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2791 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2792 return createCXString(ND->getNameAsString());
2793 return createCXString("");
2794 }
2795 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2796 return createCXString(E->getName().getAsString());
2797 OverloadedTemplateStorage *Ovl
2798 = Storage.get<OverloadedTemplateStorage*>();
2799 if (Ovl->size() == 0)
2800 return createCXString("");
2801 return createCXString((*Ovl->begin())->getNameAsString());
2802 }
2803
Daniel Dunbaracca7252009-11-30 20:42:49 +00002804 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002805 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002806 }
2807 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002808
2809 if (clang_isExpression(C.kind)) {
2810 Decl *D = getDeclFromExpr(getCursorExpr(C));
2811 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002812 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002813 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002814 }
2815
Douglas Gregor36897b02010-09-10 00:22:18 +00002816 if (clang_isStatement(C.kind)) {
2817 Stmt *S = getCursorStmt(C);
2818 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2819 return createCXString(Label->getID()->getName());
2820
2821 return createCXString("");
2822 }
2823
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002824 if (C.kind == CXCursor_MacroInstantiation)
2825 return createCXString(getCursorMacroInstantiation(C)->getName()
2826 ->getNameStart());
2827
Douglas Gregor572feb22010-03-18 18:04:21 +00002828 if (C.kind == CXCursor_MacroDefinition)
2829 return createCXString(getCursorMacroDefinition(C)->getName()
2830 ->getNameStart());
2831
Douglas Gregorecdcb882010-10-20 22:00:55 +00002832 if (C.kind == CXCursor_InclusionDirective)
2833 return createCXString(getCursorInclusionDirective(C)->getFileName());
2834
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002835 if (clang_isDeclaration(C.kind))
2836 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002837
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002838 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002839}
2840
Douglas Gregor358559d2010-10-02 22:49:11 +00002841CXString clang_getCursorDisplayName(CXCursor C) {
2842 if (!clang_isDeclaration(C.kind))
2843 return clang_getCursorSpelling(C);
2844
2845 Decl *D = getCursorDecl(C);
2846 if (!D)
2847 return createCXString("");
2848
2849 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2850 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2851 D = FunTmpl->getTemplatedDecl();
2852
2853 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2854 llvm::SmallString<64> Str;
2855 llvm::raw_svector_ostream OS(Str);
2856 OS << Function->getNameAsString();
2857 if (Function->getPrimaryTemplate())
2858 OS << "<>";
2859 OS << "(";
2860 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2861 if (I)
2862 OS << ", ";
2863 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2864 }
2865
2866 if (Function->isVariadic()) {
2867 if (Function->getNumParams())
2868 OS << ", ";
2869 OS << "...";
2870 }
2871 OS << ")";
2872 return createCXString(OS.str());
2873 }
2874
2875 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2876 llvm::SmallString<64> Str;
2877 llvm::raw_svector_ostream OS(Str);
2878 OS << ClassTemplate->getNameAsString();
2879 OS << "<";
2880 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2881 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2882 if (I)
2883 OS << ", ";
2884
2885 NamedDecl *Param = Params->getParam(I);
2886 if (Param->getIdentifier()) {
2887 OS << Param->getIdentifier()->getName();
2888 continue;
2889 }
2890
2891 // There is no parameter name, which makes this tricky. Try to come up
2892 // with something useful that isn't too long.
2893 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2894 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2895 else if (NonTypeTemplateParmDecl *NTTP
2896 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2897 OS << NTTP->getType().getAsString(Policy);
2898 else
2899 OS << "template<...> class";
2900 }
2901
2902 OS << ">";
2903 return createCXString(OS.str());
2904 }
2905
2906 if (ClassTemplateSpecializationDecl *ClassSpec
2907 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2908 // If the type was explicitly written, use that.
2909 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2910 return createCXString(TSInfo->getType().getAsString(Policy));
2911
2912 llvm::SmallString<64> Str;
2913 llvm::raw_svector_ostream OS(Str);
2914 OS << ClassSpec->getNameAsString();
2915 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002916 ClassSpec->getTemplateArgs().data(),
2917 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002918 Policy);
2919 return createCXString(OS.str());
2920 }
2921
2922 return clang_getCursorSpelling(C);
2923}
2924
Ted Kremeneke68fff62010-02-17 00:41:32 +00002925CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002926 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002927 case CXCursor_FunctionDecl:
2928 return createCXString("FunctionDecl");
2929 case CXCursor_TypedefDecl:
2930 return createCXString("TypedefDecl");
2931 case CXCursor_EnumDecl:
2932 return createCXString("EnumDecl");
2933 case CXCursor_EnumConstantDecl:
2934 return createCXString("EnumConstantDecl");
2935 case CXCursor_StructDecl:
2936 return createCXString("StructDecl");
2937 case CXCursor_UnionDecl:
2938 return createCXString("UnionDecl");
2939 case CXCursor_ClassDecl:
2940 return createCXString("ClassDecl");
2941 case CXCursor_FieldDecl:
2942 return createCXString("FieldDecl");
2943 case CXCursor_VarDecl:
2944 return createCXString("VarDecl");
2945 case CXCursor_ParmDecl:
2946 return createCXString("ParmDecl");
2947 case CXCursor_ObjCInterfaceDecl:
2948 return createCXString("ObjCInterfaceDecl");
2949 case CXCursor_ObjCCategoryDecl:
2950 return createCXString("ObjCCategoryDecl");
2951 case CXCursor_ObjCProtocolDecl:
2952 return createCXString("ObjCProtocolDecl");
2953 case CXCursor_ObjCPropertyDecl:
2954 return createCXString("ObjCPropertyDecl");
2955 case CXCursor_ObjCIvarDecl:
2956 return createCXString("ObjCIvarDecl");
2957 case CXCursor_ObjCInstanceMethodDecl:
2958 return createCXString("ObjCInstanceMethodDecl");
2959 case CXCursor_ObjCClassMethodDecl:
2960 return createCXString("ObjCClassMethodDecl");
2961 case CXCursor_ObjCImplementationDecl:
2962 return createCXString("ObjCImplementationDecl");
2963 case CXCursor_ObjCCategoryImplDecl:
2964 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002965 case CXCursor_CXXMethod:
2966 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002967 case CXCursor_UnexposedDecl:
2968 return createCXString("UnexposedDecl");
2969 case CXCursor_ObjCSuperClassRef:
2970 return createCXString("ObjCSuperClassRef");
2971 case CXCursor_ObjCProtocolRef:
2972 return createCXString("ObjCProtocolRef");
2973 case CXCursor_ObjCClassRef:
2974 return createCXString("ObjCClassRef");
2975 case CXCursor_TypeRef:
2976 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002977 case CXCursor_TemplateRef:
2978 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002979 case CXCursor_NamespaceRef:
2980 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002981 case CXCursor_MemberRef:
2982 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002983 case CXCursor_LabelRef:
2984 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002985 case CXCursor_OverloadedDeclRef:
2986 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002987 case CXCursor_UnexposedExpr:
2988 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002989 case CXCursor_BlockExpr:
2990 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002991 case CXCursor_DeclRefExpr:
2992 return createCXString("DeclRefExpr");
2993 case CXCursor_MemberRefExpr:
2994 return createCXString("MemberRefExpr");
2995 case CXCursor_CallExpr:
2996 return createCXString("CallExpr");
2997 case CXCursor_ObjCMessageExpr:
2998 return createCXString("ObjCMessageExpr");
2999 case CXCursor_UnexposedStmt:
3000 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003001 case CXCursor_LabelStmt:
3002 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003003 case CXCursor_InvalidFile:
3004 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003005 case CXCursor_InvalidCode:
3006 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003007 case CXCursor_NoDeclFound:
3008 return createCXString("NoDeclFound");
3009 case CXCursor_NotImplemented:
3010 return createCXString("NotImplemented");
3011 case CXCursor_TranslationUnit:
3012 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003013 case CXCursor_UnexposedAttr:
3014 return createCXString("UnexposedAttr");
3015 case CXCursor_IBActionAttr:
3016 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003017 case CXCursor_IBOutletAttr:
3018 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003019 case CXCursor_IBOutletCollectionAttr:
3020 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003021 case CXCursor_PreprocessingDirective:
3022 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003023 case CXCursor_MacroDefinition:
3024 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003025 case CXCursor_MacroInstantiation:
3026 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003027 case CXCursor_InclusionDirective:
3028 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003029 case CXCursor_Namespace:
3030 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003031 case CXCursor_LinkageSpec:
3032 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003033 case CXCursor_CXXBaseSpecifier:
3034 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003035 case CXCursor_Constructor:
3036 return createCXString("CXXConstructor");
3037 case CXCursor_Destructor:
3038 return createCXString("CXXDestructor");
3039 case CXCursor_ConversionFunction:
3040 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003041 case CXCursor_TemplateTypeParameter:
3042 return createCXString("TemplateTypeParameter");
3043 case CXCursor_NonTypeTemplateParameter:
3044 return createCXString("NonTypeTemplateParameter");
3045 case CXCursor_TemplateTemplateParameter:
3046 return createCXString("TemplateTemplateParameter");
3047 case CXCursor_FunctionTemplate:
3048 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003049 case CXCursor_ClassTemplate:
3050 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003051 case CXCursor_ClassTemplatePartialSpecialization:
3052 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003053 case CXCursor_NamespaceAlias:
3054 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003055 case CXCursor_UsingDirective:
3056 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003057 case CXCursor_UsingDeclaration:
3058 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003059 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003060
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003061 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003062 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003063}
Steve Naroff89922f82009-08-31 00:59:03 +00003064
Ted Kremeneke68fff62010-02-17 00:41:32 +00003065enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3066 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003067 CXClientData client_data) {
3068 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003069
3070 // If our current best cursor is the construction of a temporary object,
3071 // don't replace that cursor with a type reference, because we want
3072 // clang_getCursor() to point at the constructor.
3073 if (clang_isExpression(BestCursor->kind) &&
3074 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3075 cursor.kind == CXCursor_TypeRef)
3076 return CXChildVisit_Recurse;
3077
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003078 *BestCursor = cursor;
3079 return CXChildVisit_Recurse;
3080}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003081
Douglas Gregorb9790342010-01-22 21:44:22 +00003082CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3083 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003084 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003085
Douglas Gregorb9790342010-01-22 21:44:22 +00003086 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003087 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3088
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003089 // Translate the given source location to make it point at the beginning of
3090 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003091 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003092
3093 // Guard against an invalid SourceLocation, or we may assert in one
3094 // of the following calls.
3095 if (SLoc.isInvalid())
3096 return clang_getNullCursor();
3097
Douglas Gregor40749ee2010-11-03 00:35:38 +00003098 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003099 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3100 CXXUnit->getASTContext().getLangOptions());
3101
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003102 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3103 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003104 // FIXME: Would be great to have a "hint" cursor, then walk from that
3105 // hint cursor upward until we find a cursor whose source range encloses
3106 // the region of interest, rather than starting from the translation unit.
3107 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003108 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003109 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003110 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003111 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003112
3113 if (Logging) {
3114 CXFile SearchFile;
3115 unsigned SearchLine, SearchColumn;
3116 CXFile ResultFile;
3117 unsigned ResultLine, ResultColumn;
3118 CXString SearchFileName, ResultFileName, KindSpelling;
3119 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3120
3121 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3122 0);
3123 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3124 &ResultColumn, 0);
3125 SearchFileName = clang_getFileName(SearchFile);
3126 ResultFileName = clang_getFileName(ResultFile);
3127 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3128 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3129 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3130 clang_getCString(KindSpelling),
3131 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3132 clang_disposeString(SearchFileName);
3133 clang_disposeString(ResultFileName);
3134 clang_disposeString(KindSpelling);
3135 }
3136
Ted Kremeneke68fff62010-02-17 00:41:32 +00003137 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003138}
3139
Ted Kremenek73885552009-11-17 19:28:59 +00003140CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003141 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003142}
3143
3144unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003145 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003146}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003147
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003148unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003149 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3150}
3151
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003152unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003153 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3154}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003155
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003156unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003157 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3158}
3159
Douglas Gregor97b98722010-01-19 23:20:36 +00003160unsigned clang_isExpression(enum CXCursorKind K) {
3161 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3162}
3163
3164unsigned clang_isStatement(enum CXCursorKind K) {
3165 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3166}
3167
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003168unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3169 return K == CXCursor_TranslationUnit;
3170}
3171
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003172unsigned clang_isPreprocessing(enum CXCursorKind K) {
3173 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3174}
3175
Ted Kremenekad6eff62010-03-08 21:17:29 +00003176unsigned clang_isUnexposed(enum CXCursorKind K) {
3177 switch (K) {
3178 case CXCursor_UnexposedDecl:
3179 case CXCursor_UnexposedExpr:
3180 case CXCursor_UnexposedStmt:
3181 case CXCursor_UnexposedAttr:
3182 return true;
3183 default:
3184 return false;
3185 }
3186}
3187
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003188CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003189 return C.kind;
3190}
3191
Douglas Gregor98258af2010-01-18 22:46:11 +00003192CXSourceLocation clang_getCursorLocation(CXCursor C) {
3193 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003194 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003195 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003196 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3197 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003198 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003199 }
3200
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003201 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003202 std::pair<ObjCProtocolDecl *, SourceLocation> P
3203 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003204 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003205 }
3206
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003207 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003208 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3209 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003210 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003211 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003212
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003213 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003214 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003215 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003216 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003217
3218 case CXCursor_TemplateRef: {
3219 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3220 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3221 }
3222
Douglas Gregor69319002010-08-31 23:48:11 +00003223 case CXCursor_NamespaceRef: {
3224 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3225 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3226 }
3227
Douglas Gregora67e03f2010-09-09 21:42:20 +00003228 case CXCursor_MemberRef: {
3229 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3230 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3231 }
3232
Ted Kremenek3064ef92010-08-27 21:34:58 +00003233 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003234 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3235 if (!BaseSpec)
3236 return clang_getNullLocation();
3237
3238 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3239 return cxloc::translateSourceLocation(getCursorContext(C),
3240 TSInfo->getTypeLoc().getBeginLoc());
3241
3242 return cxloc::translateSourceLocation(getCursorContext(C),
3243 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003244 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003245
Douglas Gregor36897b02010-09-10 00:22:18 +00003246 case CXCursor_LabelRef: {
3247 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3248 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3249 }
3250
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003251 case CXCursor_OverloadedDeclRef:
3252 return cxloc::translateSourceLocation(getCursorContext(C),
3253 getCursorOverloadedDeclRef(C).second);
3254
Douglas Gregorf46034a2010-01-18 23:41:10 +00003255 default:
3256 // FIXME: Need a way to enumerate all non-reference cases.
3257 llvm_unreachable("Missed a reference kind");
3258 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003259 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003260
3261 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003262 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003263 getLocationFromExpr(getCursorExpr(C)));
3264
Douglas Gregor36897b02010-09-10 00:22:18 +00003265 if (clang_isStatement(C.kind))
3266 return cxloc::translateSourceLocation(getCursorContext(C),
3267 getCursorStmt(C)->getLocStart());
3268
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003269 if (C.kind == CXCursor_PreprocessingDirective) {
3270 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3271 return cxloc::translateSourceLocation(getCursorContext(C), L);
3272 }
Douglas Gregor48072312010-03-18 15:23:44 +00003273
3274 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003275 SourceLocation L
3276 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003277 return cxloc::translateSourceLocation(getCursorContext(C), L);
3278 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003279
3280 if (C.kind == CXCursor_MacroDefinition) {
3281 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3282 return cxloc::translateSourceLocation(getCursorContext(C), L);
3283 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003284
3285 if (C.kind == CXCursor_InclusionDirective) {
3286 SourceLocation L
3287 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3288 return cxloc::translateSourceLocation(getCursorContext(C), L);
3289 }
3290
Ted Kremenek9a700d22010-05-12 06:16:13 +00003291 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003292 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003293
Douglas Gregorf46034a2010-01-18 23:41:10 +00003294 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003295 SourceLocation Loc = D->getLocation();
3296 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3297 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003298 // FIXME: Multiple variables declared in a single declaration
3299 // currently lack the information needed to correctly determine their
3300 // ranges when accounting for the type-specifier. We use context
3301 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3302 // and if so, whether it is the first decl.
3303 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3304 if (!cxcursor::isFirstInDeclGroup(C))
3305 Loc = VD->getLocation();
3306 }
3307
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003308 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003309}
Douglas Gregora7bde202010-01-19 00:34:46 +00003310
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003311} // end extern "C"
3312
3313static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003314 if (clang_isReference(C.kind)) {
3315 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003316 case CXCursor_ObjCSuperClassRef:
3317 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003318
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003319 case CXCursor_ObjCProtocolRef:
3320 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003321
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003322 case CXCursor_ObjCClassRef:
3323 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003324
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003325 case CXCursor_TypeRef:
3326 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003327
3328 case CXCursor_TemplateRef:
3329 return getCursorTemplateRef(C).second;
3330
Douglas Gregor69319002010-08-31 23:48:11 +00003331 case CXCursor_NamespaceRef:
3332 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003333
3334 case CXCursor_MemberRef:
3335 return getCursorMemberRef(C).second;
3336
Ted Kremenek3064ef92010-08-27 21:34:58 +00003337 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003338 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003339
Douglas Gregor36897b02010-09-10 00:22:18 +00003340 case CXCursor_LabelRef:
3341 return getCursorLabelRef(C).second;
3342
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003343 case CXCursor_OverloadedDeclRef:
3344 return getCursorOverloadedDeclRef(C).second;
3345
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003346 default:
3347 // FIXME: Need a way to enumerate all non-reference cases.
3348 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003349 }
3350 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003351
3352 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003353 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003354
3355 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003356 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003357
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003358 if (C.kind == CXCursor_PreprocessingDirective)
3359 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003360
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003361 if (C.kind == CXCursor_MacroInstantiation)
3362 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003363
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003364 if (C.kind == CXCursor_MacroDefinition)
3365 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003366
3367 if (C.kind == CXCursor_InclusionDirective)
3368 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3369
Ted Kremenek007a7c92010-11-01 23:26:51 +00003370 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3371 Decl *D = cxcursor::getCursorDecl(C);
3372 SourceRange R = D->getSourceRange();
3373 // FIXME: Multiple variables declared in a single declaration
3374 // currently lack the information needed to correctly determine their
3375 // ranges when accounting for the type-specifier. We use context
3376 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3377 // and if so, whether it is the first decl.
3378 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3379 if (!cxcursor::isFirstInDeclGroup(C))
3380 R.setBegin(VD->getLocation());
3381 }
3382 return R;
3383 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003384 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003385
3386extern "C" {
3387
3388CXSourceRange clang_getCursorExtent(CXCursor C) {
3389 SourceRange R = getRawCursorExtent(C);
3390 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003391 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003392
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003393 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003394}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003395
3396CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003397 if (clang_isInvalid(C.kind))
3398 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003399
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003400 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003401 if (clang_isDeclaration(C.kind)) {
3402 Decl *D = getCursorDecl(C);
3403 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3404 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3405 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3406 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3407 if (ObjCForwardProtocolDecl *Protocols
3408 = dyn_cast<ObjCForwardProtocolDecl>(D))
3409 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3410
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003411 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003412 }
3413
Douglas Gregor97b98722010-01-19 23:20:36 +00003414 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003415 Expr *E = getCursorExpr(C);
3416 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003417 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003418 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003419
3420 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3421 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3422
Douglas Gregor97b98722010-01-19 23:20:36 +00003423 return clang_getNullCursor();
3424 }
3425
Douglas Gregor36897b02010-09-10 00:22:18 +00003426 if (clang_isStatement(C.kind)) {
3427 Stmt *S = getCursorStmt(C);
3428 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3429 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3430 getCursorASTUnit(C));
3431
3432 return clang_getNullCursor();
3433 }
3434
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003435 if (C.kind == CXCursor_MacroInstantiation) {
3436 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3437 return MakeMacroDefinitionCursor(Def, CXXUnit);
3438 }
3439
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003440 if (!clang_isReference(C.kind))
3441 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003442
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003443 switch (C.kind) {
3444 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003445 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003446
3447 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003448 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003449
3450 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003451 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003452
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003453 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003454 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003455
3456 case CXCursor_TemplateRef:
3457 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3458
Douglas Gregor69319002010-08-31 23:48:11 +00003459 case CXCursor_NamespaceRef:
3460 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3461
Douglas Gregora67e03f2010-09-09 21:42:20 +00003462 case CXCursor_MemberRef:
3463 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3464
Ted Kremenek3064ef92010-08-27 21:34:58 +00003465 case CXCursor_CXXBaseSpecifier: {
3466 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3467 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3468 CXXUnit));
3469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003470
Douglas Gregor36897b02010-09-10 00:22:18 +00003471 case CXCursor_LabelRef:
3472 // FIXME: We end up faking the "parent" declaration here because we
3473 // don't want to make CXCursor larger.
3474 return MakeCXCursor(getCursorLabelRef(C).first,
3475 CXXUnit->getASTContext().getTranslationUnitDecl(),
3476 CXXUnit);
3477
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003478 case CXCursor_OverloadedDeclRef:
3479 return C;
3480
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003481 default:
3482 // We would prefer to enumerate all non-reference cursor kinds here.
3483 llvm_unreachable("Unhandled reference cursor kind");
3484 break;
3485 }
3486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003487
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003488 return clang_getNullCursor();
3489}
3490
Douglas Gregorb6998662010-01-19 19:34:47 +00003491CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003492 if (clang_isInvalid(C.kind))
3493 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003494
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003495 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003496
Douglas Gregorb6998662010-01-19 19:34:47 +00003497 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003498 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003499 C = clang_getCursorReferenced(C);
3500 WasReference = true;
3501 }
3502
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003503 if (C.kind == CXCursor_MacroInstantiation)
3504 return clang_getCursorReferenced(C);
3505
Douglas Gregorb6998662010-01-19 19:34:47 +00003506 if (!clang_isDeclaration(C.kind))
3507 return clang_getNullCursor();
3508
3509 Decl *D = getCursorDecl(C);
3510 if (!D)
3511 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003512
Douglas Gregorb6998662010-01-19 19:34:47 +00003513 switch (D->getKind()) {
3514 // Declaration kinds that don't really separate the notions of
3515 // declaration and definition.
3516 case Decl::Namespace:
3517 case Decl::Typedef:
3518 case Decl::TemplateTypeParm:
3519 case Decl::EnumConstant:
3520 case Decl::Field:
3521 case Decl::ObjCIvar:
3522 case Decl::ObjCAtDefsField:
3523 case Decl::ImplicitParam:
3524 case Decl::ParmVar:
3525 case Decl::NonTypeTemplateParm:
3526 case Decl::TemplateTemplateParm:
3527 case Decl::ObjCCategoryImpl:
3528 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003529 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003530 case Decl::LinkageSpec:
3531 case Decl::ObjCPropertyImpl:
3532 case Decl::FileScopeAsm:
3533 case Decl::StaticAssert:
3534 case Decl::Block:
3535 return C;
3536
3537 // Declaration kinds that don't make any sense here, but are
3538 // nonetheless harmless.
3539 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003540 break;
3541
3542 // Declaration kinds for which the definition is not resolvable.
3543 case Decl::UnresolvedUsingTypename:
3544 case Decl::UnresolvedUsingValue:
3545 break;
3546
3547 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003548 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3549 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003550
3551 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003552 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003553
3554 case Decl::Enum:
3555 case Decl::Record:
3556 case Decl::CXXRecord:
3557 case Decl::ClassTemplateSpecialization:
3558 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003559 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003560 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003561 return clang_getNullCursor();
3562
3563 case Decl::Function:
3564 case Decl::CXXMethod:
3565 case Decl::CXXConstructor:
3566 case Decl::CXXDestructor:
3567 case Decl::CXXConversion: {
3568 const FunctionDecl *Def = 0;
3569 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003570 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003571 return clang_getNullCursor();
3572 }
3573
3574 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003575 // Ask the variable if it has a definition.
3576 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3577 return MakeCXCursor(Def, CXXUnit);
3578 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003579 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003580
Douglas Gregorb6998662010-01-19 19:34:47 +00003581 case Decl::FunctionTemplate: {
3582 const FunctionDecl *Def = 0;
3583 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003584 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003585 return clang_getNullCursor();
3586 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003587
Douglas Gregorb6998662010-01-19 19:34:47 +00003588 case Decl::ClassTemplate: {
3589 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003590 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003591 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003592 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003593 return clang_getNullCursor();
3594 }
3595
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003596 case Decl::Using:
3597 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3598 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003599
3600 case Decl::UsingShadow:
3601 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003602 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003603 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003604
3605 case Decl::ObjCMethod: {
3606 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3607 if (Method->isThisDeclarationADefinition())
3608 return C;
3609
3610 // Dig out the method definition in the associated
3611 // @implementation, if we have it.
3612 // FIXME: The ASTs should make finding the definition easier.
3613 if (ObjCInterfaceDecl *Class
3614 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3615 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3616 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3617 Method->isInstanceMethod()))
3618 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003619 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003620
3621 return clang_getNullCursor();
3622 }
3623
3624 case Decl::ObjCCategory:
3625 if (ObjCCategoryImplDecl *Impl
3626 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003627 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003628 return clang_getNullCursor();
3629
3630 case Decl::ObjCProtocol:
3631 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3632 return C;
3633 return clang_getNullCursor();
3634
3635 case Decl::ObjCInterface:
3636 // There are two notions of a "definition" for an Objective-C
3637 // class: the interface and its implementation. When we resolved a
3638 // reference to an Objective-C class, produce the @interface as
3639 // the definition; when we were provided with the interface,
3640 // produce the @implementation as the definition.
3641 if (WasReference) {
3642 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3643 return C;
3644 } else if (ObjCImplementationDecl *Impl
3645 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003646 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003647 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003648
Douglas Gregorb6998662010-01-19 19:34:47 +00003649 case Decl::ObjCProperty:
3650 // FIXME: We don't really know where to find the
3651 // ObjCPropertyImplDecls that implement this property.
3652 return clang_getNullCursor();
3653
3654 case Decl::ObjCCompatibleAlias:
3655 if (ObjCInterfaceDecl *Class
3656 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3657 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003658 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003659
Douglas Gregorb6998662010-01-19 19:34:47 +00003660 return clang_getNullCursor();
3661
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003662 case Decl::ObjCForwardProtocol:
3663 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3664 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003665
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003666 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003667 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003668 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003669
3670 case Decl::Friend:
3671 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003672 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003673 return clang_getNullCursor();
3674
3675 case Decl::FriendTemplate:
3676 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003677 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003678 return clang_getNullCursor();
3679 }
3680
3681 return clang_getNullCursor();
3682}
3683
3684unsigned clang_isCursorDefinition(CXCursor C) {
3685 if (!clang_isDeclaration(C.kind))
3686 return 0;
3687
3688 return clang_getCursorDefinition(C) == C;
3689}
3690
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003691unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003692 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003693 return 0;
3694
3695 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3696 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3697 return E->getNumDecls();
3698
3699 if (OverloadedTemplateStorage *S
3700 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3701 return S->size();
3702
3703 Decl *D = Storage.get<Decl*>();
3704 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003705 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003706 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3707 return Classes->size();
3708 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3709 return Protocols->protocol_size();
3710
3711 return 0;
3712}
3713
3714CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003715 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003716 return clang_getNullCursor();
3717
3718 if (index >= clang_getNumOverloadedDecls(cursor))
3719 return clang_getNullCursor();
3720
3721 ASTUnit *Unit = getCursorASTUnit(cursor);
3722 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3723 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3724 return MakeCXCursor(E->decls_begin()[index], Unit);
3725
3726 if (OverloadedTemplateStorage *S
3727 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3728 return MakeCXCursor(S->begin()[index], Unit);
3729
3730 Decl *D = Storage.get<Decl*>();
3731 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3732 // FIXME: This is, unfortunately, linear time.
3733 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3734 std::advance(Pos, index);
3735 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3736 }
3737
3738 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3739 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3740
3741 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3742 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3743
3744 return clang_getNullCursor();
3745}
3746
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003747void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003748 const char **startBuf,
3749 const char **endBuf,
3750 unsigned *startLine,
3751 unsigned *startColumn,
3752 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003753 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003754 assert(getCursorDecl(C) && "CXCursor has null decl");
3755 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003756 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3757 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003758
Steve Naroff4ade6d62009-09-23 17:52:52 +00003759 SourceManager &SM = FD->getASTContext().getSourceManager();
3760 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3761 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3762 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3763 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3764 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3765 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3766}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003767
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003768void clang_enableStackTraces(void) {
3769 llvm::sys::PrintStackTraceOnErrorSignal();
3770}
3771
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003772void clang_executeOnThread(void (*fn)(void*), void *user_data,
3773 unsigned stack_size) {
3774 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3775}
3776
Ted Kremenekfb480492010-01-13 21:46:36 +00003777} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003778
Ted Kremenekfb480492010-01-13 21:46:36 +00003779//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003780// Token-based Operations.
3781//===----------------------------------------------------------------------===//
3782
3783/* CXToken layout:
3784 * int_data[0]: a CXTokenKind
3785 * int_data[1]: starting token location
3786 * int_data[2]: token length
3787 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003788 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003789 * otherwise unused.
3790 */
3791extern "C" {
3792
3793CXTokenKind clang_getTokenKind(CXToken CXTok) {
3794 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3795}
3796
3797CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3798 switch (clang_getTokenKind(CXTok)) {
3799 case CXToken_Identifier:
3800 case CXToken_Keyword:
3801 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003802 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3803 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003804
3805 case CXToken_Literal: {
3806 // We have stashed the starting pointer in the ptr_data field. Use it.
3807 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003808 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003809 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003810
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003811 case CXToken_Punctuation:
3812 case CXToken_Comment:
3813 break;
3814 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003815
3816 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003817 // deconstructing the source location.
3818 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3819 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003820 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003821
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003822 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3823 std::pair<FileID, unsigned> LocInfo
3824 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003825 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003826 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003827 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3828 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003829 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003830
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003831 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003832}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003833
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3835 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3836 if (!CXXUnit)
3837 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003838
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003839 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3840 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3841}
3842
3843CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3844 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003845 if (!CXXUnit)
3846 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
3848 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003849 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3850}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003852void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3853 CXToken **Tokens, unsigned *NumTokens) {
3854 if (Tokens)
3855 *Tokens = 0;
3856 if (NumTokens)
3857 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3860 if (!CXXUnit || !Tokens || !NumTokens)
3861 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003862
Douglas Gregorbdf60622010-03-05 21:16:25 +00003863 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3864
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003865 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003866 if (R.isInvalid())
3867 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003868
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003869 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3870 std::pair<FileID, unsigned> BeginLocInfo
3871 = SourceMgr.getDecomposedLoc(R.getBegin());
3872 std::pair<FileID, unsigned> EndLocInfo
3873 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003874
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003875 // Cannot tokenize across files.
3876 if (BeginLocInfo.first != EndLocInfo.first)
3877 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003878
3879 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003880 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003881 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003882 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003883 if (Invalid)
3884 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003885
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003886 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3887 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003888 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003889 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003890
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003892 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893 llvm::SmallVector<CXToken, 32> CXTokens;
3894 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003895 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003896 do {
3897 // Lex the next token
3898 Lex.LexFromRawLexer(Tok);
3899 if (Tok.is(tok::eof))
3900 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003901
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003902 // Initialize the CXToken.
3903 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003904
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003905 // - Common fields
3906 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3907 CXTok.int_data[2] = Tok.getLength();
3908 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003909
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003910 // - Kind-specific fields
3911 if (Tok.isLiteral()) {
3912 CXTok.int_data[0] = CXToken_Literal;
3913 CXTok.ptr_data = (void *)Tok.getLiteralData();
3914 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003915 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003916 std::pair<FileID, unsigned> LocInfo
3917 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003918 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003919 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003920 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3921 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003922 return;
3923
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003924 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003925 IdentifierInfo *II
3926 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003927
David Chisnall096428b2010-10-13 21:44:48 +00003928 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003929 CXTok.int_data[0] = CXToken_Keyword;
3930 }
3931 else {
3932 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3933 CXToken_Identifier
3934 : CXToken_Keyword;
3935 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003936 CXTok.ptr_data = II;
3937 } else if (Tok.is(tok::comment)) {
3938 CXTok.int_data[0] = CXToken_Comment;
3939 CXTok.ptr_data = 0;
3940 } else {
3941 CXTok.int_data[0] = CXToken_Punctuation;
3942 CXTok.ptr_data = 0;
3943 }
3944 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003945 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003946 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003947
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003948 if (CXTokens.empty())
3949 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003950
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003951 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3952 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3953 *NumTokens = CXTokens.size();
3954}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003955
Ted Kremenek6db61092010-05-05 00:55:15 +00003956void clang_disposeTokens(CXTranslationUnit TU,
3957 CXToken *Tokens, unsigned NumTokens) {
3958 free(Tokens);
3959}
3960
3961} // end: extern "C"
3962
3963//===----------------------------------------------------------------------===//
3964// Token annotation APIs.
3965//===----------------------------------------------------------------------===//
3966
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003967typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003968static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3969 CXCursor parent,
3970 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003971namespace {
3972class AnnotateTokensWorker {
3973 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003974 CXToken *Tokens;
3975 CXCursor *Cursors;
3976 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003977 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003978 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003979 CursorVisitor AnnotateVis;
3980 SourceManager &SrcMgr;
3981
3982 bool MoreTokens() const { return TokIdx < NumTokens; }
3983 unsigned NextToken() const { return TokIdx; }
3984 void AdvanceToken() { ++TokIdx; }
3985 SourceLocation GetTokenLoc(unsigned tokI) {
3986 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3987 }
3988
Ted Kremenek6db61092010-05-05 00:55:15 +00003989public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003990 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003991 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3992 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003993 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003994 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003995 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3996 Decl::MaxPCHLevel, RegionOfInterest),
3997 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003998
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003999 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004000 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004001 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004002 void AnnotateTokens() {
4003 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
4004 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004005};
4006}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004007
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004008void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4009 // Walk the AST within the region of interest, annotating tokens
4010 // along the way.
4011 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004012
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004013 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4014 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004015 if (Pos != Annotated.end() &&
4016 (clang_isInvalid(Cursors[I].kind) ||
4017 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004018 Cursors[I] = Pos->second;
4019 }
4020
4021 // Finish up annotating any tokens left.
4022 if (!MoreTokens())
4023 return;
4024
4025 const CXCursor &C = clang_getNullCursor();
4026 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4027 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4028 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004029 }
4030}
4031
Ted Kremenek6db61092010-05-05 00:55:15 +00004032enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004033AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004034 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004035 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004036 if (cursorRange.isInvalid())
4037 return CXChildVisit_Recurse;
4038
Douglas Gregor4419b672010-10-21 06:10:04 +00004039 if (clang_isPreprocessing(cursor.kind)) {
4040 // For macro instantiations, just note where the beginning of the macro
4041 // instantiation occurs.
4042 if (cursor.kind == CXCursor_MacroInstantiation) {
4043 Annotated[Loc.int_data] = cursor;
4044 return CXChildVisit_Recurse;
4045 }
4046
Douglas Gregor4419b672010-10-21 06:10:04 +00004047 // Items in the preprocessing record are kept separate from items in
4048 // declarations, so we keep a separate token index.
4049 unsigned SavedTokIdx = TokIdx;
4050 TokIdx = PreprocessingTokIdx;
4051
4052 // Skip tokens up until we catch up to the beginning of the preprocessing
4053 // entry.
4054 while (MoreTokens()) {
4055 const unsigned I = NextToken();
4056 SourceLocation TokLoc = GetTokenLoc(I);
4057 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4058 case RangeBefore:
4059 AdvanceToken();
4060 continue;
4061 case RangeAfter:
4062 case RangeOverlap:
4063 break;
4064 }
4065 break;
4066 }
4067
4068 // Look at all of the tokens within this range.
4069 while (MoreTokens()) {
4070 const unsigned I = NextToken();
4071 SourceLocation TokLoc = GetTokenLoc(I);
4072 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4073 case RangeBefore:
4074 assert(0 && "Infeasible");
4075 case RangeAfter:
4076 break;
4077 case RangeOverlap:
4078 Cursors[I] = cursor;
4079 AdvanceToken();
4080 continue;
4081 }
4082 break;
4083 }
4084
4085 // Save the preprocessing token index; restore the non-preprocessing
4086 // token index.
4087 PreprocessingTokIdx = TokIdx;
4088 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004089 return CXChildVisit_Recurse;
4090 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004091
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004092 if (cursorRange.isInvalid())
4093 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004094
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004095 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4096
Ted Kremeneka333c662010-05-12 05:29:33 +00004097 // Adjust the annotated range based specific declarations.
4098 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4099 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004100 Decl *D = cxcursor::getCursorDecl(cursor);
4101 // Don't visit synthesized ObjC methods, since they have no syntatic
4102 // representation in the source.
4103 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4104 if (MD->isSynthesized())
4105 return CXChildVisit_Continue;
4106 }
4107 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004108 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4109 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004110 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004111 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004112 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004113 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004114 }
4115 }
4116 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004117
Ted Kremenek3f404602010-08-14 01:14:06 +00004118 // If the location of the cursor occurs within a macro instantiation, record
4119 // the spelling location of the cursor in our annotation map. We can then
4120 // paper over the token labelings during a post-processing step to try and
4121 // get cursor mappings for tokens that are the *arguments* of a macro
4122 // instantiation.
4123 if (L.isMacroID()) {
4124 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4125 // Only invalidate the old annotation if it isn't part of a preprocessing
4126 // directive. Here we assume that the default construction of CXCursor
4127 // results in CXCursor.kind being an initialized value (i.e., 0). If
4128 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004129
Ted Kremenek3f404602010-08-14 01:14:06 +00004130 CXCursor &oldC = Annotated[rawEncoding];
4131 if (!clang_isPreprocessing(oldC.kind))
4132 oldC = cursor;
4133 }
4134
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004135 const enum CXCursorKind K = clang_getCursorKind(parent);
4136 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004137 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4138 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004139
4140 while (MoreTokens()) {
4141 const unsigned I = NextToken();
4142 SourceLocation TokLoc = GetTokenLoc(I);
4143 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4144 case RangeBefore:
4145 Cursors[I] = updateC;
4146 AdvanceToken();
4147 continue;
4148 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004149 case RangeOverlap:
4150 break;
4151 }
4152 break;
4153 }
4154
4155 // Visit children to get their cursor information.
4156 const unsigned BeforeChildren = NextToken();
4157 VisitChildren(cursor);
4158 const unsigned AfterChildren = NextToken();
4159
4160 // Adjust 'Last' to the last token within the extent of the cursor.
4161 while (MoreTokens()) {
4162 const unsigned I = NextToken();
4163 SourceLocation TokLoc = GetTokenLoc(I);
4164 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4165 case RangeBefore:
4166 assert(0 && "Infeasible");
4167 case RangeAfter:
4168 break;
4169 case RangeOverlap:
4170 Cursors[I] = updateC;
4171 AdvanceToken();
4172 continue;
4173 }
4174 break;
4175 }
4176 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004177
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004178 // Scan the tokens that are at the beginning of the cursor, but are not
4179 // capture by the child cursors.
4180
4181 // For AST elements within macros, rely on a post-annotate pass to
4182 // to correctly annotate the tokens with cursors. Otherwise we can
4183 // get confusing results of having tokens that map to cursors that really
4184 // are expanded by an instantiation.
4185 if (L.isMacroID())
4186 cursor = clang_getNullCursor();
4187
4188 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4189 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4190 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004191
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004192 Cursors[I] = cursor;
4193 }
4194 // Scan the tokens that are at the end of the cursor, but are not captured
4195 // but the child cursors.
4196 for (unsigned I = AfterChildren; I != Last; ++I)
4197 Cursors[I] = cursor;
4198
4199 TokIdx = Last;
4200 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004201}
4202
Ted Kremenek6db61092010-05-05 00:55:15 +00004203static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4204 CXCursor parent,
4205 CXClientData client_data) {
4206 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4207}
4208
Ted Kremenekab979612010-11-11 08:05:23 +00004209// This gets run a separate thread to avoid stack blowout.
4210static void runAnnotateTokensWorker(void *UserData) {
4211 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4212}
4213
Ted Kremenek6db61092010-05-05 00:55:15 +00004214extern "C" {
4215
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004216void clang_annotateTokens(CXTranslationUnit TU,
4217 CXToken *Tokens, unsigned NumTokens,
4218 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004219
4220 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004221 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004222
Douglas Gregor4419b672010-10-21 06:10:04 +00004223 // Any token we don't specifically annotate will have a NULL cursor.
4224 CXCursor C = clang_getNullCursor();
4225 for (unsigned I = 0; I != NumTokens; ++I)
4226 Cursors[I] = C;
4227
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004228 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004229 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004230 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004231
Douglas Gregorbdf60622010-03-05 21:16:25 +00004232 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004233
Douglas Gregor0396f462010-03-19 05:22:59 +00004234 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004235 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004236 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4237 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004238 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4239 clang_getTokenLocation(TU,
4240 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004241
Douglas Gregor0396f462010-03-19 05:22:59 +00004242 // A mapping from the source locations found when re-lexing or traversing the
4243 // region of interest to the corresponding cursors.
4244 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004245
4246 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004247 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004248 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4249 std::pair<FileID, unsigned> BeginLocInfo
4250 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4251 std::pair<FileID, unsigned> EndLocInfo
4252 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004253
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004254 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004255 bool Invalid = false;
4256 if (BeginLocInfo.first == EndLocInfo.first &&
4257 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4258 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004259 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4260 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004261 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004262 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004263 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004264
4265 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004266 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004267 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004268 Token Tok;
4269 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004270
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004271 reprocess:
4272 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4273 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004274 // don't see it while preprocessing these tokens later, but keep track
4275 // of all of the token locations inside this preprocessing directive so
4276 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004277 //
4278 // FIXME: Some simple tests here could identify macro definitions and
4279 // #undefs, to provide specific cursor kinds for those.
4280 std::vector<SourceLocation> Locations;
4281 do {
4282 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004283 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004284 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004286 using namespace cxcursor;
4287 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004288 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4289 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004290 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004291 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4292 Annotated[Locations[I].getRawEncoding()] = Cursor;
4293 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004294
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004295 if (Tok.isAtStartOfLine())
4296 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004297
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004298 continue;
4299 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004300
Douglas Gregor48072312010-03-18 15:23:44 +00004301 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004302 break;
4303 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004304 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004305
Douglas Gregor0396f462010-03-19 05:22:59 +00004306 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004307 // a specific cursor.
4308 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4309 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004310
4311 // Run the worker within a CrashRecoveryContext.
4312 llvm::CrashRecoveryContext CRC;
4313 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4314 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4315 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004316}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004317} // end: extern "C"
4318
4319//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004320// Operations for querying linkage of a cursor.
4321//===----------------------------------------------------------------------===//
4322
4323extern "C" {
4324CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004325 if (!clang_isDeclaration(cursor.kind))
4326 return CXLinkage_Invalid;
4327
Ted Kremenek16b42592010-03-03 06:36:57 +00004328 Decl *D = cxcursor::getCursorDecl(cursor);
4329 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4330 switch (ND->getLinkage()) {
4331 case NoLinkage: return CXLinkage_NoLinkage;
4332 case InternalLinkage: return CXLinkage_Internal;
4333 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4334 case ExternalLinkage: return CXLinkage_External;
4335 };
4336
4337 return CXLinkage_Invalid;
4338}
4339} // end: extern "C"
4340
4341//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004342// Operations for querying language of a cursor.
4343//===----------------------------------------------------------------------===//
4344
4345static CXLanguageKind getDeclLanguage(const Decl *D) {
4346 switch (D->getKind()) {
4347 default:
4348 break;
4349 case Decl::ImplicitParam:
4350 case Decl::ObjCAtDefsField:
4351 case Decl::ObjCCategory:
4352 case Decl::ObjCCategoryImpl:
4353 case Decl::ObjCClass:
4354 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004355 case Decl::ObjCForwardProtocol:
4356 case Decl::ObjCImplementation:
4357 case Decl::ObjCInterface:
4358 case Decl::ObjCIvar:
4359 case Decl::ObjCMethod:
4360 case Decl::ObjCProperty:
4361 case Decl::ObjCPropertyImpl:
4362 case Decl::ObjCProtocol:
4363 return CXLanguage_ObjC;
4364 case Decl::CXXConstructor:
4365 case Decl::CXXConversion:
4366 case Decl::CXXDestructor:
4367 case Decl::CXXMethod:
4368 case Decl::CXXRecord:
4369 case Decl::ClassTemplate:
4370 case Decl::ClassTemplatePartialSpecialization:
4371 case Decl::ClassTemplateSpecialization:
4372 case Decl::Friend:
4373 case Decl::FriendTemplate:
4374 case Decl::FunctionTemplate:
4375 case Decl::LinkageSpec:
4376 case Decl::Namespace:
4377 case Decl::NamespaceAlias:
4378 case Decl::NonTypeTemplateParm:
4379 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004380 case Decl::TemplateTemplateParm:
4381 case Decl::TemplateTypeParm:
4382 case Decl::UnresolvedUsingTypename:
4383 case Decl::UnresolvedUsingValue:
4384 case Decl::Using:
4385 case Decl::UsingDirective:
4386 case Decl::UsingShadow:
4387 return CXLanguage_CPlusPlus;
4388 }
4389
4390 return CXLanguage_C;
4391}
4392
4393extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004394
4395enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4396 if (clang_isDeclaration(cursor.kind))
4397 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4398 if (D->hasAttr<UnavailableAttr>() ||
4399 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4400 return CXAvailability_Available;
4401
4402 if (D->hasAttr<DeprecatedAttr>())
4403 return CXAvailability_Deprecated;
4404 }
4405
4406 return CXAvailability_Available;
4407}
4408
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004409CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4410 if (clang_isDeclaration(cursor.kind))
4411 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4412
4413 return CXLanguage_Invalid;
4414}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004415
4416CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4417 if (clang_isDeclaration(cursor.kind)) {
4418 if (Decl *D = getCursorDecl(cursor)) {
4419 DeclContext *DC = D->getDeclContext();
4420 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4421 }
4422 }
4423
4424 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4425 if (Decl *D = getCursorDecl(cursor))
4426 return MakeCXCursor(D, getCursorASTUnit(cursor));
4427 }
4428
4429 return clang_getNullCursor();
4430}
4431
4432CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4433 if (clang_isDeclaration(cursor.kind)) {
4434 if (Decl *D = getCursorDecl(cursor)) {
4435 DeclContext *DC = D->getLexicalDeclContext();
4436 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4437 }
4438 }
4439
4440 // FIXME: Note that we can't easily compute the lexical context of a
4441 // statement or expression, so we return nothing.
4442 return clang_getNullCursor();
4443}
4444
Douglas Gregor9f592342010-10-01 20:25:15 +00004445static void CollectOverriddenMethods(DeclContext *Ctx,
4446 ObjCMethodDecl *Method,
4447 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4448 if (!Ctx)
4449 return;
4450
4451 // If we have a class or category implementation, jump straight to the
4452 // interface.
4453 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4454 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4455
4456 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4457 if (!Container)
4458 return;
4459
4460 // Check whether we have a matching method at this level.
4461 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4462 Method->isInstanceMethod()))
4463 if (Method != Overridden) {
4464 // We found an override at this level; there is no need to look
4465 // into other protocols or categories.
4466 Methods.push_back(Overridden);
4467 return;
4468 }
4469
4470 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4471 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4472 PEnd = Protocol->protocol_end();
4473 P != PEnd; ++P)
4474 CollectOverriddenMethods(*P, Method, Methods);
4475 }
4476
4477 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4478 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4479 PEnd = Category->protocol_end();
4480 P != PEnd; ++P)
4481 CollectOverriddenMethods(*P, Method, Methods);
4482 }
4483
4484 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4485 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4486 PEnd = Interface->protocol_end();
4487 P != PEnd; ++P)
4488 CollectOverriddenMethods(*P, Method, Methods);
4489
4490 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4491 Category; Category = Category->getNextClassCategory())
4492 CollectOverriddenMethods(Category, Method, Methods);
4493
4494 // We only look into the superclass if we haven't found anything yet.
4495 if (Methods.empty())
4496 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4497 return CollectOverriddenMethods(Super, Method, Methods);
4498 }
4499}
4500
4501void clang_getOverriddenCursors(CXCursor cursor,
4502 CXCursor **overridden,
4503 unsigned *num_overridden) {
4504 if (overridden)
4505 *overridden = 0;
4506 if (num_overridden)
4507 *num_overridden = 0;
4508 if (!overridden || !num_overridden)
4509 return;
4510
4511 if (!clang_isDeclaration(cursor.kind))
4512 return;
4513
4514 Decl *D = getCursorDecl(cursor);
4515 if (!D)
4516 return;
4517
4518 // Handle C++ member functions.
4519 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4520 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4521 *num_overridden = CXXMethod->size_overridden_methods();
4522 if (!*num_overridden)
4523 return;
4524
4525 *overridden = new CXCursor [*num_overridden];
4526 unsigned I = 0;
4527 for (CXXMethodDecl::method_iterator
4528 M = CXXMethod->begin_overridden_methods(),
4529 MEnd = CXXMethod->end_overridden_methods();
4530 M != MEnd; (void)++M, ++I)
4531 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4532 return;
4533 }
4534
4535 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4536 if (!Method)
4537 return;
4538
4539 // Handle Objective-C methods.
4540 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4541 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4542
4543 if (Methods.empty())
4544 return;
4545
4546 *num_overridden = Methods.size();
4547 *overridden = new CXCursor [Methods.size()];
4548 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4549 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4550}
4551
4552void clang_disposeOverriddenCursors(CXCursor *overridden) {
4553 delete [] overridden;
4554}
4555
Douglas Gregorecdcb882010-10-20 22:00:55 +00004556CXFile clang_getIncludedFile(CXCursor cursor) {
4557 if (cursor.kind != CXCursor_InclusionDirective)
4558 return 0;
4559
4560 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4561 return (void *)ID->getFile();
4562}
4563
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004564} // end: extern "C"
4565
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004566
4567//===----------------------------------------------------------------------===//
4568// C++ AST instrospection.
4569//===----------------------------------------------------------------------===//
4570
4571extern "C" {
4572unsigned clang_CXXMethod_isStatic(CXCursor C) {
4573 if (!clang_isDeclaration(C.kind))
4574 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004575
4576 CXXMethodDecl *Method = 0;
4577 Decl *D = cxcursor::getCursorDecl(C);
4578 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4579 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4580 else
4581 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4582 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004583}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004584
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004585} // end: extern "C"
4586
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004587//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004588// Attribute introspection.
4589//===----------------------------------------------------------------------===//
4590
4591extern "C" {
4592CXType clang_getIBOutletCollectionType(CXCursor C) {
4593 if (C.kind != CXCursor_IBOutletCollectionAttr)
4594 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4595
4596 IBOutletCollectionAttr *A =
4597 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4598
4599 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4600}
4601} // end: extern "C"
4602
4603//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004604// CXString Operations.
4605//===----------------------------------------------------------------------===//
4606
4607extern "C" {
4608const char *clang_getCString(CXString string) {
4609 return string.Spelling;
4610}
4611
4612void clang_disposeString(CXString string) {
4613 if (string.MustFreeString && string.Spelling)
4614 free((void*)string.Spelling);
4615}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004616
Ted Kremenekfb480492010-01-13 21:46:36 +00004617} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004618
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004619namespace clang { namespace cxstring {
4620CXString createCXString(const char *String, bool DupString){
4621 CXString Str;
4622 if (DupString) {
4623 Str.Spelling = strdup(String);
4624 Str.MustFreeString = 1;
4625 } else {
4626 Str.Spelling = String;
4627 Str.MustFreeString = 0;
4628 }
4629 return Str;
4630}
4631
4632CXString createCXString(llvm::StringRef String, bool DupString) {
4633 CXString Result;
4634 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4635 char *Spelling = (char *)malloc(String.size() + 1);
4636 memmove(Spelling, String.data(), String.size());
4637 Spelling[String.size()] = 0;
4638 Result.Spelling = Spelling;
4639 Result.MustFreeString = 1;
4640 } else {
4641 Result.Spelling = String.data();
4642 Result.MustFreeString = 0;
4643 }
4644 return Result;
4645}
4646}}
4647
Ted Kremenek04bb7162010-01-22 22:44:15 +00004648//===----------------------------------------------------------------------===//
4649// Misc. utility functions.
4650//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004651
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004652/// Default to using an 8 MB stack size on "safety" threads.
4653static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004654
4655namespace clang {
4656
4657bool RunSafely(llvm::CrashRecoveryContext &CRC,
4658 void (*Fn)(void*), void *UserData) {
4659 if (unsigned Size = GetSafetyThreadStackSize())
4660 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4661 return CRC.RunSafely(Fn, UserData);
4662}
4663
4664unsigned GetSafetyThreadStackSize() {
4665 return SafetyStackThreadSize;
4666}
4667
4668void SetSafetyThreadStackSize(unsigned Value) {
4669 SafetyStackThreadSize = Value;
4670}
4671
4672}
4673
Ted Kremenek04bb7162010-01-22 22:44:15 +00004674extern "C" {
4675
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004676CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004677 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004678}
4679
4680} // end: extern "C"