blob: 72726e385a2fed9a45c44e83e8a46e8f9d280ce7 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000126
127class VisitorJob {
128public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000129 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000130 TypeLocVisitKind, OverloadExprPartsKind,
131 DeclRefExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000132protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000133 void *dataA;
134 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135 CXCursor parent;
136 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000137 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
138 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000139public:
140 Kind getKind() const { return K; }
141 const CXCursor &getParent() const { return parent; }
142 static bool classof(VisitorJob *VJ) { return true; }
143};
144
145typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
146
Douglas Gregorb1373d02010-01-20 20:59:29 +0000147// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000148class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000149 public TypeLocVisitor<CursorVisitor, bool>,
150 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000151{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000153 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000154
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000155 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000157
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000158 /// \brief The declaration that serves at the parent of any statement or
159 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000160 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000161
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000162 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000167
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000168 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
169 // to the visitor. Declarations with a PCH level greater than this value will
170 // be suppressed.
171 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172
173 /// \brief When valid, a source range to which the cursor should restrict
174 /// its search.
175 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000177 // FIXME: Eventually remove. This part of a hack to support proper
178 // iteration over all Decls contained lexically within an ObjC container.
179 DeclContext::decl_iterator *DI_current;
180 DeclContext::decl_iterator DE_current;
181
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000183 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000184 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
186 /// \brief Determine whether this particular source range comes before, comes
187 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000189 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000190 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
191
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000192 class SetParentRAII {
193 CXCursor &Parent;
194 Decl *&StmtParent;
195 CXCursor OldParent;
196
197 public:
198 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
199 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
200 {
201 Parent = NewParent;
202 if (clang_isDeclaration(Parent.kind))
203 StmtParent = getCursorDecl(Parent);
204 }
205
206 ~SetParentRAII() {
207 Parent = OldParent;
208 if (clang_isDeclaration(Parent.kind))
209 StmtParent = getCursorDecl(Parent);
210 }
211 };
212
Steve Naroff89922f82009-08-31 00:59:03 +0000213public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
215 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000216 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000218 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
219 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 {
221 Parent.kind = CXCursor_NoDeclFound;
222 Parent.data[0] = 0;
223 Parent.data[1] = 0;
224 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000225 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000226 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000227
Ted Kremenekab979612010-11-11 08:05:23 +0000228 ASTUnit *getASTUnit() const { return TU; }
229
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000230 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000231
232 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
233 getPreprocessedEntities();
234
Douglas Gregorb1373d02010-01-20 20:59:29 +0000235 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000237 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000238 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000239 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000240 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000241 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000243 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
244 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000245 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000246 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000247 bool VisitClassTemplatePartialSpecializationDecl(
248 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000249 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000250 bool VisitEnumConstantDecl(EnumConstantDecl *D);
251 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
252 bool VisitFunctionDecl(FunctionDecl *ND);
253 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000254 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000255 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000256 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000257 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000258 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000259 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
260 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
261 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
262 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000263 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000264 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
265 bool VisitObjCImplDecl(ObjCImplDecl *D);
266 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
267 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000268 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
269 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
270 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000271 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000272 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000273 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000274 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000275 bool VisitUsingDecl(UsingDecl *D);
276 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
277 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000278
Douglas Gregor01829d32010-08-31 14:41:23 +0000279 // Name visitor
280 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000281 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000282
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000283 // Template visitors
284 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000285 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
287
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000288 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000289 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000290 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000291 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000292 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
293 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000294 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000295 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000296 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000297 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
298 bool VisitPointerTypeLoc(PointerTypeLoc TL);
299 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
300 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
301 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
302 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000303 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000304 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000305 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000306 // FIXME: Implement visitors here when the unimplemented TypeLocs get
307 // implemented
308 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
309 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000310
Douglas Gregora59e3902010-01-21 23:27:09 +0000311 // Statement visitors
312 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000313
Douglas Gregor336fd812010-01-23 00:40:08 +0000314 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000315 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000316 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000317 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000318 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
319 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000320 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000321 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000322 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000323 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000324 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000325 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000326 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000327 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000328 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000329
330#define DATA_RECURSIVE_VISIT(NAME)\
331bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
332 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenek73d15c42010-11-13 01:09:29 +0000333 DATA_RECURSIVE_VISIT(BlockExpr)
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000334 DATA_RECURSIVE_VISIT(CompoundLiteralExpr)
Ted Kremenek11b8e3e2010-11-13 05:55:53 +0000335 DATA_RECURSIVE_VISIT(CXXDefaultArgExpr)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000336 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek11b8e3e2010-11-13 05:55:53 +0000337 DATA_RECURSIVE_VISIT(CXXNewExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000338 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenek73d15c42010-11-13 01:09:29 +0000339 DATA_RECURSIVE_VISIT(CXXTemporaryObjectExpr)
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000340 DATA_RECURSIVE_VISIT(DeclRefExpr)
Ted Kremenek035dc412010-11-13 00:36:50 +0000341 DATA_RECURSIVE_VISIT(DeclStmt)
Ted Kremenek99394242010-11-12 22:24:57 +0000342 DATA_RECURSIVE_VISIT(ExplicitCastExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000343 DATA_RECURSIVE_VISIT(DoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000344 DATA_RECURSIVE_VISIT(IfStmt)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000345 DATA_RECURSIVE_VISIT(InitListExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000346 DATA_RECURSIVE_VISIT(ForStmt)
Ted Kremenek1876bf62010-11-13 00:58:15 +0000347 DATA_RECURSIVE_VISIT(GotoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000348 DATA_RECURSIVE_VISIT(MemberExpr)
Ted Kremenek73d15c42010-11-13 01:09:29 +0000349 DATA_RECURSIVE_VISIT(ObjCEncodeExpr)
Ted Kremenekc373e3c2010-11-12 22:24:55 +0000350 DATA_RECURSIVE_VISIT(ObjCMessageExpr)
Ted Kremenek60458782010-11-12 21:34:16 +0000351 DATA_RECURSIVE_VISIT(OverloadExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000352 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekbb677132010-11-12 18:27:04 +0000353 DATA_RECURSIVE_VISIT(WhileStmt)
Ted Kremenek60458782010-11-12 21:34:16 +0000354 DATA_RECURSIVE_VISIT(UnresolvedMemberExpr)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000355
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000356 // Data-recursive visitor functions.
357 bool IsInRegionOfInterest(CXCursor C);
358 bool RunVisitorWorkList(VisitorWorkList &WL);
359 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
360 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000361};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000362
Ted Kremenekab188932010-01-05 19:32:54 +0000363} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000364
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000365static SourceRange getRawCursorExtent(CXCursor C);
366
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
369}
370
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \brief Visit the given cursor and, if requested by the visitor,
372/// its children.
373///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374/// \param Cursor the cursor to visit.
375///
376/// \param CheckRegionOfInterest if true, then the caller already checked that
377/// this cursor is within the region of interest.
378///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379/// \returns true if the visitation should be aborted, false if it
380/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382 if (clang_isInvalid(Cursor.kind))
383 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000384
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 if (clang_isDeclaration(Cursor.kind)) {
386 Decl *D = getCursorDecl(Cursor);
387 assert(D && "Invalid declaration cursor");
388 if (D->getPCHLevel() > MaxPCHLevel)
389 return false;
390
391 if (D->isImplicit())
392 return false;
393 }
394
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000395 // If we have a range of interest, and this cursor doesn't intersect with it,
396 // we're done.
397 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000398 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000399 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000400 return false;
401 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403 switch (Visitor(Cursor, Parent, ClientData)) {
404 case CXChildVisit_Break:
405 return true;
406
407 case CXChildVisit_Continue:
408 return false;
409
410 case CXChildVisit_Recurse:
411 return VisitChildren(Cursor);
412 }
413
Douglas Gregorfd643772010-01-25 16:45:46 +0000414 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000415}
416
Douglas Gregor788f5a12010-03-20 00:41:21 +0000417std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
418CursorVisitor::getPreprocessedEntities() {
419 PreprocessingRecord &PPRec
420 = *TU->getPreprocessor().getPreprocessingRecord();
421
422 bool OnlyLocalDecls
423 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
424
425 // There is no region of interest; we have to walk everything.
426 if (RegionOfInterest.isInvalid())
427 return std::make_pair(PPRec.begin(OnlyLocalDecls),
428 PPRec.end(OnlyLocalDecls));
429
430 // Find the file in which the region of interest lands.
431 SourceManager &SM = TU->getSourceManager();
432 std::pair<FileID, unsigned> Begin
433 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
434 std::pair<FileID, unsigned> End
435 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
436
437 // The region of interest spans files; we have to walk everything.
438 if (Begin.first != End.first)
439 return std::make_pair(PPRec.begin(OnlyLocalDecls),
440 PPRec.end(OnlyLocalDecls));
441
442 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
443 = TU->getPreprocessedEntitiesByFile();
444 if (ByFileMap.empty()) {
445 // Build the mapping from files to sets of preprocessed entities.
446 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
447 EEnd = PPRec.end(OnlyLocalDecls);
448 E != EEnd; ++E) {
449 std::pair<FileID, unsigned> P
450 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
451 ByFileMap[P.first].push_back(*E);
452 }
453 }
454
455 return std::make_pair(ByFileMap[Begin.first].begin(),
456 ByFileMap[Begin.first].end());
457}
458
Douglas Gregorb1373d02010-01-20 20:59:29 +0000459/// \brief Visit the children of the given cursor.
460///
461/// \returns true if the visitation should be aborted, false if it
462/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000464 if (clang_isReference(Cursor.kind)) {
465 // By definition, references have no children.
466 return false;
467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
469 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000471 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473 if (clang_isDeclaration(Cursor.kind)) {
474 Decl *D = getCursorDecl(Cursor);
475 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000476 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478
Douglas Gregora59e3902010-01-21 23:27:09 +0000479 if (clang_isStatement(Cursor.kind))
480 return Visit(getCursorStmt(Cursor));
481 if (clang_isExpression(Cursor.kind))
482 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000483
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000485 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000486 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
487 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000488 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
489 TLEnd = CXXUnit->top_level_end();
490 TL != TLEnd; ++TL) {
491 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000492 return true;
493 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 } else if (VisitDeclContext(
495 CXXUnit->getASTContext().getTranslationUnitDecl()))
496 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000497
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000499 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 // FIXME: Once we have the ability to deserialize a preprocessing record,
501 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000502 PreprocessingRecord::iterator E, EEnd;
503 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
505 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
506 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000507
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 continue;
509 }
510
511 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
512 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
513 return true;
514
515 continue;
516 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000517
518 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
519 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
520 return true;
521
522 continue;
523 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000524 }
525 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000526 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000528
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000530 return false;
531}
532
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000534 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
535 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000536
Ted Kremenek664cffd2010-07-22 11:30:19 +0000537 if (Stmt *Body = B->getBody())
538 return Visit(MakeCXCursor(Body, StmtParent, TU));
539
540 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000541}
542
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
544 if (RegionOfInterest.isValid()) {
545 SourceRange Range = getRawCursorExtent(Cursor);
546 if (Range.isInvalid())
547 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000548
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000549 switch (CompareRegionOfInterest(Range)) {
550 case RangeBefore:
551 // This declaration comes before the region of interest; skip it.
552 return llvm::Optional<bool>();
553
554 case RangeAfter:
555 // This declaration comes after the region of interest; we're done.
556 return false;
557
558 case RangeOverlap:
559 // This declaration overlaps the region of interest; visit it.
560 break;
561 }
562 }
563 return true;
564}
565
566bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
567 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
568
569 // FIXME: Eventually remove. This part of a hack to support proper
570 // iteration over all Decls contained lexically within an ObjC container.
571 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
572 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
573
574 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000575 Decl *D = *I;
576 if (D->getLexicalDeclContext() != DC)
577 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000578 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000579 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
580 if (!V.hasValue())
581 continue;
582 if (!V.getValue())
583 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585 return true;
586 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000588}
589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
591 llvm_unreachable("Translation units are visited directly by Visit()");
592 return false;
593}
594
595bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
596 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
597 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599 return false;
600}
601
602bool CursorVisitor::VisitTagDecl(TagDecl *D) {
603 return VisitDeclContext(D);
604}
605
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000606bool CursorVisitor::VisitClassTemplateSpecializationDecl(
607 ClassTemplateSpecializationDecl *D) {
608 bool ShouldVisitBody = false;
609 switch (D->getSpecializationKind()) {
610 case TSK_Undeclared:
611 case TSK_ImplicitInstantiation:
612 // Nothing to visit
613 return false;
614
615 case TSK_ExplicitInstantiationDeclaration:
616 case TSK_ExplicitInstantiationDefinition:
617 break;
618
619 case TSK_ExplicitSpecialization:
620 ShouldVisitBody = true;
621 break;
622 }
623
624 // Visit the template arguments used in the specialization.
625 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
626 TypeLoc TL = SpecType->getTypeLoc();
627 if (TemplateSpecializationTypeLoc *TSTLoc
628 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
629 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
630 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
631 return true;
632 }
633 }
634
635 if (ShouldVisitBody && VisitCXXRecordDecl(D))
636 return true;
637
638 return false;
639}
640
Douglas Gregor74dbe642010-08-31 19:31:58 +0000641bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
642 ClassTemplatePartialSpecializationDecl *D) {
643 // FIXME: Visit the "outer" template parameter lists on the TagDecl
644 // before visiting these template parameters.
645 if (VisitTemplateParameters(D->getTemplateParameters()))
646 return true;
647
648 // Visit the partial specialization arguments.
649 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
650 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
651 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
652 return true;
653
654 return VisitCXXRecordDecl(D);
655}
656
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000657bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000658 // Visit the default argument.
659 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
660 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
661 if (Visit(DefArg->getTypeLoc()))
662 return true;
663
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000664 return false;
665}
666
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000667bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
668 if (Expr *Init = D->getInitExpr())
669 return Visit(MakeCXCursor(Init, StmtParent, TU));
670 return false;
671}
672
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000673bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
674 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
675 if (Visit(TSInfo->getTypeLoc()))
676 return true;
677
678 return false;
679}
680
Douglas Gregora67e03f2010-09-09 21:42:20 +0000681/// \brief Compare two base or member initializers based on their source order.
682static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
683 CXXBaseOrMemberInitializer const * const *X
684 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
685 CXXBaseOrMemberInitializer const * const *Y
686 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
687
688 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
689 return -1;
690 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
691 return 1;
692 else
693 return 0;
694}
695
Douglas Gregorb1373d02010-01-20 20:59:29 +0000696bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000697 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
698 // Visit the function declaration's syntactic components in the order
699 // written. This requires a bit of work.
700 TypeLoc TL = TSInfo->getTypeLoc();
701 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
702
703 // If we have a function declared directly (without the use of a typedef),
704 // visit just the return type. Otherwise, just visit the function's type
705 // now.
706 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
707 (!FTL && Visit(TL)))
708 return true;
709
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000710 // Visit the nested-name-specifier, if present.
711 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
712 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
713 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000714
715 // Visit the declaration name.
716 if (VisitDeclarationNameInfo(ND->getNameInfo()))
717 return true;
718
719 // FIXME: Visit explicitly-specified template arguments!
720
721 // Visit the function parameters, if we have a function type.
722 if (FTL && VisitFunctionTypeLoc(*FTL, true))
723 return true;
724
725 // FIXME: Attributes?
726 }
727
Douglas Gregora67e03f2010-09-09 21:42:20 +0000728 if (ND->isThisDeclarationADefinition()) {
729 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
730 // Find the initializers that were written in the source.
731 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
732 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
733 IEnd = Constructor->init_end();
734 I != IEnd; ++I) {
735 if (!(*I)->isWritten())
736 continue;
737
738 WrittenInits.push_back(*I);
739 }
740
741 // Sort the initializers in source order
742 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
743 &CompareCXXBaseOrMemberInitializers);
744
745 // Visit the initializers in source order
746 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
747 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
748 if (Init->isMemberInitializer()) {
749 if (Visit(MakeCursorMemberRef(Init->getMember(),
750 Init->getMemberLocation(), TU)))
751 return true;
752 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
753 if (Visit(BaseInfo->getTypeLoc()))
754 return true;
755 }
756
757 // Visit the initializer value.
758 if (Expr *Initializer = Init->getInit())
759 if (Visit(MakeCXCursor(Initializer, ND, TU)))
760 return true;
761 }
762 }
763
764 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
765 return true;
766 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000767
Douglas Gregorb1373d02010-01-20 20:59:29 +0000768 return false;
769}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000770
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000771bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
772 if (VisitDeclaratorDecl(D))
773 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000774
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000775 if (Expr *BitWidth = D->getBitWidth())
776 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000778 return false;
779}
780
781bool CursorVisitor::VisitVarDecl(VarDecl *D) {
782 if (VisitDeclaratorDecl(D))
783 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785 if (Expr *Init = D->getInit())
786 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788 return false;
789}
790
Douglas Gregor84b51d72010-09-01 20:16:53 +0000791bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
792 if (VisitDeclaratorDecl(D))
793 return true;
794
795 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
796 if (Expr *DefArg = D->getDefaultArgument())
797 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
798
799 return false;
800}
801
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000802bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
803 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
804 // before visiting these template parameters.
805 if (VisitTemplateParameters(D->getTemplateParameters()))
806 return true;
807
808 return VisitFunctionDecl(D->getTemplatedDecl());
809}
810
Douglas Gregor39d6f072010-08-31 19:02:00 +0000811bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
812 // FIXME: Visit the "outer" template parameter lists on the TagDecl
813 // before visiting these template parameters.
814 if (VisitTemplateParameters(D->getTemplateParameters()))
815 return true;
816
817 return VisitCXXRecordDecl(D->getTemplatedDecl());
818}
819
Douglas Gregor84b51d72010-09-01 20:16:53 +0000820bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
821 if (VisitTemplateParameters(D->getTemplateParameters()))
822 return true;
823
824 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
825 VisitTemplateArgumentLoc(D->getDefaultArgument()))
826 return true;
827
828 return false;
829}
830
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000831bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000832 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
833 if (Visit(TSInfo->getTypeLoc()))
834 return true;
835
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000836 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000837 PEnd = ND->param_end();
838 P != PEnd; ++P) {
839 if (Visit(MakeCXCursor(*P, TU)))
840 return true;
841 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 if (ND->isThisDeclarationADefinition() &&
844 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
845 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000846
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000847 return false;
848}
849
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000850namespace {
851 struct ContainerDeclsSort {
852 SourceManager &SM;
853 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
854 bool operator()(Decl *A, Decl *B) {
855 SourceLocation L_A = A->getLocStart();
856 SourceLocation L_B = B->getLocStart();
857 assert(L_A.isValid() && L_B.isValid());
858 return SM.isBeforeInTranslationUnit(L_A, L_B);
859 }
860 };
861}
862
Douglas Gregora59e3902010-01-21 23:27:09 +0000863bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000864 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
865 // an @implementation can lexically contain Decls that are not properly
866 // nested in the AST. When we identify such cases, we need to retrofit
867 // this nesting here.
868 if (!DI_current)
869 return VisitDeclContext(D);
870
871 // Scan the Decls that immediately come after the container
872 // in the current DeclContext. If any fall within the
873 // container's lexical region, stash them into a vector
874 // for later processing.
875 llvm::SmallVector<Decl *, 24> DeclsInContainer;
876 SourceLocation EndLoc = D->getSourceRange().getEnd();
877 SourceManager &SM = TU->getSourceManager();
878 if (EndLoc.isValid()) {
879 DeclContext::decl_iterator next = *DI_current;
880 while (++next != DE_current) {
881 Decl *D_next = *next;
882 if (!D_next)
883 break;
884 SourceLocation L = D_next->getLocStart();
885 if (!L.isValid())
886 break;
887 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
888 *DI_current = next;
889 DeclsInContainer.push_back(D_next);
890 continue;
891 }
892 break;
893 }
894 }
895
896 // The common case.
897 if (DeclsInContainer.empty())
898 return VisitDeclContext(D);
899
900 // Get all the Decls in the DeclContext, and sort them with the
901 // additional ones we've collected. Then visit them.
902 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
903 I!=E; ++I) {
904 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000905 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
906 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000907 continue;
908 DeclsInContainer.push_back(subDecl);
909 }
910
911 // Now sort the Decls so that they appear in lexical order.
912 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
913 ContainerDeclsSort(SM));
914
915 // Now visit the decls.
916 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
917 E = DeclsInContainer.end(); I != E; ++I) {
918 CXCursor Cursor = MakeCXCursor(*I, TU);
919 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
920 if (!V.hasValue())
921 continue;
922 if (!V.getValue())
923 return false;
924 if (Visit(Cursor, true))
925 return true;
926 }
927 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000928}
929
Douglas Gregorb1373d02010-01-20 20:59:29 +0000930bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000931 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
932 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000935 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
936 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
937 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000938 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000939 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000940
Douglas Gregora59e3902010-01-21 23:27:09 +0000941 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000942}
943
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000944bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
945 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
946 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
947 E = PID->protocol_end(); I != E; ++I, ++PL)
948 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000951 return VisitObjCContainerDecl(PID);
952}
953
Ted Kremenek23173d72010-05-18 21:09:07 +0000954bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000955 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000956 return true;
957
Ted Kremenek23173d72010-05-18 21:09:07 +0000958 // FIXME: This implements a workaround with @property declarations also being
959 // installed in the DeclContext for the @interface. Eventually this code
960 // should be removed.
961 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
962 if (!CDecl || !CDecl->IsClassExtension())
963 return false;
964
965 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
966 if (!ID)
967 return false;
968
969 IdentifierInfo *PropertyId = PD->getIdentifier();
970 ObjCPropertyDecl *prevDecl =
971 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
972
973 if (!prevDecl)
974 return false;
975
976 // Visit synthesized methods since they will be skipped when visiting
977 // the @interface.
978 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000979 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000980 if (Visit(MakeCXCursor(MD, TU)))
981 return true;
982
983 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000984 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000985 if (Visit(MakeCXCursor(MD, TU)))
986 return true;
987
988 return false;
989}
990
Douglas Gregorb1373d02010-01-20 20:59:29 +0000991bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000992 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000993 if (D->getSuperClass() &&
994 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000996 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000997 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000999 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1000 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1001 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001002 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001004
Douglas Gregora59e3902010-01-21 23:27:09 +00001005 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001006}
1007
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001008bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1009 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001010}
1011
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001012bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001013 // 'ID' could be null when dealing with invalid code.
1014 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1015 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1016 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001017
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018 return VisitObjCImplDecl(D);
1019}
1020
1021bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1022#if 0
1023 // Issue callbacks for super class.
1024 // FIXME: No source location information!
1025 if (D->getSuperClass() &&
1026 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028 TU)))
1029 return true;
1030#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001032 return VisitObjCImplDecl(D);
1033}
1034
1035bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1036 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1037 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1038 E = D->protocol_end();
1039 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001040 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001041 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042
1043 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001044}
1045
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1047 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1048 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1049 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001050
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001051 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001052}
1053
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001054bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1055 return VisitDeclContext(D);
1056}
1057
Douglas Gregor69319002010-08-31 23:48:11 +00001058bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001059 // Visit nested-name-specifier.
1060 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1061 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1062 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001063
1064 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1065 D->getTargetNameLoc(), TU));
1066}
1067
Douglas Gregor7e242562010-09-01 19:52:22 +00001068bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001069 // Visit nested-name-specifier.
1070 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1071 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1072 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001073
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001074 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1075 return true;
1076
Douglas Gregor7e242562010-09-01 19:52:22 +00001077 return VisitDeclarationNameInfo(D->getNameInfo());
1078}
1079
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001080bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001081 // Visit nested-name-specifier.
1082 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1083 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1084 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001085
1086 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1087 D->getIdentLocation(), TU));
1088}
1089
Douglas Gregor7e242562010-09-01 19:52:22 +00001090bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001091 // Visit nested-name-specifier.
1092 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1093 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1094 return true;
1095
Douglas Gregor7e242562010-09-01 19:52:22 +00001096 return VisitDeclarationNameInfo(D->getNameInfo());
1097}
1098
1099bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1100 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001101 // Visit nested-name-specifier.
1102 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1103 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1104 return true;
1105
Douglas Gregor7e242562010-09-01 19:52:22 +00001106 return false;
1107}
1108
Douglas Gregor01829d32010-08-31 14:41:23 +00001109bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1110 switch (Name.getName().getNameKind()) {
1111 case clang::DeclarationName::Identifier:
1112 case clang::DeclarationName::CXXLiteralOperatorName:
1113 case clang::DeclarationName::CXXOperatorName:
1114 case clang::DeclarationName::CXXUsingDirective:
1115 return false;
1116
1117 case clang::DeclarationName::CXXConstructorName:
1118 case clang::DeclarationName::CXXDestructorName:
1119 case clang::DeclarationName::CXXConversionFunctionName:
1120 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1121 return Visit(TSInfo->getTypeLoc());
1122 return false;
1123
1124 case clang::DeclarationName::ObjCZeroArgSelector:
1125 case clang::DeclarationName::ObjCOneArgSelector:
1126 case clang::DeclarationName::ObjCMultiArgSelector:
1127 // FIXME: Per-identifier location info?
1128 return false;
1129 }
1130
1131 return false;
1132}
1133
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001134bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1135 SourceRange Range) {
1136 // FIXME: This whole routine is a hack to work around the lack of proper
1137 // source information in nested-name-specifiers (PR5791). Since we do have
1138 // a beginning source location, we can visit the first component of the
1139 // nested-name-specifier, if it's a single-token component.
1140 if (!NNS)
1141 return false;
1142
1143 // Get the first component in the nested-name-specifier.
1144 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1145 NNS = Prefix;
1146
1147 switch (NNS->getKind()) {
1148 case NestedNameSpecifier::Namespace:
1149 // FIXME: The token at this source location might actually have been a
1150 // namespace alias, but we don't model that. Lame!
1151 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1152 TU));
1153
1154 case NestedNameSpecifier::TypeSpec: {
1155 // If the type has a form where we know that the beginning of the source
1156 // range matches up with a reference cursor. Visit the appropriate reference
1157 // cursor.
1158 Type *T = NNS->getAsType();
1159 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1160 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1161 if (const TagType *Tag = dyn_cast<TagType>(T))
1162 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1163 if (const TemplateSpecializationType *TST
1164 = dyn_cast<TemplateSpecializationType>(T))
1165 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1166 break;
1167 }
1168
1169 case NestedNameSpecifier::TypeSpecWithTemplate:
1170 case NestedNameSpecifier::Global:
1171 case NestedNameSpecifier::Identifier:
1172 break;
1173 }
1174
1175 return false;
1176}
1177
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001178bool CursorVisitor::VisitTemplateParameters(
1179 const TemplateParameterList *Params) {
1180 if (!Params)
1181 return false;
1182
1183 for (TemplateParameterList::const_iterator P = Params->begin(),
1184 PEnd = Params->end();
1185 P != PEnd; ++P) {
1186 if (Visit(MakeCXCursor(*P, TU)))
1187 return true;
1188 }
1189
1190 return false;
1191}
1192
Douglas Gregor0b36e612010-08-31 20:37:03 +00001193bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1194 switch (Name.getKind()) {
1195 case TemplateName::Template:
1196 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1197
1198 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001199 // Visit the overloaded template set.
1200 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1201 return true;
1202
Douglas Gregor0b36e612010-08-31 20:37:03 +00001203 return false;
1204
1205 case TemplateName::DependentTemplate:
1206 // FIXME: Visit nested-name-specifier.
1207 return false;
1208
1209 case TemplateName::QualifiedTemplate:
1210 // FIXME: Visit nested-name-specifier.
1211 return Visit(MakeCursorTemplateRef(
1212 Name.getAsQualifiedTemplateName()->getDecl(),
1213 Loc, TU));
1214 }
1215
1216 return false;
1217}
1218
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001219bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1220 switch (TAL.getArgument().getKind()) {
1221 case TemplateArgument::Null:
1222 case TemplateArgument::Integral:
1223 return false;
1224
1225 case TemplateArgument::Pack:
1226 // FIXME: Implement when variadic templates come along.
1227 return false;
1228
1229 case TemplateArgument::Type:
1230 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1231 return Visit(TSInfo->getTypeLoc());
1232 return false;
1233
1234 case TemplateArgument::Declaration:
1235 if (Expr *E = TAL.getSourceDeclExpression())
1236 return Visit(MakeCXCursor(E, StmtParent, TU));
1237 return false;
1238
1239 case TemplateArgument::Expression:
1240 if (Expr *E = TAL.getSourceExpression())
1241 return Visit(MakeCXCursor(E, StmtParent, TU));
1242 return false;
1243
1244 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001245 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1246 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001247 }
1248
1249 return false;
1250}
1251
Ted Kremeneka0536d82010-05-07 01:04:29 +00001252bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1253 return VisitDeclContext(D);
1254}
1255
Douglas Gregor01829d32010-08-31 14:41:23 +00001256bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1257 return Visit(TL.getUnqualifiedLoc());
1258}
1259
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001260bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1261 ASTContext &Context = TU->getASTContext();
1262
1263 // Some builtin types (such as Objective-C's "id", "sel", and
1264 // "Class") have associated declarations. Create cursors for those.
1265 QualType VisitType;
1266 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001267 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001268 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001269 case BuiltinType::Char_U:
1270 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001271 case BuiltinType::Char16:
1272 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001273 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001274 case BuiltinType::UInt:
1275 case BuiltinType::ULong:
1276 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277 case BuiltinType::UInt128:
1278 case BuiltinType::Char_S:
1279 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001280 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001281 case BuiltinType::Short:
1282 case BuiltinType::Int:
1283 case BuiltinType::Long:
1284 case BuiltinType::LongLong:
1285 case BuiltinType::Int128:
1286 case BuiltinType::Float:
1287 case BuiltinType::Double:
1288 case BuiltinType::LongDouble:
1289 case BuiltinType::NullPtr:
1290 case BuiltinType::Overload:
1291 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001292 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001293
1294 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001295 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001296
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001297 case BuiltinType::ObjCId:
1298 VisitType = Context.getObjCIdType();
1299 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001300
1301 case BuiltinType::ObjCClass:
1302 VisitType = Context.getObjCClassType();
1303 break;
1304
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001305 case BuiltinType::ObjCSel:
1306 VisitType = Context.getObjCSelType();
1307 break;
1308 }
1309
1310 if (!VisitType.isNull()) {
1311 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001312 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001313 TU));
1314 }
1315
1316 return false;
1317}
1318
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001319bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1320 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1321}
1322
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1324 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1325}
1326
1327bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1328 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1329}
1330
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001331bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001332 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001333 // no context information with which we can match up the depth/index in the
1334 // type to the appropriate
1335 return false;
1336}
1337
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1339 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1340 return true;
1341
John McCallc12c5bb2010-05-15 11:32:37 +00001342 return false;
1343}
1344
1345bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1346 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1347 return true;
1348
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001349 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1350 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1351 TU)))
1352 return true;
1353 }
1354
1355 return false;
1356}
1357
1358bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001359 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001360}
1361
1362bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1363 return Visit(TL.getPointeeLoc());
1364}
1365
1366bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1367 return Visit(TL.getPointeeLoc());
1368}
1369
1370bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1371 return Visit(TL.getPointeeLoc());
1372}
1373
1374bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001375 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376}
1377
1378bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001379 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380}
1381
Douglas Gregor01829d32010-08-31 14:41:23 +00001382bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1383 bool SkipResultType) {
1384 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385 return true;
1386
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001388 if (Decl *D = TL.getArg(I))
1389 if (Visit(MakeCXCursor(D, TU)))
1390 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001391
1392 return false;
1393}
1394
1395bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1396 if (Visit(TL.getElementLoc()))
1397 return true;
1398
1399 if (Expr *Size = TL.getSizeExpr())
1400 return Visit(MakeCXCursor(Size, StmtParent, TU));
1401
1402 return false;
1403}
1404
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001405bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1406 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001407 // Visit the template name.
1408 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1409 TL.getTemplateNameLoc()))
1410 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001411
1412 // Visit the template arguments.
1413 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1414 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1415 return true;
1416
1417 return false;
1418}
1419
Douglas Gregor2332c112010-01-21 20:48:56 +00001420bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1421 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1422}
1423
1424bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1425 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1426 return Visit(TSInfo->getTypeLoc());
1427
1428 return false;
1429}
1430
Douglas Gregora59e3902010-01-21 23:27:09 +00001431bool CursorVisitor::VisitStmt(Stmt *S) {
1432 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1433 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001434 if (Stmt *C = *Child)
1435 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1436 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438
Douglas Gregora59e3902010-01-21 23:27:09 +00001439 return false;
1440}
1441
Ted Kremenek3064ef92010-08-27 21:34:58 +00001442bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1443 if (D->isDefinition()) {
1444 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1445 E = D->bases_end(); I != E; ++I) {
1446 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1447 return true;
1448 }
1449 }
1450
1451 return VisitTagDecl(D);
1452}
1453
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001454bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001455 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001456 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1457 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001458
1459 // Visit the components of the offsetof expression.
1460 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1461 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1462 const OffsetOfNode &Node = E->getComponent(I);
1463 switch (Node.getKind()) {
1464 case OffsetOfNode::Array:
1465 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1466 StmtParent, TU)))
1467 return true;
1468 break;
1469
1470 case OffsetOfNode::Field:
1471 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1472 TU)))
1473 return true;
1474 break;
1475
1476 case OffsetOfNode::Identifier:
1477 case OffsetOfNode::Base:
1478 continue;
1479 }
1480 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001481
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001482 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001483}
1484
Douglas Gregor336fd812010-01-23 00:40:08 +00001485bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1486 if (E->isArgumentType()) {
1487 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1488 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001489
Douglas Gregor336fd812010-01-23 00:40:08 +00001490 return false;
1491 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001492
Douglas Gregor336fd812010-01-23 00:40:08 +00001493 return VisitExpr(E);
1494}
1495
Douglas Gregor36897b02010-09-10 00:22:18 +00001496bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1497 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1498}
1499
Douglas Gregor648220e2010-08-10 15:02:34 +00001500bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1501 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1502 Visit(E->getArgTInfo2()->getTypeLoc());
1503}
1504
1505bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1506 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1507 return true;
1508
1509 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1510}
1511
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001512bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1513 // Visit the designators.
1514 typedef DesignatedInitExpr::Designator Designator;
1515 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1516 DEnd = E->designators_end();
1517 D != DEnd; ++D) {
1518 if (D->isFieldDesignator()) {
1519 if (FieldDecl *Field = D->getField())
1520 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1521 return true;
1522
1523 continue;
1524 }
1525
1526 if (D->isArrayDesignator()) {
1527 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1528 return true;
1529
1530 continue;
1531 }
1532
1533 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1534 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1535 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1536 return true;
1537 }
1538
1539 // Visit the initializer value itself.
1540 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1541}
1542
Douglas Gregor94802292010-09-02 21:20:16 +00001543bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1544 if (E->isTypeOperand()) {
1545 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1546 return Visit(TSInfo->getTypeLoc());
1547
1548 return false;
1549 }
1550
1551 return VisitExpr(E);
1552}
1553
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001554bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1555 if (E->isTypeOperand()) {
1556 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1557 return Visit(TSInfo->getTypeLoc());
1558
1559 return false;
1560 }
1561
1562 return VisitExpr(E);
1563}
1564
Douglas Gregorab6677e2010-09-08 00:15:04 +00001565bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1566 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1567 return Visit(TSInfo->getTypeLoc());
1568
1569 return false;
1570}
1571
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001572bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1573 // Visit base expression.
1574 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1575 return true;
1576
1577 // Visit the nested-name-specifier.
1578 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1579 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1580 return true;
1581
1582 // Visit the scope type that looks disturbingly like the nested-name-specifier
1583 // but isn't.
1584 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1585 if (Visit(TSInfo->getTypeLoc()))
1586 return true;
1587
1588 // Visit the name of the type being destroyed.
1589 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1590 if (Visit(TSInfo->getTypeLoc()))
1591 return true;
1592
1593 return false;
1594}
1595
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001596bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1597 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1598}
1599
Douglas Gregorbfebed22010-09-03 17:24:10 +00001600bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1601 DependentScopeDeclRefExpr *E) {
1602 // Visit the nested-name-specifier.
1603 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1604 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1605 return true;
1606
1607 // Visit the declaration name.
1608 if (VisitDeclarationNameInfo(E->getNameInfo()))
1609 return true;
1610
1611 // Visit the explicitly-specified template arguments.
1612 if (const ExplicitTemplateArgumentList *ArgList
1613 = E->getOptionalExplicitTemplateArgs()) {
1614 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1615 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1616 Arg != ArgEnd; ++Arg) {
1617 if (VisitTemplateArgumentLoc(*Arg))
1618 return true;
1619 }
1620 }
1621
1622 return false;
1623}
1624
Douglas Gregorab6677e2010-09-08 00:15:04 +00001625bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1626 CXXUnresolvedConstructExpr *E) {
1627 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1628 if (Visit(TSInfo->getTypeLoc()))
1629 return true;
1630
1631 return VisitExpr(E);
1632}
1633
Douglas Gregor25d63622010-09-03 17:35:34 +00001634bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1635 CXXDependentScopeMemberExpr *E) {
1636 // Visit the base expression, if there is one.
1637 if (!E->isImplicitAccess() &&
1638 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1639 return true;
1640
1641 // Visit the nested-name-specifier.
1642 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1643 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1644 return true;
1645
1646 // Visit the declaration name.
1647 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1648 return true;
1649
1650 // Visit the explicitly-specified template arguments.
1651 if (const ExplicitTemplateArgumentList *ArgList
1652 = E->getOptionalExplicitTemplateArgs()) {
1653 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1654 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1655 Arg != ArgEnd; ++Arg) {
1656 if (VisitTemplateArgumentLoc(*Arg))
1657 return true;
1658 }
1659 }
1660
1661 return false;
1662}
1663
Ted Kremenek09dfa372010-02-18 05:46:33 +00001664bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001665 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1666 i != e; ++i)
1667 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001668 return true;
1669
1670 return false;
1671}
1672
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001673//===----------------------------------------------------------------------===//
1674// Data-recursive visitor methods.
1675//===----------------------------------------------------------------------===//
1676
Ted Kremenek28a71942010-11-13 00:36:47 +00001677namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001678#define DEF_JOB(NAME, DATA, KIND)\
1679class NAME : public VisitorJob {\
1680public:\
1681 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1682 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1683 DATA *get() const { return static_cast<DATA*>(dataA); }\
1684};
1685
1686DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1687DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001688DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001689DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1690#undef DEF_JOB
1691
1692class DeclVisit : public VisitorJob {
1693public:
1694 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1695 VisitorJob(parent, VisitorJob::DeclVisitKind,
1696 d, isFirst ? (void*) 1 : (void*) 0) {}
1697 static bool classof(const VisitorJob *VJ) {
1698 return VJ->getKind () == DeclVisitKind;
1699 }
1700 Decl *get() { return static_cast<Decl*>(dataA);}
1701 bool isFirst() const { return dataB ? true : false; }
1702};
1703
1704class TypeLocVisit : public VisitorJob {
1705public:
1706 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1707 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1708 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1709
1710 static bool classof(const VisitorJob *VJ) {
1711 return VJ->getKind() == TypeLocVisitKind;
1712 }
1713
1714 TypeLoc get() {
1715 QualType T = QualType::getFromOpaquePtr(dataA);
1716 return TypeLoc(T, dataB);
1717 }
1718};
1719
Ted Kremenek28a71942010-11-13 00:36:47 +00001720class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1721 VisitorWorkList &WL;
1722 CXCursor Parent;
1723public:
1724 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1725 : WL(wl), Parent(parent) {}
1726
Ted Kremenek73d15c42010-11-13 01:09:29 +00001727 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001728 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001729 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001730 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1731 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001732 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001733 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001734 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001735 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001736 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1737 void VisitForStmt(ForStmt *FS);
1738 void VisitIfStmt(IfStmt *If);
1739 void VisitInitListExpr(InitListExpr *IE);
1740 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001741 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001742 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1743 void VisitOverloadExpr(OverloadExpr *E);
1744 void VisitStmt(Stmt *S);
1745 void VisitSwitchStmt(SwitchStmt *S);
1746 void VisitWhileStmt(WhileStmt *W);
1747 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1748
1749private:
1750 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001751 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001752 void AddTypeLoc(TypeSourceInfo *TI);
1753 void EnqueueChildren(Stmt *S);
1754};
1755} // end anonyous namespace
1756
1757void EnqueueVisitor::AddStmt(Stmt *S) {
1758 if (S)
1759 WL.push_back(StmtVisit(S, Parent));
1760}
Ted Kremenek035dc412010-11-13 00:36:50 +00001761void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001762 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001763 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001764}
1765void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1766 if (TI)
1767 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1768 }
1769void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001770 unsigned size = WL.size();
1771 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1772 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001773 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001774 }
1775 if (size == WL.size())
1776 return;
1777 // Now reverse the entries we just added. This will match the DFS
1778 // ordering performed by the worklist.
1779 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1780 std::reverse(I, E);
1781}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001782void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1783 AddDecl(B->getBlockDecl());
1784}
Ted Kremenek28a71942010-11-13 00:36:47 +00001785void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1786 EnqueueChildren(E);
1787 AddTypeLoc(E->getTypeSourceInfo());
1788}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001789void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1790 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1791 E = S->body_rend(); I != E; ++I) {
1792 AddStmt(*I);
1793 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001794}
1795void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1796 // Enqueue the initializer or constructor arguments.
1797 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1798 AddStmt(E->getConstructorArg(I-1));
1799 // Enqueue the array size, if any.
1800 AddStmt(E->getArraySize());
1801 // Enqueue the allocated type.
1802 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1803 // Enqueue the placement arguments.
1804 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1805 AddStmt(E->getPlacementArg(I-1));
1806}
Ted Kremenek28a71942010-11-13 00:36:47 +00001807void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001808 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1809 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001810 AddStmt(CE->getCallee());
1811 AddStmt(CE->getArg(0));
1812}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001813void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1814 EnqueueChildren(E);
1815 AddTypeLoc(E->getTypeSourceInfo());
1816}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001817void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1818 WL.push_back(DeclRefExprParts(DR, Parent));
1819}
Ted Kremenek035dc412010-11-13 00:36:50 +00001820void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1821 unsigned size = WL.size();
1822 bool isFirst = true;
1823 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1824 D != DEnd; ++D) {
1825 AddDecl(*D, isFirst);
1826 isFirst = false;
1827 }
1828 if (size == WL.size())
1829 return;
1830 // Now reverse the entries we just added. This will match the DFS
1831 // ordering performed by the worklist.
1832 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1833 std::reverse(I, E);
1834}
Ted Kremenek28a71942010-11-13 00:36:47 +00001835void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1836 EnqueueChildren(E);
1837 AddTypeLoc(E->getTypeInfoAsWritten());
1838}
1839void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1840 AddStmt(FS->getBody());
1841 AddStmt(FS->getInc());
1842 AddStmt(FS->getCond());
1843 AddDecl(FS->getConditionVariable());
1844 AddStmt(FS->getInit());
1845}
1846void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1847 AddStmt(If->getElse());
1848 AddStmt(If->getThen());
1849 AddStmt(If->getCond());
1850 AddDecl(If->getConditionVariable());
1851}
1852void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1853 // We care about the syntactic form of the initializer list, only.
1854 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1855 IE = Syntactic;
1856 EnqueueChildren(IE);
1857}
1858void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1859 WL.push_back(MemberExprParts(M, Parent));
1860 AddStmt(M->getBase());
1861}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001862void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1863 AddTypeLoc(E->getEncodedTypeSourceInfo());
1864}
Ted Kremenek28a71942010-11-13 00:36:47 +00001865void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1866 EnqueueChildren(M);
1867 AddTypeLoc(M->getClassReceiverTypeInfo());
1868}
1869void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001870 WL.push_back(OverloadExprParts(E, Parent));
1871}
Ted Kremenek28a71942010-11-13 00:36:47 +00001872void EnqueueVisitor::VisitStmt(Stmt *S) {
1873 EnqueueChildren(S);
1874}
1875void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1876 AddStmt(S->getBody());
1877 AddStmt(S->getCond());
1878 AddDecl(S->getConditionVariable());
1879}
1880void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1881 AddStmt(W->getBody());
1882 AddStmt(W->getCond());
1883 AddDecl(W->getConditionVariable());
1884}
1885void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1886 VisitOverloadExpr(U);
1887 if (!U->isImplicitAccess())
1888 AddStmt(U->getBase());
1889}
Ted Kremenek60458782010-11-12 21:34:16 +00001890
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001891void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001892 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001893}
1894
1895bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1896 if (RegionOfInterest.isValid()) {
1897 SourceRange Range = getRawCursorExtent(C);
1898 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1899 return false;
1900 }
1901 return true;
1902}
1903
1904bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1905 while (!WL.empty()) {
1906 // Dequeue the worklist item.
1907 VisitorJob LI = WL.back(); WL.pop_back();
1908
1909 // Set the Parent field, then back to its old value once we're done.
1910 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1911
1912 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001913 case VisitorJob::DeclVisitKind: {
1914 Decl *D = cast<DeclVisit>(LI).get();
1915 if (!D)
1916 continue;
1917
1918 // For now, perform default visitation for Decls.
Ted Kremenek035dc412010-11-13 00:36:50 +00001919 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(LI).isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001920 return true;
1921
1922 continue;
1923 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001924 case VisitorJob::TypeLocVisitKind: {
1925 // Perform default visitation for TypeLocs.
1926 if (Visit(cast<TypeLocVisit>(LI).get()))
1927 return true;
1928 continue;
1929 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001930 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001931 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001932 if (!S)
1933 continue;
1934
Ted Kremenekf1107452010-11-12 18:26:56 +00001935 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001936 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1937
1938 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001939 case Stmt::GotoStmtClass: {
1940 GotoStmt *GS = cast<GotoStmt>(S);
1941 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1942 GS->getLabelLoc(), TU))) {
1943 return true;
1944 }
1945 continue;
1946 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001947 default: {
Ted Kremenek99394242010-11-12 22:24:57 +00001948 // FIXME: this entire switch stmt will eventually
1949 // go away.
1950 if (!isa<ExplicitCastExpr>(S)) {
1951 // Perform default visitation for other cases.
1952 if (Visit(Cursor))
1953 return true;
1954 continue;
1955 }
1956 // Fall-through.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001957 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001958 case Stmt::BinaryOperatorClass:
Ted Kremenek73d15c42010-11-13 01:09:29 +00001959 case Stmt::BlockExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001960 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001961 case Stmt::CaseStmtClass:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001962 case Stmt::CompoundLiteralExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001963 case Stmt::CompoundStmtClass:
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001964 case Stmt::CXXDefaultArgExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001965 case Stmt::CXXMemberCallExprClass:
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001966 case Stmt::CXXNewExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001967 case Stmt::CXXOperatorCallExprClass:
Ted Kremenek73d15c42010-11-13 01:09:29 +00001968 case Stmt::CXXTemporaryObjectExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001969 case Stmt::DefaultStmtClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001970 case Stmt::DoStmtClass:
1971 case Stmt::ForStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001972 case Stmt::IfStmtClass:
Ted Kremeneka6b70432010-11-12 21:34:09 +00001973 case Stmt::InitListExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001974 case Stmt::MemberExprClass:
Ted Kremenek73d15c42010-11-13 01:09:29 +00001975 case Stmt::ObjCEncodeExprClass:
Ted Kremenekc373e3c2010-11-12 22:24:55 +00001976 case Stmt::ObjCMessageExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001977 case Stmt::ParenExprClass:
1978 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00001979 case Stmt::UnaryOperatorClass:
Ted Kremenek60458782010-11-12 21:34:16 +00001980 case Stmt::UnresolvedLookupExprClass:
1981 case Stmt::UnresolvedMemberExprClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001982 case Stmt::WhileStmtClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001983 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001984 if (!IsInRegionOfInterest(Cursor))
1985 continue;
1986 switch (Visitor(Cursor, Parent, ClientData)) {
1987 case CXChildVisit_Break:
1988 return true;
1989 case CXChildVisit_Continue:
1990 break;
1991 case CXChildVisit_Recurse:
1992 EnqueueWorkList(WL, S);
1993 break;
1994 }
1995 }
1996 }
1997 continue;
1998 }
1999 case VisitorJob::MemberExprPartsKind: {
2000 // Handle the other pieces in the MemberExpr besides the base.
2001 MemberExpr *M = cast<MemberExprParts>(LI).get();
2002
2003 // Visit the nested-name-specifier
2004 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2005 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2006 return true;
2007
2008 // Visit the declaration name.
2009 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2010 return true;
2011
2012 // Visit the explicitly-specified template arguments, if any.
2013 if (M->hasExplicitTemplateArgs()) {
2014 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2015 *ArgEnd = Arg + M->getNumTemplateArgs();
2016 Arg != ArgEnd; ++Arg) {
2017 if (VisitTemplateArgumentLoc(*Arg))
2018 return true;
2019 }
2020 }
2021 continue;
2022 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002023 case VisitorJob::DeclRefExprPartsKind: {
2024 DeclRefExpr *DR = cast<DeclRefExprParts>(LI).get();
2025 // Visit nested-name-specifier, if present.
2026 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2027 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2028 return true;
2029 // Visit declaration name.
2030 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2031 return true;
2032 // Visit explicitly-specified template arguments.
2033 if (DR->hasExplicitTemplateArgs()) {
2034 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2035 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2036 *ArgEnd = Arg + Args.NumTemplateArgs;
2037 Arg != ArgEnd; ++Arg)
2038 if (VisitTemplateArgumentLoc(*Arg))
2039 return true;
2040 }
2041 continue;
2042 }
Ted Kremenek60458782010-11-12 21:34:16 +00002043 case VisitorJob::OverloadExprPartsKind: {
2044 OverloadExpr *O = cast<OverloadExprParts>(LI).get();
2045 // Visit the nested-name-specifier.
2046 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2047 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2048 return true;
2049 // Visit the declaration name.
2050 if (VisitDeclarationNameInfo(O->getNameInfo()))
2051 return true;
2052 // Visit the overloaded declaration reference.
2053 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2054 return true;
2055 // Visit the explicitly-specified template arguments.
2056 if (const ExplicitTemplateArgumentList *ArgList
2057 = O->getOptionalExplicitTemplateArgs()) {
2058 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2059 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2060 Arg != ArgEnd; ++Arg) {
2061 if (VisitTemplateArgumentLoc(*Arg))
2062 return true;
2063 }
2064 }
2065 continue;
2066 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002067 }
2068 }
2069 return false;
2070}
2071
2072bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2073 VisitorWorkList WL;
2074 EnqueueWorkList(WL, S);
2075 return RunVisitorWorkList(WL);
2076}
2077
2078//===----------------------------------------------------------------------===//
2079// Misc. API hooks.
2080//===----------------------------------------------------------------------===//
2081
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002082static llvm::sys::Mutex EnableMultithreadingMutex;
2083static bool EnabledMultithreading;
2084
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002085extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002086CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2087 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002088 // Disable pretty stack trace functionality, which will otherwise be a very
2089 // poor citizen of the world and set up all sorts of signal handlers.
2090 llvm::DisablePrettyStackTrace = true;
2091
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002092 // We use crash recovery to make some of our APIs more reliable, implicitly
2093 // enable it.
2094 llvm::CrashRecoveryContext::Enable();
2095
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002096 // Enable support for multithreading in LLVM.
2097 {
2098 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2099 if (!EnabledMultithreading) {
2100 llvm::llvm_start_multithreaded();
2101 EnabledMultithreading = true;
2102 }
2103 }
2104
Douglas Gregora030b7c2010-01-22 20:35:53 +00002105 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002106 if (excludeDeclarationsFromPCH)
2107 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002108 if (displayDiagnostics)
2109 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002110 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002111}
2112
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002113void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002114 if (CIdx)
2115 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002116}
2117
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002118CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002119 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002120 if (!CIdx)
2121 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002122
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002123 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002124 FileSystemOptions FileSystemOpts;
2125 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002126
Douglas Gregor28019772010-04-05 23:52:57 +00002127 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002128 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002129 CXXIdx->getOnlyLocalDecls(),
2130 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002131}
2132
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002133unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002134 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002135 CXTranslationUnit_CacheCompletionResults |
2136 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002137}
2138
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002139CXTranslationUnit
2140clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2141 const char *source_filename,
2142 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002143 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002144 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002145 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002146 return clang_parseTranslationUnit(CIdx, source_filename,
2147 command_line_args, num_command_line_args,
2148 unsaved_files, num_unsaved_files,
2149 CXTranslationUnit_DetailedPreprocessingRecord);
2150}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002151
2152struct ParseTranslationUnitInfo {
2153 CXIndex CIdx;
2154 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002155 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002156 int num_command_line_args;
2157 struct CXUnsavedFile *unsaved_files;
2158 unsigned num_unsaved_files;
2159 unsigned options;
2160 CXTranslationUnit result;
2161};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002162static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002163 ParseTranslationUnitInfo *PTUI =
2164 static_cast<ParseTranslationUnitInfo*>(UserData);
2165 CXIndex CIdx = PTUI->CIdx;
2166 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002167 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002168 int num_command_line_args = PTUI->num_command_line_args;
2169 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2170 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2171 unsigned options = PTUI->options;
2172 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002173
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002174 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002175 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002176
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002177 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2178
Douglas Gregor44c181a2010-07-23 00:33:23 +00002179 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002180 bool CompleteTranslationUnit
2181 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002182 bool CacheCodeCompetionResults
2183 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002184 bool CXXPrecompilePreamble
2185 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2186 bool CXXChainedPCH
2187 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002188
Douglas Gregor5352ac02010-01-28 00:27:43 +00002189 // Configure the diagnostics.
2190 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002191 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2192 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002193
Douglas Gregor4db64a42010-01-23 00:14:00 +00002194 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2195 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002196 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002197 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002198 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002199 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2200 Buffer));
2201 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
Douglas Gregorb10daed2010-10-11 16:52:23 +00002203 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002204
Ted Kremenek139ba862009-10-22 00:03:57 +00002205 // The 'source_filename' argument is optional. If the caller does not
2206 // specify it then it is assumed that the source file is specified
2207 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002208 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002209 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002210
2211 // Since the Clang C library is primarily used by batch tools dealing with
2212 // (often very broken) source code, where spell-checking can have a
2213 // significant negative impact on performance (particularly when
2214 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002215 // Only do this if we haven't found a spell-checking-related argument.
2216 bool FoundSpellCheckingArgument = false;
2217 for (int I = 0; I != num_command_line_args; ++I) {
2218 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2219 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2220 FoundSpellCheckingArgument = true;
2221 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002222 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002223 }
2224 if (!FoundSpellCheckingArgument)
2225 Args.push_back("-fno-spell-checking");
2226
2227 Args.insert(Args.end(), command_line_args,
2228 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002229
Douglas Gregor44c181a2010-07-23 00:33:23 +00002230 // Do we need the detailed preprocessing record?
2231 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002232 Args.push_back("-Xclang");
2233 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002234 }
2235
Douglas Gregorb10daed2010-10-11 16:52:23 +00002236 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002237 llvm::OwningPtr<ASTUnit> Unit(
2238 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2239 Diags,
2240 CXXIdx->getClangResourcesPath(),
2241 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002242 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002243 RemappedFiles.data(),
2244 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002245 PrecompilePreamble,
2246 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002247 CacheCodeCompetionResults,
2248 CXXPrecompilePreamble,
2249 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002250
Douglas Gregorb10daed2010-10-11 16:52:23 +00002251 if (NumErrors != Diags->getNumErrors()) {
2252 // Make sure to check that 'Unit' is non-NULL.
2253 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2254 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2255 DEnd = Unit->stored_diag_end();
2256 D != DEnd; ++D) {
2257 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2258 CXString Msg = clang_formatDiagnostic(&Diag,
2259 clang_defaultDiagnosticDisplayOptions());
2260 fprintf(stderr, "%s\n", clang_getCString(Msg));
2261 clang_disposeString(Msg);
2262 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002263#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002264 // On Windows, force a flush, since there may be multiple copies of
2265 // stderr and stdout in the file system, all with different buffers
2266 // but writing to the same device.
2267 fflush(stderr);
2268#endif
2269 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002270 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002271
Douglas Gregorb10daed2010-10-11 16:52:23 +00002272 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002273}
2274CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2275 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002276 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002277 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002278 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002279 unsigned num_unsaved_files,
2280 unsigned options) {
2281 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002282 num_command_line_args, unsaved_files,
2283 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002284 llvm::CrashRecoveryContext CRC;
2285
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002286 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002287 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2288 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2289 fprintf(stderr, " 'command_line_args' : [");
2290 for (int i = 0; i != num_command_line_args; ++i) {
2291 if (i)
2292 fprintf(stderr, ", ");
2293 fprintf(stderr, "'%s'", command_line_args[i]);
2294 }
2295 fprintf(stderr, "],\n");
2296 fprintf(stderr, " 'unsaved_files' : [");
2297 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2298 if (i)
2299 fprintf(stderr, ", ");
2300 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2301 unsaved_files[i].Length);
2302 }
2303 fprintf(stderr, "],\n");
2304 fprintf(stderr, " 'options' : %d,\n", options);
2305 fprintf(stderr, "}\n");
2306
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002307 return 0;
2308 }
2309
2310 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002311}
2312
Douglas Gregor19998442010-08-13 15:35:05 +00002313unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2314 return CXSaveTranslationUnit_None;
2315}
2316
2317int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2318 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002319 if (!TU)
2320 return 1;
2321
2322 return static_cast<ASTUnit *>(TU)->Save(FileName);
2323}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002324
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002325void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002326 if (CTUnit) {
2327 // If the translation unit has been marked as unsafe to free, just discard
2328 // it.
2329 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2330 return;
2331
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002332 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002333 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002334}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002335
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002336unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2337 return CXReparse_None;
2338}
2339
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002340struct ReparseTranslationUnitInfo {
2341 CXTranslationUnit TU;
2342 unsigned num_unsaved_files;
2343 struct CXUnsavedFile *unsaved_files;
2344 unsigned options;
2345 int result;
2346};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002347
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002348static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002349 ReparseTranslationUnitInfo *RTUI =
2350 static_cast<ReparseTranslationUnitInfo*>(UserData);
2351 CXTranslationUnit TU = RTUI->TU;
2352 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2353 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2354 unsigned options = RTUI->options;
2355 (void) options;
2356 RTUI->result = 1;
2357
Douglas Gregorabc563f2010-07-19 21:46:24 +00002358 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002359 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002360
2361 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2362 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002363
2364 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2365 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2366 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2367 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002368 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002369 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2370 Buffer));
2371 }
2372
Douglas Gregor593b0c12010-09-23 18:47:53 +00002373 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2374 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002375}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002376
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002377int clang_reparseTranslationUnit(CXTranslationUnit TU,
2378 unsigned num_unsaved_files,
2379 struct CXUnsavedFile *unsaved_files,
2380 unsigned options) {
2381 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2382 options, 0 };
2383 llvm::CrashRecoveryContext CRC;
2384
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002385 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002386 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002387 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2388 return 1;
2389 }
2390
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002391
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002392 return RTUI.result;
2393}
2394
Douglas Gregordf95a132010-08-09 20:45:32 +00002395
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002396CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002397 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002398 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002399
Steve Naroff77accc12009-09-03 18:19:54 +00002400 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002401 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002402}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002403
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002404CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002405 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002406 return Result;
2407}
2408
Ted Kremenekfb480492010-01-13 21:46:36 +00002409} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002410
Ted Kremenekfb480492010-01-13 21:46:36 +00002411//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002412// CXSourceLocation and CXSourceRange Operations.
2413//===----------------------------------------------------------------------===//
2414
Douglas Gregorb9790342010-01-22 21:44:22 +00002415extern "C" {
2416CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002417 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002418 return Result;
2419}
2420
2421unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002422 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2423 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2424 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002425}
2426
2427CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2428 CXFile file,
2429 unsigned line,
2430 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002431 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002432 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002433
Douglas Gregorb9790342010-01-22 21:44:22 +00002434 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2435 SourceLocation SLoc
2436 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002437 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002438 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002439 if (SLoc.isInvalid()) return clang_getNullLocation();
2440
2441 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2442}
2443
2444CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2445 CXFile file,
2446 unsigned offset) {
2447 if (!tu || !file)
2448 return clang_getNullLocation();
2449
2450 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2451 SourceLocation Start
2452 = CXXUnit->getSourceManager().getLocation(
2453 static_cast<const FileEntry *>(file),
2454 1, 1);
2455 if (Start.isInvalid()) return clang_getNullLocation();
2456
2457 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2458
2459 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002460
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002461 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002462}
2463
Douglas Gregor5352ac02010-01-28 00:27:43 +00002464CXSourceRange clang_getNullRange() {
2465 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2466 return Result;
2467}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002468
Douglas Gregor5352ac02010-01-28 00:27:43 +00002469CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2470 if (begin.ptr_data[0] != end.ptr_data[0] ||
2471 begin.ptr_data[1] != end.ptr_data[1])
2472 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002473
2474 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002475 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002476 return Result;
2477}
2478
Douglas Gregor46766dc2010-01-26 19:19:08 +00002479void clang_getInstantiationLocation(CXSourceLocation location,
2480 CXFile *file,
2481 unsigned *line,
2482 unsigned *column,
2483 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002484 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2485
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002486 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002487 if (file)
2488 *file = 0;
2489 if (line)
2490 *line = 0;
2491 if (column)
2492 *column = 0;
2493 if (offset)
2494 *offset = 0;
2495 return;
2496 }
2497
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002498 const SourceManager &SM =
2499 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002500 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002501
2502 if (file)
2503 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2504 if (line)
2505 *line = SM.getInstantiationLineNumber(InstLoc);
2506 if (column)
2507 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002508 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002509 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002510}
2511
Douglas Gregora9b06d42010-11-09 06:24:54 +00002512void clang_getSpellingLocation(CXSourceLocation location,
2513 CXFile *file,
2514 unsigned *line,
2515 unsigned *column,
2516 unsigned *offset) {
2517 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2518
2519 if (!location.ptr_data[0] || Loc.isInvalid()) {
2520 if (file)
2521 *file = 0;
2522 if (line)
2523 *line = 0;
2524 if (column)
2525 *column = 0;
2526 if (offset)
2527 *offset = 0;
2528 return;
2529 }
2530
2531 const SourceManager &SM =
2532 *static_cast<const SourceManager*>(location.ptr_data[0]);
2533 SourceLocation SpellLoc = Loc;
2534 if (SpellLoc.isMacroID()) {
2535 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2536 if (SimpleSpellingLoc.isFileID() &&
2537 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2538 SpellLoc = SimpleSpellingLoc;
2539 else
2540 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2541 }
2542
2543 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2544 FileID FID = LocInfo.first;
2545 unsigned FileOffset = LocInfo.second;
2546
2547 if (file)
2548 *file = (void *)SM.getFileEntryForID(FID);
2549 if (line)
2550 *line = SM.getLineNumber(FID, FileOffset);
2551 if (column)
2552 *column = SM.getColumnNumber(FID, FileOffset);
2553 if (offset)
2554 *offset = FileOffset;
2555}
2556
Douglas Gregor1db19de2010-01-19 21:36:55 +00002557CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002558 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002559 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002560 return Result;
2561}
2562
2563CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002564 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002565 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002566 return Result;
2567}
2568
Douglas Gregorb9790342010-01-22 21:44:22 +00002569} // end: extern "C"
2570
Douglas Gregor1db19de2010-01-19 21:36:55 +00002571//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002572// CXFile Operations.
2573//===----------------------------------------------------------------------===//
2574
2575extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002576CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002577 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002578 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002579
Steve Naroff88145032009-10-27 14:35:18 +00002580 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002581 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002582}
2583
2584time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002585 if (!SFile)
2586 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002587
Steve Naroff88145032009-10-27 14:35:18 +00002588 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2589 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002590}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002591
Douglas Gregorb9790342010-01-22 21:44:22 +00002592CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2593 if (!tu)
2594 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002595
Douglas Gregorb9790342010-01-22 21:44:22 +00002596 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002597
Douglas Gregorb9790342010-01-22 21:44:22 +00002598 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002599 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2600 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002601 return const_cast<FileEntry *>(File);
2602}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002603
Ted Kremenekfb480492010-01-13 21:46:36 +00002604} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002605
Ted Kremenekfb480492010-01-13 21:46:36 +00002606//===----------------------------------------------------------------------===//
2607// CXCursor Operations.
2608//===----------------------------------------------------------------------===//
2609
Ted Kremenekfb480492010-01-13 21:46:36 +00002610static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002611 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2612 return getDeclFromExpr(CE->getSubExpr());
2613
Ted Kremenekfb480492010-01-13 21:46:36 +00002614 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2615 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002616 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2617 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002618 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2619 return ME->getMemberDecl();
2620 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2621 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002622 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2623 return PRE->getProperty();
2624
Ted Kremenekfb480492010-01-13 21:46:36 +00002625 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2626 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002627 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2628 if (!CE->isElidable())
2629 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002630 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2631 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002632
Douglas Gregordb1314e2010-10-01 21:11:22 +00002633 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2634 return PE->getProtocol();
2635
Ted Kremenekfb480492010-01-13 21:46:36 +00002636 return 0;
2637}
2638
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002639static SourceLocation getLocationFromExpr(Expr *E) {
2640 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2641 return /*FIXME:*/Msg->getLeftLoc();
2642 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2643 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002644 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2645 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002646 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2647 return Member->getMemberLoc();
2648 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2649 return Ivar->getLocation();
2650 return E->getLocStart();
2651}
2652
Ted Kremenekfb480492010-01-13 21:46:36 +00002653extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002654
2655unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002656 CXCursorVisitor visitor,
2657 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002658 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002659
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002660 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2661 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002662 return CursorVis.VisitChildren(parent);
2663}
2664
David Chisnall3387c652010-11-03 14:12:26 +00002665#ifndef __has_feature
2666#define __has_feature(x) 0
2667#endif
2668#if __has_feature(blocks)
2669typedef enum CXChildVisitResult
2670 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2671
2672static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2673 CXClientData client_data) {
2674 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2675 return block(cursor, parent);
2676}
2677#else
2678// If we are compiled with a compiler that doesn't have native blocks support,
2679// define and call the block manually, so the
2680typedef struct _CXChildVisitResult
2681{
2682 void *isa;
2683 int flags;
2684 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002685 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2686 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002687} *CXCursorVisitorBlock;
2688
2689static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2690 CXClientData client_data) {
2691 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2692 return block->invoke(block, cursor, parent);
2693}
2694#endif
2695
2696
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002697unsigned clang_visitChildrenWithBlock(CXCursor parent,
2698 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002699 return clang_visitChildren(parent, visitWithBlock, block);
2700}
2701
Douglas Gregor78205d42010-01-20 21:45:58 +00002702static CXString getDeclSpelling(Decl *D) {
2703 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2704 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002705 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002706
Douglas Gregor78205d42010-01-20 21:45:58 +00002707 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002708 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002709
Douglas Gregor78205d42010-01-20 21:45:58 +00002710 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2711 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2712 // and returns different names. NamedDecl returns the class name and
2713 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002714 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002716 if (isa<UsingDirectiveDecl>(D))
2717 return createCXString("");
2718
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002719 llvm::SmallString<1024> S;
2720 llvm::raw_svector_ostream os(S);
2721 ND->printName(os);
2722
2723 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002724}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002725
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002726CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002727 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002728 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002729
Steve Narofff334b4e2009-09-02 18:26:48 +00002730 if (clang_isReference(C.kind)) {
2731 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002732 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002733 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002734 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002735 }
2736 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002737 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002738 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002739 }
2740 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002741 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002742 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002743 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002744 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002745 case CXCursor_CXXBaseSpecifier: {
2746 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2747 return createCXString(B->getType().getAsString());
2748 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002749 case CXCursor_TypeRef: {
2750 TypeDecl *Type = getCursorTypeRef(C).first;
2751 assert(Type && "Missing type decl");
2752
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002753 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2754 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002755 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002756 case CXCursor_TemplateRef: {
2757 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002758 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002759
2760 return createCXString(Template->getNameAsString());
2761 }
Douglas Gregor69319002010-08-31 23:48:11 +00002762
2763 case CXCursor_NamespaceRef: {
2764 NamedDecl *NS = getCursorNamespaceRef(C).first;
2765 assert(NS && "Missing namespace decl");
2766
2767 return createCXString(NS->getNameAsString());
2768 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002769
Douglas Gregora67e03f2010-09-09 21:42:20 +00002770 case CXCursor_MemberRef: {
2771 FieldDecl *Field = getCursorMemberRef(C).first;
2772 assert(Field && "Missing member decl");
2773
2774 return createCXString(Field->getNameAsString());
2775 }
2776
Douglas Gregor36897b02010-09-10 00:22:18 +00002777 case CXCursor_LabelRef: {
2778 LabelStmt *Label = getCursorLabelRef(C).first;
2779 assert(Label && "Missing label");
2780
2781 return createCXString(Label->getID()->getName());
2782 }
2783
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002784 case CXCursor_OverloadedDeclRef: {
2785 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2786 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2787 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2788 return createCXString(ND->getNameAsString());
2789 return createCXString("");
2790 }
2791 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2792 return createCXString(E->getName().getAsString());
2793 OverloadedTemplateStorage *Ovl
2794 = Storage.get<OverloadedTemplateStorage*>();
2795 if (Ovl->size() == 0)
2796 return createCXString("");
2797 return createCXString((*Ovl->begin())->getNameAsString());
2798 }
2799
Daniel Dunbaracca7252009-11-30 20:42:49 +00002800 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002801 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002802 }
2803 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002804
2805 if (clang_isExpression(C.kind)) {
2806 Decl *D = getDeclFromExpr(getCursorExpr(C));
2807 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002808 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002809 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002810 }
2811
Douglas Gregor36897b02010-09-10 00:22:18 +00002812 if (clang_isStatement(C.kind)) {
2813 Stmt *S = getCursorStmt(C);
2814 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2815 return createCXString(Label->getID()->getName());
2816
2817 return createCXString("");
2818 }
2819
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002820 if (C.kind == CXCursor_MacroInstantiation)
2821 return createCXString(getCursorMacroInstantiation(C)->getName()
2822 ->getNameStart());
2823
Douglas Gregor572feb22010-03-18 18:04:21 +00002824 if (C.kind == CXCursor_MacroDefinition)
2825 return createCXString(getCursorMacroDefinition(C)->getName()
2826 ->getNameStart());
2827
Douglas Gregorecdcb882010-10-20 22:00:55 +00002828 if (C.kind == CXCursor_InclusionDirective)
2829 return createCXString(getCursorInclusionDirective(C)->getFileName());
2830
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002831 if (clang_isDeclaration(C.kind))
2832 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002833
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002834 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002835}
2836
Douglas Gregor358559d2010-10-02 22:49:11 +00002837CXString clang_getCursorDisplayName(CXCursor C) {
2838 if (!clang_isDeclaration(C.kind))
2839 return clang_getCursorSpelling(C);
2840
2841 Decl *D = getCursorDecl(C);
2842 if (!D)
2843 return createCXString("");
2844
2845 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2846 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2847 D = FunTmpl->getTemplatedDecl();
2848
2849 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2850 llvm::SmallString<64> Str;
2851 llvm::raw_svector_ostream OS(Str);
2852 OS << Function->getNameAsString();
2853 if (Function->getPrimaryTemplate())
2854 OS << "<>";
2855 OS << "(";
2856 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2857 if (I)
2858 OS << ", ";
2859 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2860 }
2861
2862 if (Function->isVariadic()) {
2863 if (Function->getNumParams())
2864 OS << ", ";
2865 OS << "...";
2866 }
2867 OS << ")";
2868 return createCXString(OS.str());
2869 }
2870
2871 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2872 llvm::SmallString<64> Str;
2873 llvm::raw_svector_ostream OS(Str);
2874 OS << ClassTemplate->getNameAsString();
2875 OS << "<";
2876 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2877 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2878 if (I)
2879 OS << ", ";
2880
2881 NamedDecl *Param = Params->getParam(I);
2882 if (Param->getIdentifier()) {
2883 OS << Param->getIdentifier()->getName();
2884 continue;
2885 }
2886
2887 // There is no parameter name, which makes this tricky. Try to come up
2888 // with something useful that isn't too long.
2889 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2890 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2891 else if (NonTypeTemplateParmDecl *NTTP
2892 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2893 OS << NTTP->getType().getAsString(Policy);
2894 else
2895 OS << "template<...> class";
2896 }
2897
2898 OS << ">";
2899 return createCXString(OS.str());
2900 }
2901
2902 if (ClassTemplateSpecializationDecl *ClassSpec
2903 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2904 // If the type was explicitly written, use that.
2905 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2906 return createCXString(TSInfo->getType().getAsString(Policy));
2907
2908 llvm::SmallString<64> Str;
2909 llvm::raw_svector_ostream OS(Str);
2910 OS << ClassSpec->getNameAsString();
2911 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002912 ClassSpec->getTemplateArgs().data(),
2913 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002914 Policy);
2915 return createCXString(OS.str());
2916 }
2917
2918 return clang_getCursorSpelling(C);
2919}
2920
Ted Kremeneke68fff62010-02-17 00:41:32 +00002921CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002922 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002923 case CXCursor_FunctionDecl:
2924 return createCXString("FunctionDecl");
2925 case CXCursor_TypedefDecl:
2926 return createCXString("TypedefDecl");
2927 case CXCursor_EnumDecl:
2928 return createCXString("EnumDecl");
2929 case CXCursor_EnumConstantDecl:
2930 return createCXString("EnumConstantDecl");
2931 case CXCursor_StructDecl:
2932 return createCXString("StructDecl");
2933 case CXCursor_UnionDecl:
2934 return createCXString("UnionDecl");
2935 case CXCursor_ClassDecl:
2936 return createCXString("ClassDecl");
2937 case CXCursor_FieldDecl:
2938 return createCXString("FieldDecl");
2939 case CXCursor_VarDecl:
2940 return createCXString("VarDecl");
2941 case CXCursor_ParmDecl:
2942 return createCXString("ParmDecl");
2943 case CXCursor_ObjCInterfaceDecl:
2944 return createCXString("ObjCInterfaceDecl");
2945 case CXCursor_ObjCCategoryDecl:
2946 return createCXString("ObjCCategoryDecl");
2947 case CXCursor_ObjCProtocolDecl:
2948 return createCXString("ObjCProtocolDecl");
2949 case CXCursor_ObjCPropertyDecl:
2950 return createCXString("ObjCPropertyDecl");
2951 case CXCursor_ObjCIvarDecl:
2952 return createCXString("ObjCIvarDecl");
2953 case CXCursor_ObjCInstanceMethodDecl:
2954 return createCXString("ObjCInstanceMethodDecl");
2955 case CXCursor_ObjCClassMethodDecl:
2956 return createCXString("ObjCClassMethodDecl");
2957 case CXCursor_ObjCImplementationDecl:
2958 return createCXString("ObjCImplementationDecl");
2959 case CXCursor_ObjCCategoryImplDecl:
2960 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002961 case CXCursor_CXXMethod:
2962 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002963 case CXCursor_UnexposedDecl:
2964 return createCXString("UnexposedDecl");
2965 case CXCursor_ObjCSuperClassRef:
2966 return createCXString("ObjCSuperClassRef");
2967 case CXCursor_ObjCProtocolRef:
2968 return createCXString("ObjCProtocolRef");
2969 case CXCursor_ObjCClassRef:
2970 return createCXString("ObjCClassRef");
2971 case CXCursor_TypeRef:
2972 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002973 case CXCursor_TemplateRef:
2974 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002975 case CXCursor_NamespaceRef:
2976 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002977 case CXCursor_MemberRef:
2978 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002979 case CXCursor_LabelRef:
2980 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002981 case CXCursor_OverloadedDeclRef:
2982 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002983 case CXCursor_UnexposedExpr:
2984 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002985 case CXCursor_BlockExpr:
2986 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002987 case CXCursor_DeclRefExpr:
2988 return createCXString("DeclRefExpr");
2989 case CXCursor_MemberRefExpr:
2990 return createCXString("MemberRefExpr");
2991 case CXCursor_CallExpr:
2992 return createCXString("CallExpr");
2993 case CXCursor_ObjCMessageExpr:
2994 return createCXString("ObjCMessageExpr");
2995 case CXCursor_UnexposedStmt:
2996 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002997 case CXCursor_LabelStmt:
2998 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002999 case CXCursor_InvalidFile:
3000 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003001 case CXCursor_InvalidCode:
3002 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003003 case CXCursor_NoDeclFound:
3004 return createCXString("NoDeclFound");
3005 case CXCursor_NotImplemented:
3006 return createCXString("NotImplemented");
3007 case CXCursor_TranslationUnit:
3008 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003009 case CXCursor_UnexposedAttr:
3010 return createCXString("UnexposedAttr");
3011 case CXCursor_IBActionAttr:
3012 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003013 case CXCursor_IBOutletAttr:
3014 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003015 case CXCursor_IBOutletCollectionAttr:
3016 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003017 case CXCursor_PreprocessingDirective:
3018 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003019 case CXCursor_MacroDefinition:
3020 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003021 case CXCursor_MacroInstantiation:
3022 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003023 case CXCursor_InclusionDirective:
3024 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003025 case CXCursor_Namespace:
3026 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003027 case CXCursor_LinkageSpec:
3028 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003029 case CXCursor_CXXBaseSpecifier:
3030 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003031 case CXCursor_Constructor:
3032 return createCXString("CXXConstructor");
3033 case CXCursor_Destructor:
3034 return createCXString("CXXDestructor");
3035 case CXCursor_ConversionFunction:
3036 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003037 case CXCursor_TemplateTypeParameter:
3038 return createCXString("TemplateTypeParameter");
3039 case CXCursor_NonTypeTemplateParameter:
3040 return createCXString("NonTypeTemplateParameter");
3041 case CXCursor_TemplateTemplateParameter:
3042 return createCXString("TemplateTemplateParameter");
3043 case CXCursor_FunctionTemplate:
3044 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003045 case CXCursor_ClassTemplate:
3046 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003047 case CXCursor_ClassTemplatePartialSpecialization:
3048 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003049 case CXCursor_NamespaceAlias:
3050 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003051 case CXCursor_UsingDirective:
3052 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003053 case CXCursor_UsingDeclaration:
3054 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003055 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003056
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003057 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003058 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003059}
Steve Naroff89922f82009-08-31 00:59:03 +00003060
Ted Kremeneke68fff62010-02-17 00:41:32 +00003061enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3062 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003063 CXClientData client_data) {
3064 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003065
3066 // If our current best cursor is the construction of a temporary object,
3067 // don't replace that cursor with a type reference, because we want
3068 // clang_getCursor() to point at the constructor.
3069 if (clang_isExpression(BestCursor->kind) &&
3070 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3071 cursor.kind == CXCursor_TypeRef)
3072 return CXChildVisit_Recurse;
3073
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003074 *BestCursor = cursor;
3075 return CXChildVisit_Recurse;
3076}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003077
Douglas Gregorb9790342010-01-22 21:44:22 +00003078CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3079 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003080 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003081
Douglas Gregorb9790342010-01-22 21:44:22 +00003082 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003083 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3084
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003085 // Translate the given source location to make it point at the beginning of
3086 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003087 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003088
3089 // Guard against an invalid SourceLocation, or we may assert in one
3090 // of the following calls.
3091 if (SLoc.isInvalid())
3092 return clang_getNullCursor();
3093
Douglas Gregor40749ee2010-11-03 00:35:38 +00003094 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003095 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3096 CXXUnit->getASTContext().getLangOptions());
3097
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003098 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3099 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003100 // FIXME: Would be great to have a "hint" cursor, then walk from that
3101 // hint cursor upward until we find a cursor whose source range encloses
3102 // the region of interest, rather than starting from the translation unit.
3103 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003104 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003105 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003106 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003107 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003108
3109 if (Logging) {
3110 CXFile SearchFile;
3111 unsigned SearchLine, SearchColumn;
3112 CXFile ResultFile;
3113 unsigned ResultLine, ResultColumn;
3114 CXString SearchFileName, ResultFileName, KindSpelling;
3115 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3116
3117 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3118 0);
3119 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3120 &ResultColumn, 0);
3121 SearchFileName = clang_getFileName(SearchFile);
3122 ResultFileName = clang_getFileName(ResultFile);
3123 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3124 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3125 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3126 clang_getCString(KindSpelling),
3127 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3128 clang_disposeString(SearchFileName);
3129 clang_disposeString(ResultFileName);
3130 clang_disposeString(KindSpelling);
3131 }
3132
Ted Kremeneke68fff62010-02-17 00:41:32 +00003133 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003134}
3135
Ted Kremenek73885552009-11-17 19:28:59 +00003136CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003137 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003138}
3139
3140unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003141 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003142}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003143
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003144unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003145 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3146}
3147
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003148unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003149 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3150}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003151
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003152unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003153 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3154}
3155
Douglas Gregor97b98722010-01-19 23:20:36 +00003156unsigned clang_isExpression(enum CXCursorKind K) {
3157 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3158}
3159
3160unsigned clang_isStatement(enum CXCursorKind K) {
3161 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3162}
3163
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003164unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3165 return K == CXCursor_TranslationUnit;
3166}
3167
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003168unsigned clang_isPreprocessing(enum CXCursorKind K) {
3169 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3170}
3171
Ted Kremenekad6eff62010-03-08 21:17:29 +00003172unsigned clang_isUnexposed(enum CXCursorKind K) {
3173 switch (K) {
3174 case CXCursor_UnexposedDecl:
3175 case CXCursor_UnexposedExpr:
3176 case CXCursor_UnexposedStmt:
3177 case CXCursor_UnexposedAttr:
3178 return true;
3179 default:
3180 return false;
3181 }
3182}
3183
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003184CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003185 return C.kind;
3186}
3187
Douglas Gregor98258af2010-01-18 22:46:11 +00003188CXSourceLocation clang_getCursorLocation(CXCursor C) {
3189 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003190 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003191 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003192 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3193 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003194 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003195 }
3196
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003197 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003198 std::pair<ObjCProtocolDecl *, SourceLocation> P
3199 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003200 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003201 }
3202
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003203 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003204 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3205 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003206 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003207 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003208
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003209 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003210 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003211 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003212 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003213
3214 case CXCursor_TemplateRef: {
3215 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3216 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3217 }
3218
Douglas Gregor69319002010-08-31 23:48:11 +00003219 case CXCursor_NamespaceRef: {
3220 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3221 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3222 }
3223
Douglas Gregora67e03f2010-09-09 21:42:20 +00003224 case CXCursor_MemberRef: {
3225 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3226 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3227 }
3228
Ted Kremenek3064ef92010-08-27 21:34:58 +00003229 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003230 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3231 if (!BaseSpec)
3232 return clang_getNullLocation();
3233
3234 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3235 return cxloc::translateSourceLocation(getCursorContext(C),
3236 TSInfo->getTypeLoc().getBeginLoc());
3237
3238 return cxloc::translateSourceLocation(getCursorContext(C),
3239 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003240 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003241
Douglas Gregor36897b02010-09-10 00:22:18 +00003242 case CXCursor_LabelRef: {
3243 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3244 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3245 }
3246
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003247 case CXCursor_OverloadedDeclRef:
3248 return cxloc::translateSourceLocation(getCursorContext(C),
3249 getCursorOverloadedDeclRef(C).second);
3250
Douglas Gregorf46034a2010-01-18 23:41:10 +00003251 default:
3252 // FIXME: Need a way to enumerate all non-reference cases.
3253 llvm_unreachable("Missed a reference kind");
3254 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003255 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003256
3257 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003258 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003259 getLocationFromExpr(getCursorExpr(C)));
3260
Douglas Gregor36897b02010-09-10 00:22:18 +00003261 if (clang_isStatement(C.kind))
3262 return cxloc::translateSourceLocation(getCursorContext(C),
3263 getCursorStmt(C)->getLocStart());
3264
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003265 if (C.kind == CXCursor_PreprocessingDirective) {
3266 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3267 return cxloc::translateSourceLocation(getCursorContext(C), L);
3268 }
Douglas Gregor48072312010-03-18 15:23:44 +00003269
3270 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003271 SourceLocation L
3272 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003273 return cxloc::translateSourceLocation(getCursorContext(C), L);
3274 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003275
3276 if (C.kind == CXCursor_MacroDefinition) {
3277 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3278 return cxloc::translateSourceLocation(getCursorContext(C), L);
3279 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003280
3281 if (C.kind == CXCursor_InclusionDirective) {
3282 SourceLocation L
3283 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3284 return cxloc::translateSourceLocation(getCursorContext(C), L);
3285 }
3286
Ted Kremenek9a700d22010-05-12 06:16:13 +00003287 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003288 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003289
Douglas Gregorf46034a2010-01-18 23:41:10 +00003290 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003291 SourceLocation Loc = D->getLocation();
3292 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3293 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003294 // FIXME: Multiple variables declared in a single declaration
3295 // currently lack the information needed to correctly determine their
3296 // ranges when accounting for the type-specifier. We use context
3297 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3298 // and if so, whether it is the first decl.
3299 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3300 if (!cxcursor::isFirstInDeclGroup(C))
3301 Loc = VD->getLocation();
3302 }
3303
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003304 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003305}
Douglas Gregora7bde202010-01-19 00:34:46 +00003306
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003307} // end extern "C"
3308
3309static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003310 if (clang_isReference(C.kind)) {
3311 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003312 case CXCursor_ObjCSuperClassRef:
3313 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003314
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003315 case CXCursor_ObjCProtocolRef:
3316 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003317
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003318 case CXCursor_ObjCClassRef:
3319 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003320
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003321 case CXCursor_TypeRef:
3322 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003323
3324 case CXCursor_TemplateRef:
3325 return getCursorTemplateRef(C).second;
3326
Douglas Gregor69319002010-08-31 23:48:11 +00003327 case CXCursor_NamespaceRef:
3328 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003329
3330 case CXCursor_MemberRef:
3331 return getCursorMemberRef(C).second;
3332
Ted Kremenek3064ef92010-08-27 21:34:58 +00003333 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003334 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003335
Douglas Gregor36897b02010-09-10 00:22:18 +00003336 case CXCursor_LabelRef:
3337 return getCursorLabelRef(C).second;
3338
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003339 case CXCursor_OverloadedDeclRef:
3340 return getCursorOverloadedDeclRef(C).second;
3341
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003342 default:
3343 // FIXME: Need a way to enumerate all non-reference cases.
3344 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003345 }
3346 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003347
3348 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003349 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003350
3351 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003352 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003353
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003354 if (C.kind == CXCursor_PreprocessingDirective)
3355 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003357 if (C.kind == CXCursor_MacroInstantiation)
3358 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003359
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003360 if (C.kind == CXCursor_MacroDefinition)
3361 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003362
3363 if (C.kind == CXCursor_InclusionDirective)
3364 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3365
Ted Kremenek007a7c92010-11-01 23:26:51 +00003366 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3367 Decl *D = cxcursor::getCursorDecl(C);
3368 SourceRange R = D->getSourceRange();
3369 // FIXME: Multiple variables declared in a single declaration
3370 // currently lack the information needed to correctly determine their
3371 // ranges when accounting for the type-specifier. We use context
3372 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3373 // and if so, whether it is the first decl.
3374 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3375 if (!cxcursor::isFirstInDeclGroup(C))
3376 R.setBegin(VD->getLocation());
3377 }
3378 return R;
3379 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003380 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003381
3382extern "C" {
3383
3384CXSourceRange clang_getCursorExtent(CXCursor C) {
3385 SourceRange R = getRawCursorExtent(C);
3386 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003387 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003388
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003389 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003390}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003391
3392CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003393 if (clang_isInvalid(C.kind))
3394 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003395
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003396 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003397 if (clang_isDeclaration(C.kind)) {
3398 Decl *D = getCursorDecl(C);
3399 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3400 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3401 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3402 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3403 if (ObjCForwardProtocolDecl *Protocols
3404 = dyn_cast<ObjCForwardProtocolDecl>(D))
3405 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3406
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003407 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003408 }
3409
Douglas Gregor97b98722010-01-19 23:20:36 +00003410 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003411 Expr *E = getCursorExpr(C);
3412 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003413 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003414 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003415
3416 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3417 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3418
Douglas Gregor97b98722010-01-19 23:20:36 +00003419 return clang_getNullCursor();
3420 }
3421
Douglas Gregor36897b02010-09-10 00:22:18 +00003422 if (clang_isStatement(C.kind)) {
3423 Stmt *S = getCursorStmt(C);
3424 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3425 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3426 getCursorASTUnit(C));
3427
3428 return clang_getNullCursor();
3429 }
3430
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003431 if (C.kind == CXCursor_MacroInstantiation) {
3432 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3433 return MakeMacroDefinitionCursor(Def, CXXUnit);
3434 }
3435
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003436 if (!clang_isReference(C.kind))
3437 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003439 switch (C.kind) {
3440 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003441 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003442
3443 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003444 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003445
3446 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003447 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003448
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003449 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003450 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003451
3452 case CXCursor_TemplateRef:
3453 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3454
Douglas Gregor69319002010-08-31 23:48:11 +00003455 case CXCursor_NamespaceRef:
3456 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3457
Douglas Gregora67e03f2010-09-09 21:42:20 +00003458 case CXCursor_MemberRef:
3459 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3460
Ted Kremenek3064ef92010-08-27 21:34:58 +00003461 case CXCursor_CXXBaseSpecifier: {
3462 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3463 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3464 CXXUnit));
3465 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003466
Douglas Gregor36897b02010-09-10 00:22:18 +00003467 case CXCursor_LabelRef:
3468 // FIXME: We end up faking the "parent" declaration here because we
3469 // don't want to make CXCursor larger.
3470 return MakeCXCursor(getCursorLabelRef(C).first,
3471 CXXUnit->getASTContext().getTranslationUnitDecl(),
3472 CXXUnit);
3473
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003474 case CXCursor_OverloadedDeclRef:
3475 return C;
3476
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003477 default:
3478 // We would prefer to enumerate all non-reference cursor kinds here.
3479 llvm_unreachable("Unhandled reference cursor kind");
3480 break;
3481 }
3482 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003483
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003484 return clang_getNullCursor();
3485}
3486
Douglas Gregorb6998662010-01-19 19:34:47 +00003487CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003488 if (clang_isInvalid(C.kind))
3489 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003490
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003491 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003492
Douglas Gregorb6998662010-01-19 19:34:47 +00003493 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003494 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003495 C = clang_getCursorReferenced(C);
3496 WasReference = true;
3497 }
3498
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003499 if (C.kind == CXCursor_MacroInstantiation)
3500 return clang_getCursorReferenced(C);
3501
Douglas Gregorb6998662010-01-19 19:34:47 +00003502 if (!clang_isDeclaration(C.kind))
3503 return clang_getNullCursor();
3504
3505 Decl *D = getCursorDecl(C);
3506 if (!D)
3507 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003508
Douglas Gregorb6998662010-01-19 19:34:47 +00003509 switch (D->getKind()) {
3510 // Declaration kinds that don't really separate the notions of
3511 // declaration and definition.
3512 case Decl::Namespace:
3513 case Decl::Typedef:
3514 case Decl::TemplateTypeParm:
3515 case Decl::EnumConstant:
3516 case Decl::Field:
3517 case Decl::ObjCIvar:
3518 case Decl::ObjCAtDefsField:
3519 case Decl::ImplicitParam:
3520 case Decl::ParmVar:
3521 case Decl::NonTypeTemplateParm:
3522 case Decl::TemplateTemplateParm:
3523 case Decl::ObjCCategoryImpl:
3524 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003525 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003526 case Decl::LinkageSpec:
3527 case Decl::ObjCPropertyImpl:
3528 case Decl::FileScopeAsm:
3529 case Decl::StaticAssert:
3530 case Decl::Block:
3531 return C;
3532
3533 // Declaration kinds that don't make any sense here, but are
3534 // nonetheless harmless.
3535 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003536 break;
3537
3538 // Declaration kinds for which the definition is not resolvable.
3539 case Decl::UnresolvedUsingTypename:
3540 case Decl::UnresolvedUsingValue:
3541 break;
3542
3543 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003544 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3545 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003546
3547 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003548 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003549
3550 case Decl::Enum:
3551 case Decl::Record:
3552 case Decl::CXXRecord:
3553 case Decl::ClassTemplateSpecialization:
3554 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003555 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003556 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003557 return clang_getNullCursor();
3558
3559 case Decl::Function:
3560 case Decl::CXXMethod:
3561 case Decl::CXXConstructor:
3562 case Decl::CXXDestructor:
3563 case Decl::CXXConversion: {
3564 const FunctionDecl *Def = 0;
3565 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003566 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003567 return clang_getNullCursor();
3568 }
3569
3570 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003571 // Ask the variable if it has a definition.
3572 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3573 return MakeCXCursor(Def, CXXUnit);
3574 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003575 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003576
Douglas Gregorb6998662010-01-19 19:34:47 +00003577 case Decl::FunctionTemplate: {
3578 const FunctionDecl *Def = 0;
3579 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003580 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003581 return clang_getNullCursor();
3582 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003583
Douglas Gregorb6998662010-01-19 19:34:47 +00003584 case Decl::ClassTemplate: {
3585 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003586 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003587 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003588 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003589 return clang_getNullCursor();
3590 }
3591
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003592 case Decl::Using:
3593 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3594 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003595
3596 case Decl::UsingShadow:
3597 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003598 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003599 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003600
3601 case Decl::ObjCMethod: {
3602 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3603 if (Method->isThisDeclarationADefinition())
3604 return C;
3605
3606 // Dig out the method definition in the associated
3607 // @implementation, if we have it.
3608 // FIXME: The ASTs should make finding the definition easier.
3609 if (ObjCInterfaceDecl *Class
3610 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3611 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3612 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3613 Method->isInstanceMethod()))
3614 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003615 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003616
3617 return clang_getNullCursor();
3618 }
3619
3620 case Decl::ObjCCategory:
3621 if (ObjCCategoryImplDecl *Impl
3622 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003623 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003624 return clang_getNullCursor();
3625
3626 case Decl::ObjCProtocol:
3627 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3628 return C;
3629 return clang_getNullCursor();
3630
3631 case Decl::ObjCInterface:
3632 // There are two notions of a "definition" for an Objective-C
3633 // class: the interface and its implementation. When we resolved a
3634 // reference to an Objective-C class, produce the @interface as
3635 // the definition; when we were provided with the interface,
3636 // produce the @implementation as the definition.
3637 if (WasReference) {
3638 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3639 return C;
3640 } else if (ObjCImplementationDecl *Impl
3641 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003642 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003643 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003644
Douglas Gregorb6998662010-01-19 19:34:47 +00003645 case Decl::ObjCProperty:
3646 // FIXME: We don't really know where to find the
3647 // ObjCPropertyImplDecls that implement this property.
3648 return clang_getNullCursor();
3649
3650 case Decl::ObjCCompatibleAlias:
3651 if (ObjCInterfaceDecl *Class
3652 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3653 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003654 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003655
Douglas Gregorb6998662010-01-19 19:34:47 +00003656 return clang_getNullCursor();
3657
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003658 case Decl::ObjCForwardProtocol:
3659 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3660 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003661
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003662 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003663 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003664 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003665
3666 case Decl::Friend:
3667 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003668 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003669 return clang_getNullCursor();
3670
3671 case Decl::FriendTemplate:
3672 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003673 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003674 return clang_getNullCursor();
3675 }
3676
3677 return clang_getNullCursor();
3678}
3679
3680unsigned clang_isCursorDefinition(CXCursor C) {
3681 if (!clang_isDeclaration(C.kind))
3682 return 0;
3683
3684 return clang_getCursorDefinition(C) == C;
3685}
3686
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003687unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003688 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003689 return 0;
3690
3691 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3692 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3693 return E->getNumDecls();
3694
3695 if (OverloadedTemplateStorage *S
3696 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3697 return S->size();
3698
3699 Decl *D = Storage.get<Decl*>();
3700 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003701 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003702 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3703 return Classes->size();
3704 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3705 return Protocols->protocol_size();
3706
3707 return 0;
3708}
3709
3710CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003711 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003712 return clang_getNullCursor();
3713
3714 if (index >= clang_getNumOverloadedDecls(cursor))
3715 return clang_getNullCursor();
3716
3717 ASTUnit *Unit = getCursorASTUnit(cursor);
3718 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3719 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3720 return MakeCXCursor(E->decls_begin()[index], Unit);
3721
3722 if (OverloadedTemplateStorage *S
3723 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3724 return MakeCXCursor(S->begin()[index], Unit);
3725
3726 Decl *D = Storage.get<Decl*>();
3727 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3728 // FIXME: This is, unfortunately, linear time.
3729 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3730 std::advance(Pos, index);
3731 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3732 }
3733
3734 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3735 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3736
3737 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3738 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3739
3740 return clang_getNullCursor();
3741}
3742
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003743void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003744 const char **startBuf,
3745 const char **endBuf,
3746 unsigned *startLine,
3747 unsigned *startColumn,
3748 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003749 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003750 assert(getCursorDecl(C) && "CXCursor has null decl");
3751 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003752 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3753 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003754
Steve Naroff4ade6d62009-09-23 17:52:52 +00003755 SourceManager &SM = FD->getASTContext().getSourceManager();
3756 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3757 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3758 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3759 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3760 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3761 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3762}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003763
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003764void clang_enableStackTraces(void) {
3765 llvm::sys::PrintStackTraceOnErrorSignal();
3766}
3767
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003768void clang_executeOnThread(void (*fn)(void*), void *user_data,
3769 unsigned stack_size) {
3770 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3771}
3772
Ted Kremenekfb480492010-01-13 21:46:36 +00003773} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003774
Ted Kremenekfb480492010-01-13 21:46:36 +00003775//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003776// Token-based Operations.
3777//===----------------------------------------------------------------------===//
3778
3779/* CXToken layout:
3780 * int_data[0]: a CXTokenKind
3781 * int_data[1]: starting token location
3782 * int_data[2]: token length
3783 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003784 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003785 * otherwise unused.
3786 */
3787extern "C" {
3788
3789CXTokenKind clang_getTokenKind(CXToken CXTok) {
3790 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3791}
3792
3793CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3794 switch (clang_getTokenKind(CXTok)) {
3795 case CXToken_Identifier:
3796 case CXToken_Keyword:
3797 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003798 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3799 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003800
3801 case CXToken_Literal: {
3802 // We have stashed the starting pointer in the ptr_data field. Use it.
3803 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003804 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003805 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 case CXToken_Punctuation:
3808 case CXToken_Comment:
3809 break;
3810 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003811
3812 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003813 // deconstructing the source location.
3814 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3815 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003816 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003817
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003818 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3819 std::pair<FileID, unsigned> LocInfo
3820 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003821 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003822 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003823 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3824 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003825 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003826
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003827 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003828}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003829
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003830CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3831 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3832 if (!CXXUnit)
3833 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003834
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003835 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3836 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3837}
3838
3839CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3840 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003841 if (!CXXUnit)
3842 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
3844 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003845 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3846}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003848void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3849 CXToken **Tokens, unsigned *NumTokens) {
3850 if (Tokens)
3851 *Tokens = 0;
3852 if (NumTokens)
3853 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003854
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3856 if (!CXXUnit || !Tokens || !NumTokens)
3857 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregorbdf60622010-03-05 21:16:25 +00003859 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3860
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003861 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003862 if (R.isInvalid())
3863 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003864
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003865 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3866 std::pair<FileID, unsigned> BeginLocInfo
3867 = SourceMgr.getDecomposedLoc(R.getBegin());
3868 std::pair<FileID, unsigned> EndLocInfo
3869 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003870
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003871 // Cannot tokenize across files.
3872 if (BeginLocInfo.first != EndLocInfo.first)
3873 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003874
3875 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003876 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003877 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003878 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003879 if (Invalid)
3880 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003881
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003882 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3883 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003884 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003885 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003886
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003887 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003888 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003889 llvm::SmallVector<CXToken, 32> CXTokens;
3890 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003891 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003892 do {
3893 // Lex the next token
3894 Lex.LexFromRawLexer(Tok);
3895 if (Tok.is(tok::eof))
3896 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003897
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003898 // Initialize the CXToken.
3899 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003900
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003901 // - Common fields
3902 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3903 CXTok.int_data[2] = Tok.getLength();
3904 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003905
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003906 // - Kind-specific fields
3907 if (Tok.isLiteral()) {
3908 CXTok.int_data[0] = CXToken_Literal;
3909 CXTok.ptr_data = (void *)Tok.getLiteralData();
3910 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003911 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003912 std::pair<FileID, unsigned> LocInfo
3913 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003914 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003915 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003916 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3917 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003918 return;
3919
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003920 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003921 IdentifierInfo *II
3922 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003923
David Chisnall096428b2010-10-13 21:44:48 +00003924 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003925 CXTok.int_data[0] = CXToken_Keyword;
3926 }
3927 else {
3928 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3929 CXToken_Identifier
3930 : CXToken_Keyword;
3931 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003932 CXTok.ptr_data = II;
3933 } else if (Tok.is(tok::comment)) {
3934 CXTok.int_data[0] = CXToken_Comment;
3935 CXTok.ptr_data = 0;
3936 } else {
3937 CXTok.int_data[0] = CXToken_Punctuation;
3938 CXTok.ptr_data = 0;
3939 }
3940 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003941 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003942 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003943
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003944 if (CXTokens.empty())
3945 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003946
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003947 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3948 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3949 *NumTokens = CXTokens.size();
3950}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003951
Ted Kremenek6db61092010-05-05 00:55:15 +00003952void clang_disposeTokens(CXTranslationUnit TU,
3953 CXToken *Tokens, unsigned NumTokens) {
3954 free(Tokens);
3955}
3956
3957} // end: extern "C"
3958
3959//===----------------------------------------------------------------------===//
3960// Token annotation APIs.
3961//===----------------------------------------------------------------------===//
3962
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003963typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003964static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3965 CXCursor parent,
3966 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003967namespace {
3968class AnnotateTokensWorker {
3969 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003970 CXToken *Tokens;
3971 CXCursor *Cursors;
3972 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003973 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003974 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003975 CursorVisitor AnnotateVis;
3976 SourceManager &SrcMgr;
3977
3978 bool MoreTokens() const { return TokIdx < NumTokens; }
3979 unsigned NextToken() const { return TokIdx; }
3980 void AdvanceToken() { ++TokIdx; }
3981 SourceLocation GetTokenLoc(unsigned tokI) {
3982 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3983 }
3984
Ted Kremenek6db61092010-05-05 00:55:15 +00003985public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003986 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003987 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3988 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003989 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003990 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003991 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3992 Decl::MaxPCHLevel, RegionOfInterest),
3993 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003994
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003995 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003996 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003997 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003998 void AnnotateTokens() {
3999 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
4000 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004001};
4002}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004003
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4005 // Walk the AST within the region of interest, annotating tokens
4006 // along the way.
4007 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004008
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004009 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4010 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004011 if (Pos != Annotated.end() &&
4012 (clang_isInvalid(Cursors[I].kind) ||
4013 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004014 Cursors[I] = Pos->second;
4015 }
4016
4017 // Finish up annotating any tokens left.
4018 if (!MoreTokens())
4019 return;
4020
4021 const CXCursor &C = clang_getNullCursor();
4022 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4023 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4024 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004025 }
4026}
4027
Ted Kremenek6db61092010-05-05 00:55:15 +00004028enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004029AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004030 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004031 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004032 if (cursorRange.isInvalid())
4033 return CXChildVisit_Recurse;
4034
Douglas Gregor4419b672010-10-21 06:10:04 +00004035 if (clang_isPreprocessing(cursor.kind)) {
4036 // For macro instantiations, just note where the beginning of the macro
4037 // instantiation occurs.
4038 if (cursor.kind == CXCursor_MacroInstantiation) {
4039 Annotated[Loc.int_data] = cursor;
4040 return CXChildVisit_Recurse;
4041 }
4042
Douglas Gregor4419b672010-10-21 06:10:04 +00004043 // Items in the preprocessing record are kept separate from items in
4044 // declarations, so we keep a separate token index.
4045 unsigned SavedTokIdx = TokIdx;
4046 TokIdx = PreprocessingTokIdx;
4047
4048 // Skip tokens up until we catch up to the beginning of the preprocessing
4049 // entry.
4050 while (MoreTokens()) {
4051 const unsigned I = NextToken();
4052 SourceLocation TokLoc = GetTokenLoc(I);
4053 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4054 case RangeBefore:
4055 AdvanceToken();
4056 continue;
4057 case RangeAfter:
4058 case RangeOverlap:
4059 break;
4060 }
4061 break;
4062 }
4063
4064 // Look at all of the tokens within this range.
4065 while (MoreTokens()) {
4066 const unsigned I = NextToken();
4067 SourceLocation TokLoc = GetTokenLoc(I);
4068 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4069 case RangeBefore:
4070 assert(0 && "Infeasible");
4071 case RangeAfter:
4072 break;
4073 case RangeOverlap:
4074 Cursors[I] = cursor;
4075 AdvanceToken();
4076 continue;
4077 }
4078 break;
4079 }
4080
4081 // Save the preprocessing token index; restore the non-preprocessing
4082 // token index.
4083 PreprocessingTokIdx = TokIdx;
4084 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004085 return CXChildVisit_Recurse;
4086 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004087
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004088 if (cursorRange.isInvalid())
4089 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004090
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004091 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4092
Ted Kremeneka333c662010-05-12 05:29:33 +00004093 // Adjust the annotated range based specific declarations.
4094 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4095 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004096 Decl *D = cxcursor::getCursorDecl(cursor);
4097 // Don't visit synthesized ObjC methods, since they have no syntatic
4098 // representation in the source.
4099 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4100 if (MD->isSynthesized())
4101 return CXChildVisit_Continue;
4102 }
4103 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004104 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4105 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004106 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004107 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004108 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004109 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004110 }
4111 }
4112 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004113
Ted Kremenek3f404602010-08-14 01:14:06 +00004114 // If the location of the cursor occurs within a macro instantiation, record
4115 // the spelling location of the cursor in our annotation map. We can then
4116 // paper over the token labelings during a post-processing step to try and
4117 // get cursor mappings for tokens that are the *arguments* of a macro
4118 // instantiation.
4119 if (L.isMacroID()) {
4120 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4121 // Only invalidate the old annotation if it isn't part of a preprocessing
4122 // directive. Here we assume that the default construction of CXCursor
4123 // results in CXCursor.kind being an initialized value (i.e., 0). If
4124 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004125
Ted Kremenek3f404602010-08-14 01:14:06 +00004126 CXCursor &oldC = Annotated[rawEncoding];
4127 if (!clang_isPreprocessing(oldC.kind))
4128 oldC = cursor;
4129 }
4130
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004131 const enum CXCursorKind K = clang_getCursorKind(parent);
4132 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004133 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4134 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004135
4136 while (MoreTokens()) {
4137 const unsigned I = NextToken();
4138 SourceLocation TokLoc = GetTokenLoc(I);
4139 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4140 case RangeBefore:
4141 Cursors[I] = updateC;
4142 AdvanceToken();
4143 continue;
4144 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004145 case RangeOverlap:
4146 break;
4147 }
4148 break;
4149 }
4150
4151 // Visit children to get their cursor information.
4152 const unsigned BeforeChildren = NextToken();
4153 VisitChildren(cursor);
4154 const unsigned AfterChildren = NextToken();
4155
4156 // Adjust 'Last' to the last token within the extent of the cursor.
4157 while (MoreTokens()) {
4158 const unsigned I = NextToken();
4159 SourceLocation TokLoc = GetTokenLoc(I);
4160 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4161 case RangeBefore:
4162 assert(0 && "Infeasible");
4163 case RangeAfter:
4164 break;
4165 case RangeOverlap:
4166 Cursors[I] = updateC;
4167 AdvanceToken();
4168 continue;
4169 }
4170 break;
4171 }
4172 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004173
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004174 // Scan the tokens that are at the beginning of the cursor, but are not
4175 // capture by the child cursors.
4176
4177 // For AST elements within macros, rely on a post-annotate pass to
4178 // to correctly annotate the tokens with cursors. Otherwise we can
4179 // get confusing results of having tokens that map to cursors that really
4180 // are expanded by an instantiation.
4181 if (L.isMacroID())
4182 cursor = clang_getNullCursor();
4183
4184 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4185 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4186 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004187
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004188 Cursors[I] = cursor;
4189 }
4190 // Scan the tokens that are at the end of the cursor, but are not captured
4191 // but the child cursors.
4192 for (unsigned I = AfterChildren; I != Last; ++I)
4193 Cursors[I] = cursor;
4194
4195 TokIdx = Last;
4196 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004197}
4198
Ted Kremenek6db61092010-05-05 00:55:15 +00004199static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4200 CXCursor parent,
4201 CXClientData client_data) {
4202 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4203}
4204
Ted Kremenekab979612010-11-11 08:05:23 +00004205// This gets run a separate thread to avoid stack blowout.
4206static void runAnnotateTokensWorker(void *UserData) {
4207 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4208}
4209
Ted Kremenek6db61092010-05-05 00:55:15 +00004210extern "C" {
4211
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004212void clang_annotateTokens(CXTranslationUnit TU,
4213 CXToken *Tokens, unsigned NumTokens,
4214 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004215
4216 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004217 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004218
Douglas Gregor4419b672010-10-21 06:10:04 +00004219 // Any token we don't specifically annotate will have a NULL cursor.
4220 CXCursor C = clang_getNullCursor();
4221 for (unsigned I = 0; I != NumTokens; ++I)
4222 Cursors[I] = C;
4223
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004224 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004225 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004226 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227
Douglas Gregorbdf60622010-03-05 21:16:25 +00004228 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229
Douglas Gregor0396f462010-03-19 05:22:59 +00004230 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004231 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4233 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004234 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4235 clang_getTokenLocation(TU,
4236 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004237
Douglas Gregor0396f462010-03-19 05:22:59 +00004238 // A mapping from the source locations found when re-lexing or traversing the
4239 // region of interest to the corresponding cursors.
4240 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004241
4242 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004243 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004244 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4245 std::pair<FileID, unsigned> BeginLocInfo
4246 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4247 std::pair<FileID, unsigned> EndLocInfo
4248 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004249
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004250 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004251 bool Invalid = false;
4252 if (BeginLocInfo.first == EndLocInfo.first &&
4253 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4254 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004255 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4256 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004257 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004258 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004259 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004260
4261 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004262 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004263 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004264 Token Tok;
4265 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004266
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004267 reprocess:
4268 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4269 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004270 // don't see it while preprocessing these tokens later, but keep track
4271 // of all of the token locations inside this preprocessing directive so
4272 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004273 //
4274 // FIXME: Some simple tests here could identify macro definitions and
4275 // #undefs, to provide specific cursor kinds for those.
4276 std::vector<SourceLocation> Locations;
4277 do {
4278 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004280 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004281
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004282 using namespace cxcursor;
4283 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004284 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4285 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004286 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004287 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4288 Annotated[Locations[I].getRawEncoding()] = Cursor;
4289 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004290
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004291 if (Tok.isAtStartOfLine())
4292 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004293
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004294 continue;
4295 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004296
Douglas Gregor48072312010-03-18 15:23:44 +00004297 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004298 break;
4299 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004300 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004301
Douglas Gregor0396f462010-03-19 05:22:59 +00004302 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004303 // a specific cursor.
4304 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4305 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004306
4307 // Run the worker within a CrashRecoveryContext.
4308 llvm::CrashRecoveryContext CRC;
4309 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4310 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4311 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004312}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004313} // end: extern "C"
4314
4315//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004316// Operations for querying linkage of a cursor.
4317//===----------------------------------------------------------------------===//
4318
4319extern "C" {
4320CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004321 if (!clang_isDeclaration(cursor.kind))
4322 return CXLinkage_Invalid;
4323
Ted Kremenek16b42592010-03-03 06:36:57 +00004324 Decl *D = cxcursor::getCursorDecl(cursor);
4325 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4326 switch (ND->getLinkage()) {
4327 case NoLinkage: return CXLinkage_NoLinkage;
4328 case InternalLinkage: return CXLinkage_Internal;
4329 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4330 case ExternalLinkage: return CXLinkage_External;
4331 };
4332
4333 return CXLinkage_Invalid;
4334}
4335} // end: extern "C"
4336
4337//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004338// Operations for querying language of a cursor.
4339//===----------------------------------------------------------------------===//
4340
4341static CXLanguageKind getDeclLanguage(const Decl *D) {
4342 switch (D->getKind()) {
4343 default:
4344 break;
4345 case Decl::ImplicitParam:
4346 case Decl::ObjCAtDefsField:
4347 case Decl::ObjCCategory:
4348 case Decl::ObjCCategoryImpl:
4349 case Decl::ObjCClass:
4350 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004351 case Decl::ObjCForwardProtocol:
4352 case Decl::ObjCImplementation:
4353 case Decl::ObjCInterface:
4354 case Decl::ObjCIvar:
4355 case Decl::ObjCMethod:
4356 case Decl::ObjCProperty:
4357 case Decl::ObjCPropertyImpl:
4358 case Decl::ObjCProtocol:
4359 return CXLanguage_ObjC;
4360 case Decl::CXXConstructor:
4361 case Decl::CXXConversion:
4362 case Decl::CXXDestructor:
4363 case Decl::CXXMethod:
4364 case Decl::CXXRecord:
4365 case Decl::ClassTemplate:
4366 case Decl::ClassTemplatePartialSpecialization:
4367 case Decl::ClassTemplateSpecialization:
4368 case Decl::Friend:
4369 case Decl::FriendTemplate:
4370 case Decl::FunctionTemplate:
4371 case Decl::LinkageSpec:
4372 case Decl::Namespace:
4373 case Decl::NamespaceAlias:
4374 case Decl::NonTypeTemplateParm:
4375 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004376 case Decl::TemplateTemplateParm:
4377 case Decl::TemplateTypeParm:
4378 case Decl::UnresolvedUsingTypename:
4379 case Decl::UnresolvedUsingValue:
4380 case Decl::Using:
4381 case Decl::UsingDirective:
4382 case Decl::UsingShadow:
4383 return CXLanguage_CPlusPlus;
4384 }
4385
4386 return CXLanguage_C;
4387}
4388
4389extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004390
4391enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4392 if (clang_isDeclaration(cursor.kind))
4393 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4394 if (D->hasAttr<UnavailableAttr>() ||
4395 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4396 return CXAvailability_Available;
4397
4398 if (D->hasAttr<DeprecatedAttr>())
4399 return CXAvailability_Deprecated;
4400 }
4401
4402 return CXAvailability_Available;
4403}
4404
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004405CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4406 if (clang_isDeclaration(cursor.kind))
4407 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4408
4409 return CXLanguage_Invalid;
4410}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004411
4412CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4413 if (clang_isDeclaration(cursor.kind)) {
4414 if (Decl *D = getCursorDecl(cursor)) {
4415 DeclContext *DC = D->getDeclContext();
4416 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4417 }
4418 }
4419
4420 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4421 if (Decl *D = getCursorDecl(cursor))
4422 return MakeCXCursor(D, getCursorASTUnit(cursor));
4423 }
4424
4425 return clang_getNullCursor();
4426}
4427
4428CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4429 if (clang_isDeclaration(cursor.kind)) {
4430 if (Decl *D = getCursorDecl(cursor)) {
4431 DeclContext *DC = D->getLexicalDeclContext();
4432 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4433 }
4434 }
4435
4436 // FIXME: Note that we can't easily compute the lexical context of a
4437 // statement or expression, so we return nothing.
4438 return clang_getNullCursor();
4439}
4440
Douglas Gregor9f592342010-10-01 20:25:15 +00004441static void CollectOverriddenMethods(DeclContext *Ctx,
4442 ObjCMethodDecl *Method,
4443 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4444 if (!Ctx)
4445 return;
4446
4447 // If we have a class or category implementation, jump straight to the
4448 // interface.
4449 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4450 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4451
4452 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4453 if (!Container)
4454 return;
4455
4456 // Check whether we have a matching method at this level.
4457 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4458 Method->isInstanceMethod()))
4459 if (Method != Overridden) {
4460 // We found an override at this level; there is no need to look
4461 // into other protocols or categories.
4462 Methods.push_back(Overridden);
4463 return;
4464 }
4465
4466 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4467 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4468 PEnd = Protocol->protocol_end();
4469 P != PEnd; ++P)
4470 CollectOverriddenMethods(*P, Method, Methods);
4471 }
4472
4473 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4474 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4475 PEnd = Category->protocol_end();
4476 P != PEnd; ++P)
4477 CollectOverriddenMethods(*P, Method, Methods);
4478 }
4479
4480 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4481 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4482 PEnd = Interface->protocol_end();
4483 P != PEnd; ++P)
4484 CollectOverriddenMethods(*P, Method, Methods);
4485
4486 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4487 Category; Category = Category->getNextClassCategory())
4488 CollectOverriddenMethods(Category, Method, Methods);
4489
4490 // We only look into the superclass if we haven't found anything yet.
4491 if (Methods.empty())
4492 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4493 return CollectOverriddenMethods(Super, Method, Methods);
4494 }
4495}
4496
4497void clang_getOverriddenCursors(CXCursor cursor,
4498 CXCursor **overridden,
4499 unsigned *num_overridden) {
4500 if (overridden)
4501 *overridden = 0;
4502 if (num_overridden)
4503 *num_overridden = 0;
4504 if (!overridden || !num_overridden)
4505 return;
4506
4507 if (!clang_isDeclaration(cursor.kind))
4508 return;
4509
4510 Decl *D = getCursorDecl(cursor);
4511 if (!D)
4512 return;
4513
4514 // Handle C++ member functions.
4515 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4516 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4517 *num_overridden = CXXMethod->size_overridden_methods();
4518 if (!*num_overridden)
4519 return;
4520
4521 *overridden = new CXCursor [*num_overridden];
4522 unsigned I = 0;
4523 for (CXXMethodDecl::method_iterator
4524 M = CXXMethod->begin_overridden_methods(),
4525 MEnd = CXXMethod->end_overridden_methods();
4526 M != MEnd; (void)++M, ++I)
4527 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4528 return;
4529 }
4530
4531 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4532 if (!Method)
4533 return;
4534
4535 // Handle Objective-C methods.
4536 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4537 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4538
4539 if (Methods.empty())
4540 return;
4541
4542 *num_overridden = Methods.size();
4543 *overridden = new CXCursor [Methods.size()];
4544 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4545 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4546}
4547
4548void clang_disposeOverriddenCursors(CXCursor *overridden) {
4549 delete [] overridden;
4550}
4551
Douglas Gregorecdcb882010-10-20 22:00:55 +00004552CXFile clang_getIncludedFile(CXCursor cursor) {
4553 if (cursor.kind != CXCursor_InclusionDirective)
4554 return 0;
4555
4556 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4557 return (void *)ID->getFile();
4558}
4559
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004560} // end: extern "C"
4561
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004562
4563//===----------------------------------------------------------------------===//
4564// C++ AST instrospection.
4565//===----------------------------------------------------------------------===//
4566
4567extern "C" {
4568unsigned clang_CXXMethod_isStatic(CXCursor C) {
4569 if (!clang_isDeclaration(C.kind))
4570 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004571
4572 CXXMethodDecl *Method = 0;
4573 Decl *D = cxcursor::getCursorDecl(C);
4574 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4575 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4576 else
4577 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4578 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004579}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004580
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004581} // end: extern "C"
4582
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004583//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004584// Attribute introspection.
4585//===----------------------------------------------------------------------===//
4586
4587extern "C" {
4588CXType clang_getIBOutletCollectionType(CXCursor C) {
4589 if (C.kind != CXCursor_IBOutletCollectionAttr)
4590 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4591
4592 IBOutletCollectionAttr *A =
4593 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4594
4595 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4596}
4597} // end: extern "C"
4598
4599//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004600// CXString Operations.
4601//===----------------------------------------------------------------------===//
4602
4603extern "C" {
4604const char *clang_getCString(CXString string) {
4605 return string.Spelling;
4606}
4607
4608void clang_disposeString(CXString string) {
4609 if (string.MustFreeString && string.Spelling)
4610 free((void*)string.Spelling);
4611}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004612
Ted Kremenekfb480492010-01-13 21:46:36 +00004613} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004614
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004615namespace clang { namespace cxstring {
4616CXString createCXString(const char *String, bool DupString){
4617 CXString Str;
4618 if (DupString) {
4619 Str.Spelling = strdup(String);
4620 Str.MustFreeString = 1;
4621 } else {
4622 Str.Spelling = String;
4623 Str.MustFreeString = 0;
4624 }
4625 return Str;
4626}
4627
4628CXString createCXString(llvm::StringRef String, bool DupString) {
4629 CXString Result;
4630 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4631 char *Spelling = (char *)malloc(String.size() + 1);
4632 memmove(Spelling, String.data(), String.size());
4633 Spelling[String.size()] = 0;
4634 Result.Spelling = Spelling;
4635 Result.MustFreeString = 1;
4636 } else {
4637 Result.Spelling = String.data();
4638 Result.MustFreeString = 0;
4639 }
4640 return Result;
4641}
4642}}
4643
Ted Kremenek04bb7162010-01-22 22:44:15 +00004644//===----------------------------------------------------------------------===//
4645// Misc. utility functions.
4646//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004647
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004648/// Default to using an 8 MB stack size on "safety" threads.
4649static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004650
4651namespace clang {
4652
4653bool RunSafely(llvm::CrashRecoveryContext &CRC,
4654 void (*Fn)(void*), void *UserData) {
4655 if (unsigned Size = GetSafetyThreadStackSize())
4656 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4657 return CRC.RunSafely(Fn, UserData);
4658}
4659
4660unsigned GetSafetyThreadStackSize() {
4661 return SafetyStackThreadSize;
4662}
4663
4664void SetSafetyThreadStackSize(unsigned Value) {
4665 SafetyStackThreadSize = Value;
4666}
4667
4668}
4669
Ted Kremenek04bb7162010-01-22 22:44:15 +00004670extern "C" {
4671
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004672CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004673 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004674}
4675
4676} // end: extern "C"