blob: 9e6a439fdb067f90e8d5cdba53c6e0ae0dc66126 [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 Kremenek60458782010-11-12 21:34:16 +0000130 TypeLocVisitKind, OverloadExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000131protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000132 void *dataA;
133 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000134 CXCursor parent;
135 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000136 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
137 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000138public:
139 Kind getKind() const { return K; }
140 const CXCursor &getParent() const { return parent; }
141 static bool classof(VisitorJob *VJ) { return true; }
142};
143
144typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
145
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000147class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000148 public TypeLocVisitor<CursorVisitor, bool>,
149 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000150{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000152 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000153
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000154 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000155 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000156
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000157 /// \brief The declaration that serves at the parent of any statement or
158 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000159 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000160
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000163
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000164 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000166
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000167 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
168 // to the visitor. Declarations with a PCH level greater than this value will
169 // be suppressed.
170 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171
172 /// \brief When valid, a source range to which the cursor should restrict
173 /// its search.
174 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000176 // FIXME: Eventually remove. This part of a hack to support proper
177 // iteration over all Decls contained lexically within an ObjC container.
178 DeclContext::decl_iterator *DI_current;
179 DeclContext::decl_iterator DE_current;
180
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000182 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000183 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000184
185 /// \brief Determine whether this particular source range comes before, comes
186 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000187 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000188 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000189 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
190
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000191 class SetParentRAII {
192 CXCursor &Parent;
193 Decl *&StmtParent;
194 CXCursor OldParent;
195
196 public:
197 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
198 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
199 {
200 Parent = NewParent;
201 if (clang_isDeclaration(Parent.kind))
202 StmtParent = getCursorDecl(Parent);
203 }
204
205 ~SetParentRAII() {
206 Parent = OldParent;
207 if (clang_isDeclaration(Parent.kind))
208 StmtParent = getCursorDecl(Parent);
209 }
210 };
211
Steve Naroff89922f82009-08-31 00:59:03 +0000212public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000213 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
214 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000216 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000217 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
218 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 {
220 Parent.kind = CXCursor_NoDeclFound;
221 Parent.data[0] = 0;
222 Parent.data[1] = 0;
223 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000224 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000225 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000226
Ted Kremenekab979612010-11-11 08:05:23 +0000227 ASTUnit *getASTUnit() const { return TU; }
228
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000229 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000230
231 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
232 getPreprocessedEntities();
233
Douglas Gregorb1373d02010-01-20 20:59:29 +0000234 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000236 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000237 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000238 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000239 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000240 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000242 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
243 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000244 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000245 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000246 bool VisitClassTemplatePartialSpecializationDecl(
247 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000248 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000249 bool VisitEnumConstantDecl(EnumConstantDecl *D);
250 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
251 bool VisitFunctionDecl(FunctionDecl *ND);
252 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000253 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000254 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000255 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000256 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000257 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000258 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
259 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
260 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
261 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000262 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000263 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
264 bool VisitObjCImplDecl(ObjCImplDecl *D);
265 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
266 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000267 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
268 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
269 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000270 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000271 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000272 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000273 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000274 bool VisitUsingDecl(UsingDecl *D);
275 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
276 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000277
Douglas Gregor01829d32010-08-31 14:41:23 +0000278 // Name visitor
279 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000280 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000281
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000282 // Template visitors
283 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000284 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000285 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
286
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000287 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000288 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000289 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000290 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000291 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
292 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000293 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000294 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000295 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000296 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
297 bool VisitPointerTypeLoc(PointerTypeLoc TL);
298 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
299 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
300 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
301 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000302 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000303 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000304 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000305 // FIXME: Implement visitors here when the unimplemented TypeLocs get
306 // implemented
307 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
308 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000309
Douglas Gregora59e3902010-01-21 23:27:09 +0000310 // Statement visitors
311 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000312
Douglas Gregor336fd812010-01-23 00:40:08 +0000313 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000314 bool VisitDeclRefExpr(DeclRefExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000315 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor81d34662010-04-20 15:39:42 +0000316 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000317 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000318 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000319 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000320 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
321 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000322 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000323 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000324 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000325 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000326 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
327 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000328 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000329 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000330 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000331 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000332 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000333 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000334
335#define DATA_RECURSIVE_VISIT(NAME)\
336bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
337 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000338 DATA_RECURSIVE_VISIT(CompoundLiteralExpr)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000339 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000340 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted 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 Kremenekc373e3c2010-11-12 22:24:55 +0000349 DATA_RECURSIVE_VISIT(ObjCMessageExpr)
Ted Kremenek60458782010-11-12 21:34:16 +0000350 DATA_RECURSIVE_VISIT(OverloadExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000351 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekbb677132010-11-12 18:27:04 +0000352 DATA_RECURSIVE_VISIT(WhileStmt)
Ted Kremenek60458782010-11-12 21:34:16 +0000353 DATA_RECURSIVE_VISIT(UnresolvedMemberExpr)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000354
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000355 // Data-recursive visitor functions.
356 bool IsInRegionOfInterest(CXCursor C);
357 bool RunVisitorWorkList(VisitorWorkList &WL);
358 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
359 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000360};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000361
Ted Kremenekab188932010-01-05 19:32:54 +0000362} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000363
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000364static SourceRange getRawCursorExtent(CXCursor C);
365
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
368}
369
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370/// \brief Visit the given cursor and, if requested by the visitor,
371/// its children.
372///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000373/// \param Cursor the cursor to visit.
374///
375/// \param CheckRegionOfInterest if true, then the caller already checked that
376/// this cursor is within the region of interest.
377///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378/// \returns true if the visitation should be aborted, false if it
379/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000380bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381 if (clang_isInvalid(Cursor.kind))
382 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000383
Douglas Gregorb1373d02010-01-20 20:59:29 +0000384 if (clang_isDeclaration(Cursor.kind)) {
385 Decl *D = getCursorDecl(Cursor);
386 assert(D && "Invalid declaration cursor");
387 if (D->getPCHLevel() > MaxPCHLevel)
388 return false;
389
390 if (D->isImplicit())
391 return false;
392 }
393
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000394 // If we have a range of interest, and this cursor doesn't intersect with it,
395 // we're done.
396 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000397 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000398 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000399 return false;
400 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000401
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402 switch (Visitor(Cursor, Parent, ClientData)) {
403 case CXChildVisit_Break:
404 return true;
405
406 case CXChildVisit_Continue:
407 return false;
408
409 case CXChildVisit_Recurse:
410 return VisitChildren(Cursor);
411 }
412
Douglas Gregorfd643772010-01-25 16:45:46 +0000413 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000414}
415
Douglas Gregor788f5a12010-03-20 00:41:21 +0000416std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
417CursorVisitor::getPreprocessedEntities() {
418 PreprocessingRecord &PPRec
419 = *TU->getPreprocessor().getPreprocessingRecord();
420
421 bool OnlyLocalDecls
422 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
423
424 // There is no region of interest; we have to walk everything.
425 if (RegionOfInterest.isInvalid())
426 return std::make_pair(PPRec.begin(OnlyLocalDecls),
427 PPRec.end(OnlyLocalDecls));
428
429 // Find the file in which the region of interest lands.
430 SourceManager &SM = TU->getSourceManager();
431 std::pair<FileID, unsigned> Begin
432 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
433 std::pair<FileID, unsigned> End
434 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
435
436 // The region of interest spans files; we have to walk everything.
437 if (Begin.first != End.first)
438 return std::make_pair(PPRec.begin(OnlyLocalDecls),
439 PPRec.end(OnlyLocalDecls));
440
441 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
442 = TU->getPreprocessedEntitiesByFile();
443 if (ByFileMap.empty()) {
444 // Build the mapping from files to sets of preprocessed entities.
445 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
446 EEnd = PPRec.end(OnlyLocalDecls);
447 E != EEnd; ++E) {
448 std::pair<FileID, unsigned> P
449 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
450 ByFileMap[P.first].push_back(*E);
451 }
452 }
453
454 return std::make_pair(ByFileMap[Begin.first].begin(),
455 ByFileMap[Begin.first].end());
456}
457
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458/// \brief Visit the children of the given cursor.
459///
460/// \returns true if the visitation should be aborted, false if it
461/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000462bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000463 if (clang_isReference(Cursor.kind)) {
464 // By definition, references have no children.
465 return false;
466 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000467
468 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000470 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 if (clang_isDeclaration(Cursor.kind)) {
473 Decl *D = getCursorDecl(Cursor);
474 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000475 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000477
Douglas Gregora59e3902010-01-21 23:27:09 +0000478 if (clang_isStatement(Cursor.kind))
479 return Visit(getCursorStmt(Cursor));
480 if (clang_isExpression(Cursor.kind))
481 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000484 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000485 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
486 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000487 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
488 TLEnd = CXXUnit->top_level_end();
489 TL != TLEnd; ++TL) {
490 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000491 return true;
492 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 } else if (VisitDeclContext(
494 CXXUnit->getASTContext().getTranslationUnitDecl()))
495 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000496
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000498 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000499 // FIXME: Once we have the ability to deserialize a preprocessing record,
500 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000501 PreprocessingRecord::iterator E, EEnd;
502 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
504 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
505 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000506
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 continue;
508 }
509
510 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
511 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
512 return true;
513
514 continue;
515 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000516
517 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
518 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
519 return true;
520
521 continue;
522 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000523 }
524 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000525 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000527
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 return false;
530}
531
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000532bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000533 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
534 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000535
Ted Kremenek664cffd2010-07-22 11:30:19 +0000536 if (Stmt *Body = B->getBody())
537 return Visit(MakeCXCursor(Body, StmtParent, TU));
538
539 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000540}
541
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000542llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
543 if (RegionOfInterest.isValid()) {
544 SourceRange Range = getRawCursorExtent(Cursor);
545 if (Range.isInvalid())
546 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000547
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000548 switch (CompareRegionOfInterest(Range)) {
549 case RangeBefore:
550 // This declaration comes before the region of interest; skip it.
551 return llvm::Optional<bool>();
552
553 case RangeAfter:
554 // This declaration comes after the region of interest; we're done.
555 return false;
556
557 case RangeOverlap:
558 // This declaration overlaps the region of interest; visit it.
559 break;
560 }
561 }
562 return true;
563}
564
565bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
566 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
567
568 // FIXME: Eventually remove. This part of a hack to support proper
569 // iteration over all Decls contained lexically within an ObjC container.
570 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
571 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
572
573 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000574 Decl *D = *I;
575 if (D->getLexicalDeclContext() != DC)
576 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000577 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000578 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
579 if (!V.hasValue())
580 continue;
581 if (!V.getValue())
582 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000583 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return true;
585 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000586 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000587}
588
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000589bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
590 llvm_unreachable("Translation units are visited directly by Visit()");
591 return false;
592}
593
594bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
595 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
596 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598 return false;
599}
600
601bool CursorVisitor::VisitTagDecl(TagDecl *D) {
602 return VisitDeclContext(D);
603}
604
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000605bool CursorVisitor::VisitClassTemplateSpecializationDecl(
606 ClassTemplateSpecializationDecl *D) {
607 bool ShouldVisitBody = false;
608 switch (D->getSpecializationKind()) {
609 case TSK_Undeclared:
610 case TSK_ImplicitInstantiation:
611 // Nothing to visit
612 return false;
613
614 case TSK_ExplicitInstantiationDeclaration:
615 case TSK_ExplicitInstantiationDefinition:
616 break;
617
618 case TSK_ExplicitSpecialization:
619 ShouldVisitBody = true;
620 break;
621 }
622
623 // Visit the template arguments used in the specialization.
624 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
625 TypeLoc TL = SpecType->getTypeLoc();
626 if (TemplateSpecializationTypeLoc *TSTLoc
627 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
628 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
629 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
630 return true;
631 }
632 }
633
634 if (ShouldVisitBody && VisitCXXRecordDecl(D))
635 return true;
636
637 return false;
638}
639
Douglas Gregor74dbe642010-08-31 19:31:58 +0000640bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
641 ClassTemplatePartialSpecializationDecl *D) {
642 // FIXME: Visit the "outer" template parameter lists on the TagDecl
643 // before visiting these template parameters.
644 if (VisitTemplateParameters(D->getTemplateParameters()))
645 return true;
646
647 // Visit the partial specialization arguments.
648 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
649 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
650 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
651 return true;
652
653 return VisitCXXRecordDecl(D);
654}
655
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000656bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000657 // Visit the default argument.
658 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
659 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
660 if (Visit(DefArg->getTypeLoc()))
661 return true;
662
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000663 return false;
664}
665
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000666bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
667 if (Expr *Init = D->getInitExpr())
668 return Visit(MakeCXCursor(Init, StmtParent, TU));
669 return false;
670}
671
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000672bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
673 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
674 if (Visit(TSInfo->getTypeLoc()))
675 return true;
676
677 return false;
678}
679
Douglas Gregora67e03f2010-09-09 21:42:20 +0000680/// \brief Compare two base or member initializers based on their source order.
681static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
682 CXXBaseOrMemberInitializer const * const *X
683 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
684 CXXBaseOrMemberInitializer const * const *Y
685 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
686
687 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
688 return -1;
689 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
690 return 1;
691 else
692 return 0;
693}
694
Douglas Gregorb1373d02010-01-20 20:59:29 +0000695bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000696 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
697 // Visit the function declaration's syntactic components in the order
698 // written. This requires a bit of work.
699 TypeLoc TL = TSInfo->getTypeLoc();
700 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
701
702 // If we have a function declared directly (without the use of a typedef),
703 // visit just the return type. Otherwise, just visit the function's type
704 // now.
705 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
706 (!FTL && Visit(TL)))
707 return true;
708
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000709 // Visit the nested-name-specifier, if present.
710 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
711 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
712 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000713
714 // Visit the declaration name.
715 if (VisitDeclarationNameInfo(ND->getNameInfo()))
716 return true;
717
718 // FIXME: Visit explicitly-specified template arguments!
719
720 // Visit the function parameters, if we have a function type.
721 if (FTL && VisitFunctionTypeLoc(*FTL, true))
722 return true;
723
724 // FIXME: Attributes?
725 }
726
Douglas Gregora67e03f2010-09-09 21:42:20 +0000727 if (ND->isThisDeclarationADefinition()) {
728 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
729 // Find the initializers that were written in the source.
730 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
731 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
732 IEnd = Constructor->init_end();
733 I != IEnd; ++I) {
734 if (!(*I)->isWritten())
735 continue;
736
737 WrittenInits.push_back(*I);
738 }
739
740 // Sort the initializers in source order
741 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
742 &CompareCXXBaseOrMemberInitializers);
743
744 // Visit the initializers in source order
745 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
746 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
747 if (Init->isMemberInitializer()) {
748 if (Visit(MakeCursorMemberRef(Init->getMember(),
749 Init->getMemberLocation(), TU)))
750 return true;
751 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
752 if (Visit(BaseInfo->getTypeLoc()))
753 return true;
754 }
755
756 // Visit the initializer value.
757 if (Expr *Initializer = Init->getInit())
758 if (Visit(MakeCXCursor(Initializer, ND, TU)))
759 return true;
760 }
761 }
762
763 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
764 return true;
765 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000766
Douglas Gregorb1373d02010-01-20 20:59:29 +0000767 return false;
768}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
771 if (VisitDeclaratorDecl(D))
772 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000773
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000774 if (Expr *BitWidth = D->getBitWidth())
775 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000777 return false;
778}
779
780bool CursorVisitor::VisitVarDecl(VarDecl *D) {
781 if (VisitDeclaratorDecl(D))
782 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 if (Expr *Init = D->getInit())
785 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 return false;
788}
789
Douglas Gregor84b51d72010-09-01 20:16:53 +0000790bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
791 if (VisitDeclaratorDecl(D))
792 return true;
793
794 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
795 if (Expr *DefArg = D->getDefaultArgument())
796 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
797
798 return false;
799}
800
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000801bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
802 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
803 // before visiting these template parameters.
804 if (VisitTemplateParameters(D->getTemplateParameters()))
805 return true;
806
807 return VisitFunctionDecl(D->getTemplatedDecl());
808}
809
Douglas Gregor39d6f072010-08-31 19:02:00 +0000810bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
811 // FIXME: Visit the "outer" template parameter lists on the TagDecl
812 // before visiting these template parameters.
813 if (VisitTemplateParameters(D->getTemplateParameters()))
814 return true;
815
816 return VisitCXXRecordDecl(D->getTemplatedDecl());
817}
818
Douglas Gregor84b51d72010-09-01 20:16:53 +0000819bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
820 if (VisitTemplateParameters(D->getTemplateParameters()))
821 return true;
822
823 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
824 VisitTemplateArgumentLoc(D->getDefaultArgument()))
825 return true;
826
827 return false;
828}
829
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000830bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000831 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
832 if (Visit(TSInfo->getTypeLoc()))
833 return true;
834
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000835 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836 PEnd = ND->param_end();
837 P != PEnd; ++P) {
838 if (Visit(MakeCXCursor(*P, TU)))
839 return true;
840 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 if (ND->isThisDeclarationADefinition() &&
843 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
844 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000846 return false;
847}
848
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000849namespace {
850 struct ContainerDeclsSort {
851 SourceManager &SM;
852 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
853 bool operator()(Decl *A, Decl *B) {
854 SourceLocation L_A = A->getLocStart();
855 SourceLocation L_B = B->getLocStart();
856 assert(L_A.isValid() && L_B.isValid());
857 return SM.isBeforeInTranslationUnit(L_A, L_B);
858 }
859 };
860}
861
Douglas Gregora59e3902010-01-21 23:27:09 +0000862bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000863 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
864 // an @implementation can lexically contain Decls that are not properly
865 // nested in the AST. When we identify such cases, we need to retrofit
866 // this nesting here.
867 if (!DI_current)
868 return VisitDeclContext(D);
869
870 // Scan the Decls that immediately come after the container
871 // in the current DeclContext. If any fall within the
872 // container's lexical region, stash them into a vector
873 // for later processing.
874 llvm::SmallVector<Decl *, 24> DeclsInContainer;
875 SourceLocation EndLoc = D->getSourceRange().getEnd();
876 SourceManager &SM = TU->getSourceManager();
877 if (EndLoc.isValid()) {
878 DeclContext::decl_iterator next = *DI_current;
879 while (++next != DE_current) {
880 Decl *D_next = *next;
881 if (!D_next)
882 break;
883 SourceLocation L = D_next->getLocStart();
884 if (!L.isValid())
885 break;
886 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
887 *DI_current = next;
888 DeclsInContainer.push_back(D_next);
889 continue;
890 }
891 break;
892 }
893 }
894
895 // The common case.
896 if (DeclsInContainer.empty())
897 return VisitDeclContext(D);
898
899 // Get all the Decls in the DeclContext, and sort them with the
900 // additional ones we've collected. Then visit them.
901 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
902 I!=E; ++I) {
903 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000904 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
905 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000906 continue;
907 DeclsInContainer.push_back(subDecl);
908 }
909
910 // Now sort the Decls so that they appear in lexical order.
911 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
912 ContainerDeclsSort(SM));
913
914 // Now visit the decls.
915 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
916 E = DeclsInContainer.end(); I != E; ++I) {
917 CXCursor Cursor = MakeCXCursor(*I, TU);
918 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
919 if (!V.hasValue())
920 continue;
921 if (!V.getValue())
922 return false;
923 if (Visit(Cursor, true))
924 return true;
925 }
926 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000927}
928
Douglas Gregorb1373d02010-01-20 20:59:29 +0000929bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000930 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
931 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000932 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000933
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000934 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
935 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
936 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000937 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000938 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000939
Douglas Gregora59e3902010-01-21 23:27:09 +0000940 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000941}
942
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000943bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
944 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
945 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
946 E = PID->protocol_end(); I != E; ++I, ++PL)
947 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
948 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000950 return VisitObjCContainerDecl(PID);
951}
952
Ted Kremenek23173d72010-05-18 21:09:07 +0000953bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000954 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000955 return true;
956
Ted Kremenek23173d72010-05-18 21:09:07 +0000957 // FIXME: This implements a workaround with @property declarations also being
958 // installed in the DeclContext for the @interface. Eventually this code
959 // should be removed.
960 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
961 if (!CDecl || !CDecl->IsClassExtension())
962 return false;
963
964 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
965 if (!ID)
966 return false;
967
968 IdentifierInfo *PropertyId = PD->getIdentifier();
969 ObjCPropertyDecl *prevDecl =
970 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
971
972 if (!prevDecl)
973 return false;
974
975 // Visit synthesized methods since they will be skipped when visiting
976 // the @interface.
977 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000978 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000979 if (Visit(MakeCXCursor(MD, TU)))
980 return true;
981
982 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000983 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000984 if (Visit(MakeCXCursor(MD, TU)))
985 return true;
986
987 return false;
988}
989
Douglas Gregorb1373d02010-01-20 20:59:29 +0000990bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000991 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000992 if (D->getSuperClass() &&
993 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000995 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000996 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000997
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000998 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
999 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1000 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001001 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001002 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001003
Douglas Gregora59e3902010-01-21 23:27:09 +00001004 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001005}
1006
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001007bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1008 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001009}
1010
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001011bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001012 // 'ID' could be null when dealing with invalid code.
1013 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1014 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001017 return VisitObjCImplDecl(D);
1018}
1019
1020bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1021#if 0
1022 // Issue callbacks for super class.
1023 // FIXME: No source location information!
1024 if (D->getSuperClass() &&
1025 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001027 TU)))
1028 return true;
1029#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001030
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001031 return VisitObjCImplDecl(D);
1032}
1033
1034bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1035 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1036 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1037 E = D->protocol_end();
1038 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001039 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001040 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041
1042 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001043}
1044
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1046 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1047 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1048 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001050 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001051}
1052
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001053bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1054 return VisitDeclContext(D);
1055}
1056
Douglas Gregor69319002010-08-31 23:48:11 +00001057bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001058 // Visit nested-name-specifier.
1059 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1060 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1061 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001062
1063 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1064 D->getTargetNameLoc(), TU));
1065}
1066
Douglas Gregor7e242562010-09-01 19:52:22 +00001067bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001068 // Visit nested-name-specifier.
1069 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1070 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1071 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001072
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001073 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1074 return true;
1075
Douglas Gregor7e242562010-09-01 19:52:22 +00001076 return VisitDeclarationNameInfo(D->getNameInfo());
1077}
1078
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001079bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080 // Visit nested-name-specifier.
1081 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1082 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1083 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001084
1085 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1086 D->getIdentLocation(), TU));
1087}
1088
Douglas Gregor7e242562010-09-01 19:52:22 +00001089bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 // Visit nested-name-specifier.
1091 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1092 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1093 return true;
1094
Douglas Gregor7e242562010-09-01 19:52:22 +00001095 return VisitDeclarationNameInfo(D->getNameInfo());
1096}
1097
1098bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1099 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 // Visit nested-name-specifier.
1101 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1102 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1103 return true;
1104
Douglas Gregor7e242562010-09-01 19:52:22 +00001105 return false;
1106}
1107
Douglas Gregor01829d32010-08-31 14:41:23 +00001108bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1109 switch (Name.getName().getNameKind()) {
1110 case clang::DeclarationName::Identifier:
1111 case clang::DeclarationName::CXXLiteralOperatorName:
1112 case clang::DeclarationName::CXXOperatorName:
1113 case clang::DeclarationName::CXXUsingDirective:
1114 return false;
1115
1116 case clang::DeclarationName::CXXConstructorName:
1117 case clang::DeclarationName::CXXDestructorName:
1118 case clang::DeclarationName::CXXConversionFunctionName:
1119 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1120 return Visit(TSInfo->getTypeLoc());
1121 return false;
1122
1123 case clang::DeclarationName::ObjCZeroArgSelector:
1124 case clang::DeclarationName::ObjCOneArgSelector:
1125 case clang::DeclarationName::ObjCMultiArgSelector:
1126 // FIXME: Per-identifier location info?
1127 return false;
1128 }
1129
1130 return false;
1131}
1132
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1134 SourceRange Range) {
1135 // FIXME: This whole routine is a hack to work around the lack of proper
1136 // source information in nested-name-specifiers (PR5791). Since we do have
1137 // a beginning source location, we can visit the first component of the
1138 // nested-name-specifier, if it's a single-token component.
1139 if (!NNS)
1140 return false;
1141
1142 // Get the first component in the nested-name-specifier.
1143 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1144 NNS = Prefix;
1145
1146 switch (NNS->getKind()) {
1147 case NestedNameSpecifier::Namespace:
1148 // FIXME: The token at this source location might actually have been a
1149 // namespace alias, but we don't model that. Lame!
1150 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1151 TU));
1152
1153 case NestedNameSpecifier::TypeSpec: {
1154 // If the type has a form where we know that the beginning of the source
1155 // range matches up with a reference cursor. Visit the appropriate reference
1156 // cursor.
1157 Type *T = NNS->getAsType();
1158 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1159 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1160 if (const TagType *Tag = dyn_cast<TagType>(T))
1161 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1162 if (const TemplateSpecializationType *TST
1163 = dyn_cast<TemplateSpecializationType>(T))
1164 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1165 break;
1166 }
1167
1168 case NestedNameSpecifier::TypeSpecWithTemplate:
1169 case NestedNameSpecifier::Global:
1170 case NestedNameSpecifier::Identifier:
1171 break;
1172 }
1173
1174 return false;
1175}
1176
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001177bool CursorVisitor::VisitTemplateParameters(
1178 const TemplateParameterList *Params) {
1179 if (!Params)
1180 return false;
1181
1182 for (TemplateParameterList::const_iterator P = Params->begin(),
1183 PEnd = Params->end();
1184 P != PEnd; ++P) {
1185 if (Visit(MakeCXCursor(*P, TU)))
1186 return true;
1187 }
1188
1189 return false;
1190}
1191
Douglas Gregor0b36e612010-08-31 20:37:03 +00001192bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1193 switch (Name.getKind()) {
1194 case TemplateName::Template:
1195 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1196
1197 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001198 // Visit the overloaded template set.
1199 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1200 return true;
1201
Douglas Gregor0b36e612010-08-31 20:37:03 +00001202 return false;
1203
1204 case TemplateName::DependentTemplate:
1205 // FIXME: Visit nested-name-specifier.
1206 return false;
1207
1208 case TemplateName::QualifiedTemplate:
1209 // FIXME: Visit nested-name-specifier.
1210 return Visit(MakeCursorTemplateRef(
1211 Name.getAsQualifiedTemplateName()->getDecl(),
1212 Loc, TU));
1213 }
1214
1215 return false;
1216}
1217
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001218bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1219 switch (TAL.getArgument().getKind()) {
1220 case TemplateArgument::Null:
1221 case TemplateArgument::Integral:
1222 return false;
1223
1224 case TemplateArgument::Pack:
1225 // FIXME: Implement when variadic templates come along.
1226 return false;
1227
1228 case TemplateArgument::Type:
1229 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1230 return Visit(TSInfo->getTypeLoc());
1231 return false;
1232
1233 case TemplateArgument::Declaration:
1234 if (Expr *E = TAL.getSourceDeclExpression())
1235 return Visit(MakeCXCursor(E, StmtParent, TU));
1236 return false;
1237
1238 case TemplateArgument::Expression:
1239 if (Expr *E = TAL.getSourceExpression())
1240 return Visit(MakeCXCursor(E, StmtParent, TU));
1241 return false;
1242
1243 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001244 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1245 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001246 }
1247
1248 return false;
1249}
1250
Ted Kremeneka0536d82010-05-07 01:04:29 +00001251bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1252 return VisitDeclContext(D);
1253}
1254
Douglas Gregor01829d32010-08-31 14:41:23 +00001255bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1256 return Visit(TL.getUnqualifiedLoc());
1257}
1258
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001259bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1260 ASTContext &Context = TU->getASTContext();
1261
1262 // Some builtin types (such as Objective-C's "id", "sel", and
1263 // "Class") have associated declarations. Create cursors for those.
1264 QualType VisitType;
1265 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001266 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001268 case BuiltinType::Char_U:
1269 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270 case BuiltinType::Char16:
1271 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001272 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273 case BuiltinType::UInt:
1274 case BuiltinType::ULong:
1275 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001276 case BuiltinType::UInt128:
1277 case BuiltinType::Char_S:
1278 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001279 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001280 case BuiltinType::Short:
1281 case BuiltinType::Int:
1282 case BuiltinType::Long:
1283 case BuiltinType::LongLong:
1284 case BuiltinType::Int128:
1285 case BuiltinType::Float:
1286 case BuiltinType::Double:
1287 case BuiltinType::LongDouble:
1288 case BuiltinType::NullPtr:
1289 case BuiltinType::Overload:
1290 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001292
1293 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001294 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001295
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001296 case BuiltinType::ObjCId:
1297 VisitType = Context.getObjCIdType();
1298 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001299
1300 case BuiltinType::ObjCClass:
1301 VisitType = Context.getObjCClassType();
1302 break;
1303
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001304 case BuiltinType::ObjCSel:
1305 VisitType = Context.getObjCSelType();
1306 break;
1307 }
1308
1309 if (!VisitType.isNull()) {
1310 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001311 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001312 TU));
1313 }
1314
1315 return false;
1316}
1317
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001318bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1319 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1320}
1321
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001322bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1323 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1324}
1325
1326bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1327 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1328}
1329
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001330bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001331 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001332 // no context information with which we can match up the depth/index in the
1333 // type to the appropriate
1334 return false;
1335}
1336
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1338 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1339 return true;
1340
John McCallc12c5bb2010-05-15 11:32:37 +00001341 return false;
1342}
1343
1344bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1345 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1346 return true;
1347
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1349 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1350 TU)))
1351 return true;
1352 }
1353
1354 return false;
1355}
1356
1357bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001358 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359}
1360
1361bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1362 return Visit(TL.getPointeeLoc());
1363}
1364
1365bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1366 return Visit(TL.getPointeeLoc());
1367}
1368
1369bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1370 return Visit(TL.getPointeeLoc());
1371}
1372
1373bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001374 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375}
1376
1377bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001378 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001379}
1380
Douglas Gregor01829d32010-08-31 14:41:23 +00001381bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1382 bool SkipResultType) {
1383 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384 return true;
1385
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001387 if (Decl *D = TL.getArg(I))
1388 if (Visit(MakeCXCursor(D, TU)))
1389 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390
1391 return false;
1392}
1393
1394bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1395 if (Visit(TL.getElementLoc()))
1396 return true;
1397
1398 if (Expr *Size = TL.getSizeExpr())
1399 return Visit(MakeCXCursor(Size, StmtParent, TU));
1400
1401 return false;
1402}
1403
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001404bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1405 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001406 // Visit the template name.
1407 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1408 TL.getTemplateNameLoc()))
1409 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001410
1411 // Visit the template arguments.
1412 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1413 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1414 return true;
1415
1416 return false;
1417}
1418
Douglas Gregor2332c112010-01-21 20:48:56 +00001419bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1420 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1421}
1422
1423bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1424 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1425 return Visit(TSInfo->getTypeLoc());
1426
1427 return false;
1428}
1429
Douglas Gregora59e3902010-01-21 23:27:09 +00001430bool CursorVisitor::VisitStmt(Stmt *S) {
1431 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1432 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001433 if (Stmt *C = *Child)
1434 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1435 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001436 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001437
Douglas Gregora59e3902010-01-21 23:27:09 +00001438 return false;
1439}
1440
Douglas Gregor8947a752010-09-02 20:35:02 +00001441bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1442 // Visit nested-name-specifier, if present.
1443 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1444 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1445 return true;
1446
1447 // Visit declaration name.
1448 if (VisitDeclarationNameInfo(E->getNameInfo()))
1449 return true;
1450
1451 // Visit explicitly-specified template arguments.
1452 if (E->hasExplicitTemplateArgs()) {
1453 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1454 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1455 *ArgEnd = Arg + Args.NumTemplateArgs;
1456 Arg != ArgEnd; ++Arg)
1457 if (VisitTemplateArgumentLoc(*Arg))
1458 return true;
1459 }
1460
1461 return false;
1462}
1463
Ted Kremenek3064ef92010-08-27 21:34:58 +00001464bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1465 if (D->isDefinition()) {
1466 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1467 E = D->bases_end(); I != E; ++I) {
1468 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1469 return true;
1470 }
1471 }
1472
1473 return VisitTagDecl(D);
1474}
1475
1476
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001477bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1478 return Visit(B->getBlockDecl());
1479}
1480
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001481bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001482 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001483 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1484 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001485
1486 // Visit the components of the offsetof expression.
1487 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1488 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1489 const OffsetOfNode &Node = E->getComponent(I);
1490 switch (Node.getKind()) {
1491 case OffsetOfNode::Array:
1492 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1493 StmtParent, TU)))
1494 return true;
1495 break;
1496
1497 case OffsetOfNode::Field:
1498 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1499 TU)))
1500 return true;
1501 break;
1502
1503 case OffsetOfNode::Identifier:
1504 case OffsetOfNode::Base:
1505 continue;
1506 }
1507 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001508
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001509 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001510}
1511
Douglas Gregor336fd812010-01-23 00:40:08 +00001512bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1513 if (E->isArgumentType()) {
1514 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1515 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001516
Douglas Gregor336fd812010-01-23 00:40:08 +00001517 return false;
1518 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001519
Douglas Gregor336fd812010-01-23 00:40:08 +00001520 return VisitExpr(E);
1521}
1522
Douglas Gregor36897b02010-09-10 00:22:18 +00001523bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1524 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1525}
1526
Douglas Gregor648220e2010-08-10 15:02:34 +00001527bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1528 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1529 Visit(E->getArgTInfo2()->getTypeLoc());
1530}
1531
1532bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1533 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1534 return true;
1535
1536 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1537}
1538
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001539bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1540 // Visit the designators.
1541 typedef DesignatedInitExpr::Designator Designator;
1542 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1543 DEnd = E->designators_end();
1544 D != DEnd; ++D) {
1545 if (D->isFieldDesignator()) {
1546 if (FieldDecl *Field = D->getField())
1547 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1548 return true;
1549
1550 continue;
1551 }
1552
1553 if (D->isArrayDesignator()) {
1554 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1555 return true;
1556
1557 continue;
1558 }
1559
1560 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1561 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1562 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1563 return true;
1564 }
1565
1566 // Visit the initializer value itself.
1567 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1568}
1569
Douglas Gregor94802292010-09-02 21:20:16 +00001570bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1571 if (E->isTypeOperand()) {
1572 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1573 return Visit(TSInfo->getTypeLoc());
1574
1575 return false;
1576 }
1577
1578 return VisitExpr(E);
1579}
1580
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001581bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1582 if (E->isTypeOperand()) {
1583 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1584 return Visit(TSInfo->getTypeLoc());
1585
1586 return false;
1587 }
1588
1589 return VisitExpr(E);
1590}
1591
Douglas Gregorab6677e2010-09-08 00:15:04 +00001592bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1593 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001594 if (Visit(TSInfo->getTypeLoc()))
1595 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001596
1597 return VisitExpr(E);
1598}
1599
1600bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1601 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1602 return Visit(TSInfo->getTypeLoc());
1603
1604 return false;
1605}
1606
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001607bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1608 // Visit placement arguments.
1609 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1610 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1611 return true;
1612
1613 // Visit the allocated type.
1614 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1615 if (Visit(TSInfo->getTypeLoc()))
1616 return true;
1617
1618 // Visit the array size, if any.
1619 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1620 return true;
1621
1622 // Visit the initializer or constructor arguments.
1623 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1624 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1625 return true;
1626
1627 return false;
1628}
1629
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001630bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1631 // Visit base expression.
1632 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1633 return true;
1634
1635 // Visit the nested-name-specifier.
1636 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1637 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1638 return true;
1639
1640 // Visit the scope type that looks disturbingly like the nested-name-specifier
1641 // but isn't.
1642 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1643 if (Visit(TSInfo->getTypeLoc()))
1644 return true;
1645
1646 // Visit the name of the type being destroyed.
1647 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1648 if (Visit(TSInfo->getTypeLoc()))
1649 return true;
1650
1651 return false;
1652}
1653
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001654bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1655 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1656}
1657
Douglas Gregorbfebed22010-09-03 17:24:10 +00001658bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1659 DependentScopeDeclRefExpr *E) {
1660 // Visit the nested-name-specifier.
1661 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1662 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1663 return true;
1664
1665 // Visit the declaration name.
1666 if (VisitDeclarationNameInfo(E->getNameInfo()))
1667 return true;
1668
1669 // Visit the explicitly-specified template arguments.
1670 if (const ExplicitTemplateArgumentList *ArgList
1671 = E->getOptionalExplicitTemplateArgs()) {
1672 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1673 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1674 Arg != ArgEnd; ++Arg) {
1675 if (VisitTemplateArgumentLoc(*Arg))
1676 return true;
1677 }
1678 }
1679
1680 return false;
1681}
1682
Douglas Gregorab6677e2010-09-08 00:15:04 +00001683bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1684 CXXUnresolvedConstructExpr *E) {
1685 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1686 if (Visit(TSInfo->getTypeLoc()))
1687 return true;
1688
1689 return VisitExpr(E);
1690}
1691
Douglas Gregor25d63622010-09-03 17:35:34 +00001692bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1693 CXXDependentScopeMemberExpr *E) {
1694 // Visit the base expression, if there is one.
1695 if (!E->isImplicitAccess() &&
1696 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1697 return true;
1698
1699 // Visit the nested-name-specifier.
1700 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1701 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1702 return true;
1703
1704 // Visit the declaration name.
1705 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1706 return true;
1707
1708 // Visit the explicitly-specified template arguments.
1709 if (const ExplicitTemplateArgumentList *ArgList
1710 = E->getOptionalExplicitTemplateArgs()) {
1711 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1712 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1713 Arg != ArgEnd; ++Arg) {
1714 if (VisitTemplateArgumentLoc(*Arg))
1715 return true;
1716 }
1717 }
1718
1719 return false;
1720}
1721
Douglas Gregor81d34662010-04-20 15:39:42 +00001722bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1723 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1724}
1725
1726
Ted Kremenek09dfa372010-02-18 05:46:33 +00001727bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001728 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1729 i != e; ++i)
1730 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001731 return true;
1732
1733 return false;
1734}
1735
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001736//===----------------------------------------------------------------------===//
1737// Data-recursive visitor methods.
1738//===----------------------------------------------------------------------===//
1739
Ted Kremenek28a71942010-11-13 00:36:47 +00001740namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001741#define DEF_JOB(NAME, DATA, KIND)\
1742class NAME : public VisitorJob {\
1743public:\
1744 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1745 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1746 DATA *get() const { return static_cast<DATA*>(dataA); }\
1747};
1748
1749DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1750DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1751DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1752#undef DEF_JOB
1753
1754class DeclVisit : public VisitorJob {
1755public:
1756 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1757 VisitorJob(parent, VisitorJob::DeclVisitKind,
1758 d, isFirst ? (void*) 1 : (void*) 0) {}
1759 static bool classof(const VisitorJob *VJ) {
1760 return VJ->getKind () == DeclVisitKind;
1761 }
1762 Decl *get() { return static_cast<Decl*>(dataA);}
1763 bool isFirst() const { return dataB ? true : false; }
1764};
1765
1766class TypeLocVisit : public VisitorJob {
1767public:
1768 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1769 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1770 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1771
1772 static bool classof(const VisitorJob *VJ) {
1773 return VJ->getKind() == TypeLocVisitKind;
1774 }
1775
1776 TypeLoc get() {
1777 QualType T = QualType::getFromOpaquePtr(dataA);
1778 return TypeLoc(T, dataB);
1779 }
1780};
1781
Ted Kremenek28a71942010-11-13 00:36:47 +00001782class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1783 VisitorWorkList &WL;
1784 CXCursor Parent;
1785public:
1786 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1787 : WL(wl), Parent(parent) {}
1788
1789 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1790 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek035dc412010-11-13 00:36:50 +00001791 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001792 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1793 void VisitForStmt(ForStmt *FS);
1794 void VisitIfStmt(IfStmt *If);
1795 void VisitInitListExpr(InitListExpr *IE);
1796 void VisitMemberExpr(MemberExpr *M);
1797 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1798 void VisitOverloadExpr(OverloadExpr *E);
1799 void VisitStmt(Stmt *S);
1800 void VisitSwitchStmt(SwitchStmt *S);
1801 void VisitWhileStmt(WhileStmt *W);
1802 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1803
1804private:
1805 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001806 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001807 void AddTypeLoc(TypeSourceInfo *TI);
1808 void EnqueueChildren(Stmt *S);
1809};
1810} // end anonyous namespace
1811
1812void EnqueueVisitor::AddStmt(Stmt *S) {
1813 if (S)
1814 WL.push_back(StmtVisit(S, Parent));
1815}
Ted Kremenek035dc412010-11-13 00:36:50 +00001816void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001817 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001818 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001819}
1820void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1821 if (TI)
1822 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1823 }
1824void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001825 unsigned size = WL.size();
1826 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1827 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001828 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001829 }
1830 if (size == WL.size())
1831 return;
1832 // Now reverse the entries we just added. This will match the DFS
1833 // ordering performed by the worklist.
1834 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1835 std::reverse(I, E);
1836}
Ted Kremenek28a71942010-11-13 00:36:47 +00001837void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1838 EnqueueChildren(E);
1839 AddTypeLoc(E->getTypeSourceInfo());
1840}
1841void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1842 // Note that we enqueue things in reverse order so that
1843 // they are visited correctly by the DFS.
1844 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
1845 AddStmt(CE->getArg(N-I));
1846 AddStmt(CE->getCallee());
1847 AddStmt(CE->getArg(0));
1848}
Ted Kremenek035dc412010-11-13 00:36:50 +00001849void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1850 unsigned size = WL.size();
1851 bool isFirst = true;
1852 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1853 D != DEnd; ++D) {
1854 AddDecl(*D, isFirst);
1855 isFirst = false;
1856 }
1857 if (size == WL.size())
1858 return;
1859 // Now reverse the entries we just added. This will match the DFS
1860 // ordering performed by the worklist.
1861 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1862 std::reverse(I, E);
1863}
Ted Kremenek28a71942010-11-13 00:36:47 +00001864void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1865 EnqueueChildren(E);
1866 AddTypeLoc(E->getTypeInfoAsWritten());
1867}
1868void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1869 AddStmt(FS->getBody());
1870 AddStmt(FS->getInc());
1871 AddStmt(FS->getCond());
1872 AddDecl(FS->getConditionVariable());
1873 AddStmt(FS->getInit());
1874}
1875void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1876 AddStmt(If->getElse());
1877 AddStmt(If->getThen());
1878 AddStmt(If->getCond());
1879 AddDecl(If->getConditionVariable());
1880}
1881void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1882 // We care about the syntactic form of the initializer list, only.
1883 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1884 IE = Syntactic;
1885 EnqueueChildren(IE);
1886}
1887void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1888 WL.push_back(MemberExprParts(M, Parent));
1889 AddStmt(M->getBase());
1890}
1891void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1892 EnqueueChildren(M);
1893 AddTypeLoc(M->getClassReceiverTypeInfo());
1894}
1895void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001896 WL.push_back(OverloadExprParts(E, Parent));
1897}
Ted Kremenek28a71942010-11-13 00:36:47 +00001898void EnqueueVisitor::VisitStmt(Stmt *S) {
1899 EnqueueChildren(S);
1900}
1901void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1902 AddStmt(S->getBody());
1903 AddStmt(S->getCond());
1904 AddDecl(S->getConditionVariable());
1905}
1906void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1907 AddStmt(W->getBody());
1908 AddStmt(W->getCond());
1909 AddDecl(W->getConditionVariable());
1910}
1911void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1912 VisitOverloadExpr(U);
1913 if (!U->isImplicitAccess())
1914 AddStmt(U->getBase());
1915}
Ted Kremenek60458782010-11-12 21:34:16 +00001916
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001917void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001918 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001919}
1920
1921bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1922 if (RegionOfInterest.isValid()) {
1923 SourceRange Range = getRawCursorExtent(C);
1924 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1925 return false;
1926 }
1927 return true;
1928}
1929
1930bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1931 while (!WL.empty()) {
1932 // Dequeue the worklist item.
1933 VisitorJob LI = WL.back(); WL.pop_back();
1934
1935 // Set the Parent field, then back to its old value once we're done.
1936 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1937
1938 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001939 case VisitorJob::DeclVisitKind: {
1940 Decl *D = cast<DeclVisit>(LI).get();
1941 if (!D)
1942 continue;
1943
1944 // For now, perform default visitation for Decls.
Ted Kremenek035dc412010-11-13 00:36:50 +00001945 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(LI).isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001946 return true;
1947
1948 continue;
1949 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001950 case VisitorJob::TypeLocVisitKind: {
1951 // Perform default visitation for TypeLocs.
1952 if (Visit(cast<TypeLocVisit>(LI).get()))
1953 return true;
1954 continue;
1955 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001956 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001957 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001958 if (!S)
1959 continue;
1960
Ted Kremenekf1107452010-11-12 18:26:56 +00001961 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001962 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1963
1964 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001965 case Stmt::GotoStmtClass: {
1966 GotoStmt *GS = cast<GotoStmt>(S);
1967 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1968 GS->getLabelLoc(), TU))) {
1969 return true;
1970 }
1971 continue;
1972 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001973 default: {
Ted Kremenek99394242010-11-12 22:24:57 +00001974 // FIXME: this entire switch stmt will eventually
1975 // go away.
1976 if (!isa<ExplicitCastExpr>(S)) {
1977 // Perform default visitation for other cases.
1978 if (Visit(Cursor))
1979 return true;
1980 continue;
1981 }
1982 // Fall-through.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001983 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001984 case Stmt::BinaryOperatorClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001985 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001986 case Stmt::CaseStmtClass:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001987 case Stmt::CompoundLiteralExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001988 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001989 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001990 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001991 case Stmt::DefaultStmtClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001992 case Stmt::DoStmtClass:
1993 case Stmt::ForStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001994 case Stmt::IfStmtClass:
Ted Kremeneka6b70432010-11-12 21:34:09 +00001995 case Stmt::InitListExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001996 case Stmt::MemberExprClass:
Ted Kremenekc373e3c2010-11-12 22:24:55 +00001997 case Stmt::ObjCMessageExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001998 case Stmt::ParenExprClass:
1999 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00002000 case Stmt::UnaryOperatorClass:
Ted Kremenek60458782010-11-12 21:34:16 +00002001 case Stmt::UnresolvedLookupExprClass:
2002 case Stmt::UnresolvedMemberExprClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00002003 case Stmt::WhileStmtClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00002004 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002005 if (!IsInRegionOfInterest(Cursor))
2006 continue;
2007 switch (Visitor(Cursor, Parent, ClientData)) {
2008 case CXChildVisit_Break:
2009 return true;
2010 case CXChildVisit_Continue:
2011 break;
2012 case CXChildVisit_Recurse:
2013 EnqueueWorkList(WL, S);
2014 break;
2015 }
2016 }
2017 }
2018 continue;
2019 }
2020 case VisitorJob::MemberExprPartsKind: {
2021 // Handle the other pieces in the MemberExpr besides the base.
2022 MemberExpr *M = cast<MemberExprParts>(LI).get();
2023
2024 // Visit the nested-name-specifier
2025 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2026 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2027 return true;
2028
2029 // Visit the declaration name.
2030 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2031 return true;
2032
2033 // Visit the explicitly-specified template arguments, if any.
2034 if (M->hasExplicitTemplateArgs()) {
2035 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2036 *ArgEnd = Arg + M->getNumTemplateArgs();
2037 Arg != ArgEnd; ++Arg) {
2038 if (VisitTemplateArgumentLoc(*Arg))
2039 return true;
2040 }
2041 }
2042 continue;
2043 }
Ted Kremenek60458782010-11-12 21:34:16 +00002044 case VisitorJob::OverloadExprPartsKind: {
2045 OverloadExpr *O = cast<OverloadExprParts>(LI).get();
2046 // Visit the nested-name-specifier.
2047 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2048 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2049 return true;
2050 // Visit the declaration name.
2051 if (VisitDeclarationNameInfo(O->getNameInfo()))
2052 return true;
2053 // Visit the overloaded declaration reference.
2054 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2055 return true;
2056 // Visit the explicitly-specified template arguments.
2057 if (const ExplicitTemplateArgumentList *ArgList
2058 = O->getOptionalExplicitTemplateArgs()) {
2059 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2060 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2061 Arg != ArgEnd; ++Arg) {
2062 if (VisitTemplateArgumentLoc(*Arg))
2063 return true;
2064 }
2065 }
2066 continue;
2067 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002068 }
2069 }
2070 return false;
2071}
2072
2073bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2074 VisitorWorkList WL;
2075 EnqueueWorkList(WL, S);
2076 return RunVisitorWorkList(WL);
2077}
2078
2079//===----------------------------------------------------------------------===//
2080// Misc. API hooks.
2081//===----------------------------------------------------------------------===//
2082
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002083static llvm::sys::Mutex EnableMultithreadingMutex;
2084static bool EnabledMultithreading;
2085
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002086extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002087CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2088 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002089 // Disable pretty stack trace functionality, which will otherwise be a very
2090 // poor citizen of the world and set up all sorts of signal handlers.
2091 llvm::DisablePrettyStackTrace = true;
2092
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002093 // We use crash recovery to make some of our APIs more reliable, implicitly
2094 // enable it.
2095 llvm::CrashRecoveryContext::Enable();
2096
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002097 // Enable support for multithreading in LLVM.
2098 {
2099 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2100 if (!EnabledMultithreading) {
2101 llvm::llvm_start_multithreaded();
2102 EnabledMultithreading = true;
2103 }
2104 }
2105
Douglas Gregora030b7c2010-01-22 20:35:53 +00002106 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002107 if (excludeDeclarationsFromPCH)
2108 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002109 if (displayDiagnostics)
2110 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002111 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002112}
2113
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002114void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002115 if (CIdx)
2116 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002117}
2118
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002119CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002120 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002121 if (!CIdx)
2122 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002123
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002124 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002125 FileSystemOptions FileSystemOpts;
2126 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002127
Douglas Gregor28019772010-04-05 23:52:57 +00002128 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002129 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002130 CXXIdx->getOnlyLocalDecls(),
2131 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002132}
2133
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002134unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002135 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002136 CXTranslationUnit_CacheCompletionResults |
2137 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002138}
2139
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002140CXTranslationUnit
2141clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2142 const char *source_filename,
2143 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002144 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002145 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002146 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002147 return clang_parseTranslationUnit(CIdx, source_filename,
2148 command_line_args, num_command_line_args,
2149 unsaved_files, num_unsaved_files,
2150 CXTranslationUnit_DetailedPreprocessingRecord);
2151}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002152
2153struct ParseTranslationUnitInfo {
2154 CXIndex CIdx;
2155 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002156 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002157 int num_command_line_args;
2158 struct CXUnsavedFile *unsaved_files;
2159 unsigned num_unsaved_files;
2160 unsigned options;
2161 CXTranslationUnit result;
2162};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002163static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002164 ParseTranslationUnitInfo *PTUI =
2165 static_cast<ParseTranslationUnitInfo*>(UserData);
2166 CXIndex CIdx = PTUI->CIdx;
2167 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002168 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002169 int num_command_line_args = PTUI->num_command_line_args;
2170 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2171 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2172 unsigned options = PTUI->options;
2173 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002174
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002175 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002176 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002177
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002178 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2179
Douglas Gregor44c181a2010-07-23 00:33:23 +00002180 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002181 bool CompleteTranslationUnit
2182 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002183 bool CacheCodeCompetionResults
2184 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002185 bool CXXPrecompilePreamble
2186 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2187 bool CXXChainedPCH
2188 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002189
Douglas Gregor5352ac02010-01-28 00:27:43 +00002190 // Configure the diagnostics.
2191 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002192 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2193 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002194
Douglas Gregor4db64a42010-01-23 00:14:00 +00002195 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2196 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002197 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002198 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002199 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002200 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2201 Buffer));
2202 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002203
Douglas Gregorb10daed2010-10-11 16:52:23 +00002204 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002205
Ted Kremenek139ba862009-10-22 00:03:57 +00002206 // The 'source_filename' argument is optional. If the caller does not
2207 // specify it then it is assumed that the source file is specified
2208 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002209 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002210 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002211
2212 // Since the Clang C library is primarily used by batch tools dealing with
2213 // (often very broken) source code, where spell-checking can have a
2214 // significant negative impact on performance (particularly when
2215 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 // Only do this if we haven't found a spell-checking-related argument.
2217 bool FoundSpellCheckingArgument = false;
2218 for (int I = 0; I != num_command_line_args; ++I) {
2219 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2220 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2221 FoundSpellCheckingArgument = true;
2222 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002223 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002224 }
2225 if (!FoundSpellCheckingArgument)
2226 Args.push_back("-fno-spell-checking");
2227
2228 Args.insert(Args.end(), command_line_args,
2229 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002230
Douglas Gregor44c181a2010-07-23 00:33:23 +00002231 // Do we need the detailed preprocessing record?
2232 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002233 Args.push_back("-Xclang");
2234 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002235 }
2236
Douglas Gregorb10daed2010-10-11 16:52:23 +00002237 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002238 llvm::OwningPtr<ASTUnit> Unit(
2239 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2240 Diags,
2241 CXXIdx->getClangResourcesPath(),
2242 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002243 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002244 RemappedFiles.data(),
2245 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002246 PrecompilePreamble,
2247 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002248 CacheCodeCompetionResults,
2249 CXXPrecompilePreamble,
2250 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002251
Douglas Gregorb10daed2010-10-11 16:52:23 +00002252 if (NumErrors != Diags->getNumErrors()) {
2253 // Make sure to check that 'Unit' is non-NULL.
2254 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2255 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2256 DEnd = Unit->stored_diag_end();
2257 D != DEnd; ++D) {
2258 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2259 CXString Msg = clang_formatDiagnostic(&Diag,
2260 clang_defaultDiagnosticDisplayOptions());
2261 fprintf(stderr, "%s\n", clang_getCString(Msg));
2262 clang_disposeString(Msg);
2263 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002264#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002265 // On Windows, force a flush, since there may be multiple copies of
2266 // stderr and stdout in the file system, all with different buffers
2267 // but writing to the same device.
2268 fflush(stderr);
2269#endif
2270 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002271 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002272
Douglas Gregorb10daed2010-10-11 16:52:23 +00002273 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002274}
2275CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2276 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002277 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002278 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002279 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002280 unsigned num_unsaved_files,
2281 unsigned options) {
2282 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002283 num_command_line_args, unsaved_files,
2284 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002285 llvm::CrashRecoveryContext CRC;
2286
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002287 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002288 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2289 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2290 fprintf(stderr, " 'command_line_args' : [");
2291 for (int i = 0; i != num_command_line_args; ++i) {
2292 if (i)
2293 fprintf(stderr, ", ");
2294 fprintf(stderr, "'%s'", command_line_args[i]);
2295 }
2296 fprintf(stderr, "],\n");
2297 fprintf(stderr, " 'unsaved_files' : [");
2298 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2299 if (i)
2300 fprintf(stderr, ", ");
2301 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2302 unsaved_files[i].Length);
2303 }
2304 fprintf(stderr, "],\n");
2305 fprintf(stderr, " 'options' : %d,\n", options);
2306 fprintf(stderr, "}\n");
2307
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002308 return 0;
2309 }
2310
2311 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002312}
2313
Douglas Gregor19998442010-08-13 15:35:05 +00002314unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2315 return CXSaveTranslationUnit_None;
2316}
2317
2318int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2319 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002320 if (!TU)
2321 return 1;
2322
2323 return static_cast<ASTUnit *>(TU)->Save(FileName);
2324}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002325
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002326void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002327 if (CTUnit) {
2328 // If the translation unit has been marked as unsafe to free, just discard
2329 // it.
2330 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2331 return;
2332
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002333 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002334 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002335}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002336
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002337unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2338 return CXReparse_None;
2339}
2340
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002341struct ReparseTranslationUnitInfo {
2342 CXTranslationUnit TU;
2343 unsigned num_unsaved_files;
2344 struct CXUnsavedFile *unsaved_files;
2345 unsigned options;
2346 int result;
2347};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002348
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002349static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002350 ReparseTranslationUnitInfo *RTUI =
2351 static_cast<ReparseTranslationUnitInfo*>(UserData);
2352 CXTranslationUnit TU = RTUI->TU;
2353 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2354 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2355 unsigned options = RTUI->options;
2356 (void) options;
2357 RTUI->result = 1;
2358
Douglas Gregorabc563f2010-07-19 21:46:24 +00002359 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002360 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002361
2362 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2363 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002364
2365 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2366 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2367 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2368 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002369 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002370 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2371 Buffer));
2372 }
2373
Douglas Gregor593b0c12010-09-23 18:47:53 +00002374 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2375 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002376}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002377
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002378int clang_reparseTranslationUnit(CXTranslationUnit TU,
2379 unsigned num_unsaved_files,
2380 struct CXUnsavedFile *unsaved_files,
2381 unsigned options) {
2382 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2383 options, 0 };
2384 llvm::CrashRecoveryContext CRC;
2385
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002386 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002387 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002388 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2389 return 1;
2390 }
2391
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002392
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002393 return RTUI.result;
2394}
2395
Douglas Gregordf95a132010-08-09 20:45:32 +00002396
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002397CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002398 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002399 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002400
Steve Naroff77accc12009-09-03 18:19:54 +00002401 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002402 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002403}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002404
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002405CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002406 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002407 return Result;
2408}
2409
Ted Kremenekfb480492010-01-13 21:46:36 +00002410} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002411
Ted Kremenekfb480492010-01-13 21:46:36 +00002412//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002413// CXSourceLocation and CXSourceRange Operations.
2414//===----------------------------------------------------------------------===//
2415
Douglas Gregorb9790342010-01-22 21:44:22 +00002416extern "C" {
2417CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002418 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002419 return Result;
2420}
2421
2422unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002423 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2424 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2425 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002426}
2427
2428CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2429 CXFile file,
2430 unsigned line,
2431 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002432 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002433 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002434
Douglas Gregorb9790342010-01-22 21:44:22 +00002435 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2436 SourceLocation SLoc
2437 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002438 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002439 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002440 if (SLoc.isInvalid()) return clang_getNullLocation();
2441
2442 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2443}
2444
2445CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2446 CXFile file,
2447 unsigned offset) {
2448 if (!tu || !file)
2449 return clang_getNullLocation();
2450
2451 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2452 SourceLocation Start
2453 = CXXUnit->getSourceManager().getLocation(
2454 static_cast<const FileEntry *>(file),
2455 1, 1);
2456 if (Start.isInvalid()) return clang_getNullLocation();
2457
2458 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2459
2460 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002461
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002462 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002463}
2464
Douglas Gregor5352ac02010-01-28 00:27:43 +00002465CXSourceRange clang_getNullRange() {
2466 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2467 return Result;
2468}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002469
Douglas Gregor5352ac02010-01-28 00:27:43 +00002470CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2471 if (begin.ptr_data[0] != end.ptr_data[0] ||
2472 begin.ptr_data[1] != end.ptr_data[1])
2473 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002474
2475 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002476 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002477 return Result;
2478}
2479
Douglas Gregor46766dc2010-01-26 19:19:08 +00002480void clang_getInstantiationLocation(CXSourceLocation location,
2481 CXFile *file,
2482 unsigned *line,
2483 unsigned *column,
2484 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002485 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2486
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002487 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002488 if (file)
2489 *file = 0;
2490 if (line)
2491 *line = 0;
2492 if (column)
2493 *column = 0;
2494 if (offset)
2495 *offset = 0;
2496 return;
2497 }
2498
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002499 const SourceManager &SM =
2500 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002501 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002502
2503 if (file)
2504 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2505 if (line)
2506 *line = SM.getInstantiationLineNumber(InstLoc);
2507 if (column)
2508 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002509 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002510 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002511}
2512
Douglas Gregora9b06d42010-11-09 06:24:54 +00002513void clang_getSpellingLocation(CXSourceLocation location,
2514 CXFile *file,
2515 unsigned *line,
2516 unsigned *column,
2517 unsigned *offset) {
2518 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2519
2520 if (!location.ptr_data[0] || Loc.isInvalid()) {
2521 if (file)
2522 *file = 0;
2523 if (line)
2524 *line = 0;
2525 if (column)
2526 *column = 0;
2527 if (offset)
2528 *offset = 0;
2529 return;
2530 }
2531
2532 const SourceManager &SM =
2533 *static_cast<const SourceManager*>(location.ptr_data[0]);
2534 SourceLocation SpellLoc = Loc;
2535 if (SpellLoc.isMacroID()) {
2536 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2537 if (SimpleSpellingLoc.isFileID() &&
2538 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2539 SpellLoc = SimpleSpellingLoc;
2540 else
2541 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2542 }
2543
2544 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2545 FileID FID = LocInfo.first;
2546 unsigned FileOffset = LocInfo.second;
2547
2548 if (file)
2549 *file = (void *)SM.getFileEntryForID(FID);
2550 if (line)
2551 *line = SM.getLineNumber(FID, FileOffset);
2552 if (column)
2553 *column = SM.getColumnNumber(FID, FileOffset);
2554 if (offset)
2555 *offset = FileOffset;
2556}
2557
Douglas Gregor1db19de2010-01-19 21:36:55 +00002558CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002559 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002560 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002561 return Result;
2562}
2563
2564CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002565 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002566 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002567 return Result;
2568}
2569
Douglas Gregorb9790342010-01-22 21:44:22 +00002570} // end: extern "C"
2571
Douglas Gregor1db19de2010-01-19 21:36:55 +00002572//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002573// CXFile Operations.
2574//===----------------------------------------------------------------------===//
2575
2576extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002577CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002578 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002579 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002580
Steve Naroff88145032009-10-27 14:35:18 +00002581 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002582 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002583}
2584
2585time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002586 if (!SFile)
2587 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002588
Steve Naroff88145032009-10-27 14:35:18 +00002589 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2590 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002591}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
Douglas Gregorb9790342010-01-22 21:44:22 +00002593CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2594 if (!tu)
2595 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002596
Douglas Gregorb9790342010-01-22 21:44:22 +00002597 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Douglas Gregorb9790342010-01-22 21:44:22 +00002599 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002600 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2601 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002602 return const_cast<FileEntry *>(File);
2603}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002604
Ted Kremenekfb480492010-01-13 21:46:36 +00002605} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002606
Ted Kremenekfb480492010-01-13 21:46:36 +00002607//===----------------------------------------------------------------------===//
2608// CXCursor Operations.
2609//===----------------------------------------------------------------------===//
2610
Ted Kremenekfb480492010-01-13 21:46:36 +00002611static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002612 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2613 return getDeclFromExpr(CE->getSubExpr());
2614
Ted Kremenekfb480492010-01-13 21:46:36 +00002615 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2616 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002617 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2618 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002619 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2620 return ME->getMemberDecl();
2621 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2622 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002623 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2624 return PRE->getProperty();
2625
Ted Kremenekfb480492010-01-13 21:46:36 +00002626 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2627 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002628 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2629 if (!CE->isElidable())
2630 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002631 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2632 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002633
Douglas Gregordb1314e2010-10-01 21:11:22 +00002634 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2635 return PE->getProtocol();
2636
Ted Kremenekfb480492010-01-13 21:46:36 +00002637 return 0;
2638}
2639
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002640static SourceLocation getLocationFromExpr(Expr *E) {
2641 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2642 return /*FIXME:*/Msg->getLeftLoc();
2643 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2644 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002645 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2646 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002647 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2648 return Member->getMemberLoc();
2649 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2650 return Ivar->getLocation();
2651 return E->getLocStart();
2652}
2653
Ted Kremenekfb480492010-01-13 21:46:36 +00002654extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002655
2656unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002657 CXCursorVisitor visitor,
2658 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002659 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002660
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002661 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2662 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002663 return CursorVis.VisitChildren(parent);
2664}
2665
David Chisnall3387c652010-11-03 14:12:26 +00002666#ifndef __has_feature
2667#define __has_feature(x) 0
2668#endif
2669#if __has_feature(blocks)
2670typedef enum CXChildVisitResult
2671 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2672
2673static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2674 CXClientData client_data) {
2675 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2676 return block(cursor, parent);
2677}
2678#else
2679// If we are compiled with a compiler that doesn't have native blocks support,
2680// define and call the block manually, so the
2681typedef struct _CXChildVisitResult
2682{
2683 void *isa;
2684 int flags;
2685 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002686 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2687 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002688} *CXCursorVisitorBlock;
2689
2690static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2691 CXClientData client_data) {
2692 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2693 return block->invoke(block, cursor, parent);
2694}
2695#endif
2696
2697
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002698unsigned clang_visitChildrenWithBlock(CXCursor parent,
2699 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002700 return clang_visitChildren(parent, visitWithBlock, block);
2701}
2702
Douglas Gregor78205d42010-01-20 21:45:58 +00002703static CXString getDeclSpelling(Decl *D) {
2704 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2705 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002706 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002707
Douglas Gregor78205d42010-01-20 21:45:58 +00002708 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002709 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002710
Douglas Gregor78205d42010-01-20 21:45:58 +00002711 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2712 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2713 // and returns different names. NamedDecl returns the class name and
2714 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002715 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002716
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002717 if (isa<UsingDirectiveDecl>(D))
2718 return createCXString("");
2719
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002720 llvm::SmallString<1024> S;
2721 llvm::raw_svector_ostream os(S);
2722 ND->printName(os);
2723
2724 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002725}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002726
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002727CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002728 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002729 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002730
Steve Narofff334b4e2009-09-02 18:26:48 +00002731 if (clang_isReference(C.kind)) {
2732 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002733 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002734 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002735 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002736 }
2737 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002738 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002739 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002740 }
2741 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002742 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002743 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002744 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002745 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002746 case CXCursor_CXXBaseSpecifier: {
2747 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2748 return createCXString(B->getType().getAsString());
2749 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002750 case CXCursor_TypeRef: {
2751 TypeDecl *Type = getCursorTypeRef(C).first;
2752 assert(Type && "Missing type decl");
2753
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002754 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2755 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002756 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002757 case CXCursor_TemplateRef: {
2758 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002759 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002760
2761 return createCXString(Template->getNameAsString());
2762 }
Douglas Gregor69319002010-08-31 23:48:11 +00002763
2764 case CXCursor_NamespaceRef: {
2765 NamedDecl *NS = getCursorNamespaceRef(C).first;
2766 assert(NS && "Missing namespace decl");
2767
2768 return createCXString(NS->getNameAsString());
2769 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002770
Douglas Gregora67e03f2010-09-09 21:42:20 +00002771 case CXCursor_MemberRef: {
2772 FieldDecl *Field = getCursorMemberRef(C).first;
2773 assert(Field && "Missing member decl");
2774
2775 return createCXString(Field->getNameAsString());
2776 }
2777
Douglas Gregor36897b02010-09-10 00:22:18 +00002778 case CXCursor_LabelRef: {
2779 LabelStmt *Label = getCursorLabelRef(C).first;
2780 assert(Label && "Missing label");
2781
2782 return createCXString(Label->getID()->getName());
2783 }
2784
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002785 case CXCursor_OverloadedDeclRef: {
2786 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2787 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2788 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2789 return createCXString(ND->getNameAsString());
2790 return createCXString("");
2791 }
2792 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2793 return createCXString(E->getName().getAsString());
2794 OverloadedTemplateStorage *Ovl
2795 = Storage.get<OverloadedTemplateStorage*>();
2796 if (Ovl->size() == 0)
2797 return createCXString("");
2798 return createCXString((*Ovl->begin())->getNameAsString());
2799 }
2800
Daniel Dunbaracca7252009-11-30 20:42:49 +00002801 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002802 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002803 }
2804 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002805
2806 if (clang_isExpression(C.kind)) {
2807 Decl *D = getDeclFromExpr(getCursorExpr(C));
2808 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002809 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002810 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002811 }
2812
Douglas Gregor36897b02010-09-10 00:22:18 +00002813 if (clang_isStatement(C.kind)) {
2814 Stmt *S = getCursorStmt(C);
2815 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2816 return createCXString(Label->getID()->getName());
2817
2818 return createCXString("");
2819 }
2820
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002821 if (C.kind == CXCursor_MacroInstantiation)
2822 return createCXString(getCursorMacroInstantiation(C)->getName()
2823 ->getNameStart());
2824
Douglas Gregor572feb22010-03-18 18:04:21 +00002825 if (C.kind == CXCursor_MacroDefinition)
2826 return createCXString(getCursorMacroDefinition(C)->getName()
2827 ->getNameStart());
2828
Douglas Gregorecdcb882010-10-20 22:00:55 +00002829 if (C.kind == CXCursor_InclusionDirective)
2830 return createCXString(getCursorInclusionDirective(C)->getFileName());
2831
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002832 if (clang_isDeclaration(C.kind))
2833 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002834
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002835 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002836}
2837
Douglas Gregor358559d2010-10-02 22:49:11 +00002838CXString clang_getCursorDisplayName(CXCursor C) {
2839 if (!clang_isDeclaration(C.kind))
2840 return clang_getCursorSpelling(C);
2841
2842 Decl *D = getCursorDecl(C);
2843 if (!D)
2844 return createCXString("");
2845
2846 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2847 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2848 D = FunTmpl->getTemplatedDecl();
2849
2850 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2851 llvm::SmallString<64> Str;
2852 llvm::raw_svector_ostream OS(Str);
2853 OS << Function->getNameAsString();
2854 if (Function->getPrimaryTemplate())
2855 OS << "<>";
2856 OS << "(";
2857 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2858 if (I)
2859 OS << ", ";
2860 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2861 }
2862
2863 if (Function->isVariadic()) {
2864 if (Function->getNumParams())
2865 OS << ", ";
2866 OS << "...";
2867 }
2868 OS << ")";
2869 return createCXString(OS.str());
2870 }
2871
2872 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2873 llvm::SmallString<64> Str;
2874 llvm::raw_svector_ostream OS(Str);
2875 OS << ClassTemplate->getNameAsString();
2876 OS << "<";
2877 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2878 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2879 if (I)
2880 OS << ", ";
2881
2882 NamedDecl *Param = Params->getParam(I);
2883 if (Param->getIdentifier()) {
2884 OS << Param->getIdentifier()->getName();
2885 continue;
2886 }
2887
2888 // There is no parameter name, which makes this tricky. Try to come up
2889 // with something useful that isn't too long.
2890 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2891 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2892 else if (NonTypeTemplateParmDecl *NTTP
2893 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2894 OS << NTTP->getType().getAsString(Policy);
2895 else
2896 OS << "template<...> class";
2897 }
2898
2899 OS << ">";
2900 return createCXString(OS.str());
2901 }
2902
2903 if (ClassTemplateSpecializationDecl *ClassSpec
2904 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2905 // If the type was explicitly written, use that.
2906 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2907 return createCXString(TSInfo->getType().getAsString(Policy));
2908
2909 llvm::SmallString<64> Str;
2910 llvm::raw_svector_ostream OS(Str);
2911 OS << ClassSpec->getNameAsString();
2912 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002913 ClassSpec->getTemplateArgs().data(),
2914 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002915 Policy);
2916 return createCXString(OS.str());
2917 }
2918
2919 return clang_getCursorSpelling(C);
2920}
2921
Ted Kremeneke68fff62010-02-17 00:41:32 +00002922CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002923 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002924 case CXCursor_FunctionDecl:
2925 return createCXString("FunctionDecl");
2926 case CXCursor_TypedefDecl:
2927 return createCXString("TypedefDecl");
2928 case CXCursor_EnumDecl:
2929 return createCXString("EnumDecl");
2930 case CXCursor_EnumConstantDecl:
2931 return createCXString("EnumConstantDecl");
2932 case CXCursor_StructDecl:
2933 return createCXString("StructDecl");
2934 case CXCursor_UnionDecl:
2935 return createCXString("UnionDecl");
2936 case CXCursor_ClassDecl:
2937 return createCXString("ClassDecl");
2938 case CXCursor_FieldDecl:
2939 return createCXString("FieldDecl");
2940 case CXCursor_VarDecl:
2941 return createCXString("VarDecl");
2942 case CXCursor_ParmDecl:
2943 return createCXString("ParmDecl");
2944 case CXCursor_ObjCInterfaceDecl:
2945 return createCXString("ObjCInterfaceDecl");
2946 case CXCursor_ObjCCategoryDecl:
2947 return createCXString("ObjCCategoryDecl");
2948 case CXCursor_ObjCProtocolDecl:
2949 return createCXString("ObjCProtocolDecl");
2950 case CXCursor_ObjCPropertyDecl:
2951 return createCXString("ObjCPropertyDecl");
2952 case CXCursor_ObjCIvarDecl:
2953 return createCXString("ObjCIvarDecl");
2954 case CXCursor_ObjCInstanceMethodDecl:
2955 return createCXString("ObjCInstanceMethodDecl");
2956 case CXCursor_ObjCClassMethodDecl:
2957 return createCXString("ObjCClassMethodDecl");
2958 case CXCursor_ObjCImplementationDecl:
2959 return createCXString("ObjCImplementationDecl");
2960 case CXCursor_ObjCCategoryImplDecl:
2961 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002962 case CXCursor_CXXMethod:
2963 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002964 case CXCursor_UnexposedDecl:
2965 return createCXString("UnexposedDecl");
2966 case CXCursor_ObjCSuperClassRef:
2967 return createCXString("ObjCSuperClassRef");
2968 case CXCursor_ObjCProtocolRef:
2969 return createCXString("ObjCProtocolRef");
2970 case CXCursor_ObjCClassRef:
2971 return createCXString("ObjCClassRef");
2972 case CXCursor_TypeRef:
2973 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002974 case CXCursor_TemplateRef:
2975 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002976 case CXCursor_NamespaceRef:
2977 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002978 case CXCursor_MemberRef:
2979 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002980 case CXCursor_LabelRef:
2981 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002982 case CXCursor_OverloadedDeclRef:
2983 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002984 case CXCursor_UnexposedExpr:
2985 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002986 case CXCursor_BlockExpr:
2987 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002988 case CXCursor_DeclRefExpr:
2989 return createCXString("DeclRefExpr");
2990 case CXCursor_MemberRefExpr:
2991 return createCXString("MemberRefExpr");
2992 case CXCursor_CallExpr:
2993 return createCXString("CallExpr");
2994 case CXCursor_ObjCMessageExpr:
2995 return createCXString("ObjCMessageExpr");
2996 case CXCursor_UnexposedStmt:
2997 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002998 case CXCursor_LabelStmt:
2999 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003000 case CXCursor_InvalidFile:
3001 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003002 case CXCursor_InvalidCode:
3003 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003004 case CXCursor_NoDeclFound:
3005 return createCXString("NoDeclFound");
3006 case CXCursor_NotImplemented:
3007 return createCXString("NotImplemented");
3008 case CXCursor_TranslationUnit:
3009 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003010 case CXCursor_UnexposedAttr:
3011 return createCXString("UnexposedAttr");
3012 case CXCursor_IBActionAttr:
3013 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003014 case CXCursor_IBOutletAttr:
3015 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003016 case CXCursor_IBOutletCollectionAttr:
3017 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003018 case CXCursor_PreprocessingDirective:
3019 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003020 case CXCursor_MacroDefinition:
3021 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003022 case CXCursor_MacroInstantiation:
3023 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003024 case CXCursor_InclusionDirective:
3025 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003026 case CXCursor_Namespace:
3027 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003028 case CXCursor_LinkageSpec:
3029 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003030 case CXCursor_CXXBaseSpecifier:
3031 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003032 case CXCursor_Constructor:
3033 return createCXString("CXXConstructor");
3034 case CXCursor_Destructor:
3035 return createCXString("CXXDestructor");
3036 case CXCursor_ConversionFunction:
3037 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003038 case CXCursor_TemplateTypeParameter:
3039 return createCXString("TemplateTypeParameter");
3040 case CXCursor_NonTypeTemplateParameter:
3041 return createCXString("NonTypeTemplateParameter");
3042 case CXCursor_TemplateTemplateParameter:
3043 return createCXString("TemplateTemplateParameter");
3044 case CXCursor_FunctionTemplate:
3045 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003046 case CXCursor_ClassTemplate:
3047 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003048 case CXCursor_ClassTemplatePartialSpecialization:
3049 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003050 case CXCursor_NamespaceAlias:
3051 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003052 case CXCursor_UsingDirective:
3053 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003054 case CXCursor_UsingDeclaration:
3055 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003056 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003057
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003058 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003059 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003060}
Steve Naroff89922f82009-08-31 00:59:03 +00003061
Ted Kremeneke68fff62010-02-17 00:41:32 +00003062enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3063 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003064 CXClientData client_data) {
3065 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003066
3067 // If our current best cursor is the construction of a temporary object,
3068 // don't replace that cursor with a type reference, because we want
3069 // clang_getCursor() to point at the constructor.
3070 if (clang_isExpression(BestCursor->kind) &&
3071 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3072 cursor.kind == CXCursor_TypeRef)
3073 return CXChildVisit_Recurse;
3074
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003075 *BestCursor = cursor;
3076 return CXChildVisit_Recurse;
3077}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003078
Douglas Gregorb9790342010-01-22 21:44:22 +00003079CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3080 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003081 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003082
Douglas Gregorb9790342010-01-22 21:44:22 +00003083 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003084 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3085
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003086 // Translate the given source location to make it point at the beginning of
3087 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003088 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003089
3090 // Guard against an invalid SourceLocation, or we may assert in one
3091 // of the following calls.
3092 if (SLoc.isInvalid())
3093 return clang_getNullCursor();
3094
Douglas Gregor40749ee2010-11-03 00:35:38 +00003095 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003096 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3097 CXXUnit->getASTContext().getLangOptions());
3098
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003099 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3100 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003101 // FIXME: Would be great to have a "hint" cursor, then walk from that
3102 // hint cursor upward until we find a cursor whose source range encloses
3103 // the region of interest, rather than starting from the translation unit.
3104 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003105 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003106 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003107 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003108 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003109
3110 if (Logging) {
3111 CXFile SearchFile;
3112 unsigned SearchLine, SearchColumn;
3113 CXFile ResultFile;
3114 unsigned ResultLine, ResultColumn;
3115 CXString SearchFileName, ResultFileName, KindSpelling;
3116 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3117
3118 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3119 0);
3120 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3121 &ResultColumn, 0);
3122 SearchFileName = clang_getFileName(SearchFile);
3123 ResultFileName = clang_getFileName(ResultFile);
3124 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3125 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3126 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3127 clang_getCString(KindSpelling),
3128 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3129 clang_disposeString(SearchFileName);
3130 clang_disposeString(ResultFileName);
3131 clang_disposeString(KindSpelling);
3132 }
3133
Ted Kremeneke68fff62010-02-17 00:41:32 +00003134 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003135}
3136
Ted Kremenek73885552009-11-17 19:28:59 +00003137CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003138 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003139}
3140
3141unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003142 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003143}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003144
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003145unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003146 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3147}
3148
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003149unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003150 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3151}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003152
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003153unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003154 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3155}
3156
Douglas Gregor97b98722010-01-19 23:20:36 +00003157unsigned clang_isExpression(enum CXCursorKind K) {
3158 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3159}
3160
3161unsigned clang_isStatement(enum CXCursorKind K) {
3162 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3163}
3164
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003165unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3166 return K == CXCursor_TranslationUnit;
3167}
3168
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003169unsigned clang_isPreprocessing(enum CXCursorKind K) {
3170 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3171}
3172
Ted Kremenekad6eff62010-03-08 21:17:29 +00003173unsigned clang_isUnexposed(enum CXCursorKind K) {
3174 switch (K) {
3175 case CXCursor_UnexposedDecl:
3176 case CXCursor_UnexposedExpr:
3177 case CXCursor_UnexposedStmt:
3178 case CXCursor_UnexposedAttr:
3179 return true;
3180 default:
3181 return false;
3182 }
3183}
3184
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003185CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003186 return C.kind;
3187}
3188
Douglas Gregor98258af2010-01-18 22:46:11 +00003189CXSourceLocation clang_getCursorLocation(CXCursor C) {
3190 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003191 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003192 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003193 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3194 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003195 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003196 }
3197
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003198 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003199 std::pair<ObjCProtocolDecl *, SourceLocation> P
3200 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003201 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003202 }
3203
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003204 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003205 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3206 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003207 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003208 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003209
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003210 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003211 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003212 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003213 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003214
3215 case CXCursor_TemplateRef: {
3216 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3217 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3218 }
3219
Douglas Gregor69319002010-08-31 23:48:11 +00003220 case CXCursor_NamespaceRef: {
3221 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3222 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3223 }
3224
Douglas Gregora67e03f2010-09-09 21:42:20 +00003225 case CXCursor_MemberRef: {
3226 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3227 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3228 }
3229
Ted Kremenek3064ef92010-08-27 21:34:58 +00003230 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003231 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3232 if (!BaseSpec)
3233 return clang_getNullLocation();
3234
3235 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3236 return cxloc::translateSourceLocation(getCursorContext(C),
3237 TSInfo->getTypeLoc().getBeginLoc());
3238
3239 return cxloc::translateSourceLocation(getCursorContext(C),
3240 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003241 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003242
Douglas Gregor36897b02010-09-10 00:22:18 +00003243 case CXCursor_LabelRef: {
3244 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3245 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3246 }
3247
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003248 case CXCursor_OverloadedDeclRef:
3249 return cxloc::translateSourceLocation(getCursorContext(C),
3250 getCursorOverloadedDeclRef(C).second);
3251
Douglas Gregorf46034a2010-01-18 23:41:10 +00003252 default:
3253 // FIXME: Need a way to enumerate all non-reference cases.
3254 llvm_unreachable("Missed a reference kind");
3255 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003256 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003257
3258 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003259 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003260 getLocationFromExpr(getCursorExpr(C)));
3261
Douglas Gregor36897b02010-09-10 00:22:18 +00003262 if (clang_isStatement(C.kind))
3263 return cxloc::translateSourceLocation(getCursorContext(C),
3264 getCursorStmt(C)->getLocStart());
3265
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003266 if (C.kind == CXCursor_PreprocessingDirective) {
3267 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3268 return cxloc::translateSourceLocation(getCursorContext(C), L);
3269 }
Douglas Gregor48072312010-03-18 15:23:44 +00003270
3271 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003272 SourceLocation L
3273 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003274 return cxloc::translateSourceLocation(getCursorContext(C), L);
3275 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003276
3277 if (C.kind == CXCursor_MacroDefinition) {
3278 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3279 return cxloc::translateSourceLocation(getCursorContext(C), L);
3280 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003281
3282 if (C.kind == CXCursor_InclusionDirective) {
3283 SourceLocation L
3284 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3285 return cxloc::translateSourceLocation(getCursorContext(C), L);
3286 }
3287
Ted Kremenek9a700d22010-05-12 06:16:13 +00003288 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003289 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003290
Douglas Gregorf46034a2010-01-18 23:41:10 +00003291 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003292 SourceLocation Loc = D->getLocation();
3293 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3294 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003295 // FIXME: Multiple variables declared in a single declaration
3296 // currently lack the information needed to correctly determine their
3297 // ranges when accounting for the type-specifier. We use context
3298 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3299 // and if so, whether it is the first decl.
3300 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3301 if (!cxcursor::isFirstInDeclGroup(C))
3302 Loc = VD->getLocation();
3303 }
3304
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003305 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003306}
Douglas Gregora7bde202010-01-19 00:34:46 +00003307
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003308} // end extern "C"
3309
3310static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003311 if (clang_isReference(C.kind)) {
3312 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003313 case CXCursor_ObjCSuperClassRef:
3314 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003315
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003316 case CXCursor_ObjCProtocolRef:
3317 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003318
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003319 case CXCursor_ObjCClassRef:
3320 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003321
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003322 case CXCursor_TypeRef:
3323 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003324
3325 case CXCursor_TemplateRef:
3326 return getCursorTemplateRef(C).second;
3327
Douglas Gregor69319002010-08-31 23:48:11 +00003328 case CXCursor_NamespaceRef:
3329 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003330
3331 case CXCursor_MemberRef:
3332 return getCursorMemberRef(C).second;
3333
Ted Kremenek3064ef92010-08-27 21:34:58 +00003334 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003335 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003336
Douglas Gregor36897b02010-09-10 00:22:18 +00003337 case CXCursor_LabelRef:
3338 return getCursorLabelRef(C).second;
3339
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003340 case CXCursor_OverloadedDeclRef:
3341 return getCursorOverloadedDeclRef(C).second;
3342
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003343 default:
3344 // FIXME: Need a way to enumerate all non-reference cases.
3345 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003346 }
3347 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003348
3349 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003350 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003351
3352 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003353 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003354
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003355 if (C.kind == CXCursor_PreprocessingDirective)
3356 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003357
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003358 if (C.kind == CXCursor_MacroInstantiation)
3359 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003360
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003361 if (C.kind == CXCursor_MacroDefinition)
3362 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003363
3364 if (C.kind == CXCursor_InclusionDirective)
3365 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3366
Ted Kremenek007a7c92010-11-01 23:26:51 +00003367 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3368 Decl *D = cxcursor::getCursorDecl(C);
3369 SourceRange R = D->getSourceRange();
3370 // FIXME: Multiple variables declared in a single declaration
3371 // currently lack the information needed to correctly determine their
3372 // ranges when accounting for the type-specifier. We use context
3373 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3374 // and if so, whether it is the first decl.
3375 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3376 if (!cxcursor::isFirstInDeclGroup(C))
3377 R.setBegin(VD->getLocation());
3378 }
3379 return R;
3380 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003381 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003382
3383extern "C" {
3384
3385CXSourceRange clang_getCursorExtent(CXCursor C) {
3386 SourceRange R = getRawCursorExtent(C);
3387 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003388 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003389
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003390 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003391}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003392
3393CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003394 if (clang_isInvalid(C.kind))
3395 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003396
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003397 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003398 if (clang_isDeclaration(C.kind)) {
3399 Decl *D = getCursorDecl(C);
3400 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3401 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3402 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3403 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3404 if (ObjCForwardProtocolDecl *Protocols
3405 = dyn_cast<ObjCForwardProtocolDecl>(D))
3406 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3407
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003408 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003409 }
3410
Douglas Gregor97b98722010-01-19 23:20:36 +00003411 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003412 Expr *E = getCursorExpr(C);
3413 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003414 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003415 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003416
3417 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3418 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3419
Douglas Gregor97b98722010-01-19 23:20:36 +00003420 return clang_getNullCursor();
3421 }
3422
Douglas Gregor36897b02010-09-10 00:22:18 +00003423 if (clang_isStatement(C.kind)) {
3424 Stmt *S = getCursorStmt(C);
3425 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3426 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3427 getCursorASTUnit(C));
3428
3429 return clang_getNullCursor();
3430 }
3431
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003432 if (C.kind == CXCursor_MacroInstantiation) {
3433 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3434 return MakeMacroDefinitionCursor(Def, CXXUnit);
3435 }
3436
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003437 if (!clang_isReference(C.kind))
3438 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003439
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003440 switch (C.kind) {
3441 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003442 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003443
3444 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003445 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003446
3447 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003448 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003449
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003450 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003451 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003452
3453 case CXCursor_TemplateRef:
3454 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3455
Douglas Gregor69319002010-08-31 23:48:11 +00003456 case CXCursor_NamespaceRef:
3457 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3458
Douglas Gregora67e03f2010-09-09 21:42:20 +00003459 case CXCursor_MemberRef:
3460 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3461
Ted Kremenek3064ef92010-08-27 21:34:58 +00003462 case CXCursor_CXXBaseSpecifier: {
3463 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3464 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3465 CXXUnit));
3466 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003467
Douglas Gregor36897b02010-09-10 00:22:18 +00003468 case CXCursor_LabelRef:
3469 // FIXME: We end up faking the "parent" declaration here because we
3470 // don't want to make CXCursor larger.
3471 return MakeCXCursor(getCursorLabelRef(C).first,
3472 CXXUnit->getASTContext().getTranslationUnitDecl(),
3473 CXXUnit);
3474
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003475 case CXCursor_OverloadedDeclRef:
3476 return C;
3477
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003478 default:
3479 // We would prefer to enumerate all non-reference cursor kinds here.
3480 llvm_unreachable("Unhandled reference cursor kind");
3481 break;
3482 }
3483 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003484
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003485 return clang_getNullCursor();
3486}
3487
Douglas Gregorb6998662010-01-19 19:34:47 +00003488CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003489 if (clang_isInvalid(C.kind))
3490 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003491
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003492 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003493
Douglas Gregorb6998662010-01-19 19:34:47 +00003494 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003495 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003496 C = clang_getCursorReferenced(C);
3497 WasReference = true;
3498 }
3499
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003500 if (C.kind == CXCursor_MacroInstantiation)
3501 return clang_getCursorReferenced(C);
3502
Douglas Gregorb6998662010-01-19 19:34:47 +00003503 if (!clang_isDeclaration(C.kind))
3504 return clang_getNullCursor();
3505
3506 Decl *D = getCursorDecl(C);
3507 if (!D)
3508 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003509
Douglas Gregorb6998662010-01-19 19:34:47 +00003510 switch (D->getKind()) {
3511 // Declaration kinds that don't really separate the notions of
3512 // declaration and definition.
3513 case Decl::Namespace:
3514 case Decl::Typedef:
3515 case Decl::TemplateTypeParm:
3516 case Decl::EnumConstant:
3517 case Decl::Field:
3518 case Decl::ObjCIvar:
3519 case Decl::ObjCAtDefsField:
3520 case Decl::ImplicitParam:
3521 case Decl::ParmVar:
3522 case Decl::NonTypeTemplateParm:
3523 case Decl::TemplateTemplateParm:
3524 case Decl::ObjCCategoryImpl:
3525 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003526 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003527 case Decl::LinkageSpec:
3528 case Decl::ObjCPropertyImpl:
3529 case Decl::FileScopeAsm:
3530 case Decl::StaticAssert:
3531 case Decl::Block:
3532 return C;
3533
3534 // Declaration kinds that don't make any sense here, but are
3535 // nonetheless harmless.
3536 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003537 break;
3538
3539 // Declaration kinds for which the definition is not resolvable.
3540 case Decl::UnresolvedUsingTypename:
3541 case Decl::UnresolvedUsingValue:
3542 break;
3543
3544 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003545 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3546 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003547
3548 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003549 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003550
3551 case Decl::Enum:
3552 case Decl::Record:
3553 case Decl::CXXRecord:
3554 case Decl::ClassTemplateSpecialization:
3555 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003556 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003557 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003558 return clang_getNullCursor();
3559
3560 case Decl::Function:
3561 case Decl::CXXMethod:
3562 case Decl::CXXConstructor:
3563 case Decl::CXXDestructor:
3564 case Decl::CXXConversion: {
3565 const FunctionDecl *Def = 0;
3566 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003567 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003568 return clang_getNullCursor();
3569 }
3570
3571 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003572 // Ask the variable if it has a definition.
3573 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3574 return MakeCXCursor(Def, CXXUnit);
3575 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003576 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003577
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 case Decl::FunctionTemplate: {
3579 const FunctionDecl *Def = 0;
3580 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003581 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003582 return clang_getNullCursor();
3583 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003584
Douglas Gregorb6998662010-01-19 19:34:47 +00003585 case Decl::ClassTemplate: {
3586 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003587 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003588 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003589 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003590 return clang_getNullCursor();
3591 }
3592
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003593 case Decl::Using:
3594 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3595 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003596
3597 case Decl::UsingShadow:
3598 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003599 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003600 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003601
3602 case Decl::ObjCMethod: {
3603 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3604 if (Method->isThisDeclarationADefinition())
3605 return C;
3606
3607 // Dig out the method definition in the associated
3608 // @implementation, if we have it.
3609 // FIXME: The ASTs should make finding the definition easier.
3610 if (ObjCInterfaceDecl *Class
3611 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3612 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3613 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3614 Method->isInstanceMethod()))
3615 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003616 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003617
3618 return clang_getNullCursor();
3619 }
3620
3621 case Decl::ObjCCategory:
3622 if (ObjCCategoryImplDecl *Impl
3623 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003624 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003625 return clang_getNullCursor();
3626
3627 case Decl::ObjCProtocol:
3628 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3629 return C;
3630 return clang_getNullCursor();
3631
3632 case Decl::ObjCInterface:
3633 // There are two notions of a "definition" for an Objective-C
3634 // class: the interface and its implementation. When we resolved a
3635 // reference to an Objective-C class, produce the @interface as
3636 // the definition; when we were provided with the interface,
3637 // produce the @implementation as the definition.
3638 if (WasReference) {
3639 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3640 return C;
3641 } else if (ObjCImplementationDecl *Impl
3642 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003643 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003644 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003645
Douglas Gregorb6998662010-01-19 19:34:47 +00003646 case Decl::ObjCProperty:
3647 // FIXME: We don't really know where to find the
3648 // ObjCPropertyImplDecls that implement this property.
3649 return clang_getNullCursor();
3650
3651 case Decl::ObjCCompatibleAlias:
3652 if (ObjCInterfaceDecl *Class
3653 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3654 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003655 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003656
Douglas Gregorb6998662010-01-19 19:34:47 +00003657 return clang_getNullCursor();
3658
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003659 case Decl::ObjCForwardProtocol:
3660 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3661 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003662
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003663 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003664 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003665 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003666
3667 case Decl::Friend:
3668 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003669 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003670 return clang_getNullCursor();
3671
3672 case Decl::FriendTemplate:
3673 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003674 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003675 return clang_getNullCursor();
3676 }
3677
3678 return clang_getNullCursor();
3679}
3680
3681unsigned clang_isCursorDefinition(CXCursor C) {
3682 if (!clang_isDeclaration(C.kind))
3683 return 0;
3684
3685 return clang_getCursorDefinition(C) == C;
3686}
3687
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003688unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003689 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003690 return 0;
3691
3692 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3693 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3694 return E->getNumDecls();
3695
3696 if (OverloadedTemplateStorage *S
3697 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3698 return S->size();
3699
3700 Decl *D = Storage.get<Decl*>();
3701 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003702 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003703 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3704 return Classes->size();
3705 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3706 return Protocols->protocol_size();
3707
3708 return 0;
3709}
3710
3711CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003712 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003713 return clang_getNullCursor();
3714
3715 if (index >= clang_getNumOverloadedDecls(cursor))
3716 return clang_getNullCursor();
3717
3718 ASTUnit *Unit = getCursorASTUnit(cursor);
3719 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3720 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3721 return MakeCXCursor(E->decls_begin()[index], Unit);
3722
3723 if (OverloadedTemplateStorage *S
3724 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3725 return MakeCXCursor(S->begin()[index], Unit);
3726
3727 Decl *D = Storage.get<Decl*>();
3728 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3729 // FIXME: This is, unfortunately, linear time.
3730 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3731 std::advance(Pos, index);
3732 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3733 }
3734
3735 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3736 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3737
3738 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3739 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3740
3741 return clang_getNullCursor();
3742}
3743
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003744void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003745 const char **startBuf,
3746 const char **endBuf,
3747 unsigned *startLine,
3748 unsigned *startColumn,
3749 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003750 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003751 assert(getCursorDecl(C) && "CXCursor has null decl");
3752 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003753 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3754 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003755
Steve Naroff4ade6d62009-09-23 17:52:52 +00003756 SourceManager &SM = FD->getASTContext().getSourceManager();
3757 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3758 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3759 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3760 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3761 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3762 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3763}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003764
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003765void clang_enableStackTraces(void) {
3766 llvm::sys::PrintStackTraceOnErrorSignal();
3767}
3768
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003769void clang_executeOnThread(void (*fn)(void*), void *user_data,
3770 unsigned stack_size) {
3771 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3772}
3773
Ted Kremenekfb480492010-01-13 21:46:36 +00003774} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003775
Ted Kremenekfb480492010-01-13 21:46:36 +00003776//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003777// Token-based Operations.
3778//===----------------------------------------------------------------------===//
3779
3780/* CXToken layout:
3781 * int_data[0]: a CXTokenKind
3782 * int_data[1]: starting token location
3783 * int_data[2]: token length
3784 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003785 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003786 * otherwise unused.
3787 */
3788extern "C" {
3789
3790CXTokenKind clang_getTokenKind(CXToken CXTok) {
3791 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3792}
3793
3794CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3795 switch (clang_getTokenKind(CXTok)) {
3796 case CXToken_Identifier:
3797 case CXToken_Keyword:
3798 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003799 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3800 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003801
3802 case CXToken_Literal: {
3803 // We have stashed the starting pointer in the ptr_data field. Use it.
3804 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003805 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003806 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003807
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003808 case CXToken_Punctuation:
3809 case CXToken_Comment:
3810 break;
3811 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003812
3813 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003814 // deconstructing the source location.
3815 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3816 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003817 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003818
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003819 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3820 std::pair<FileID, unsigned> LocInfo
3821 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003822 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003823 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003824 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3825 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003826 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003827
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003828 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003829}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003830
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003831CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3832 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3833 if (!CXXUnit)
3834 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003836 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3837 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3838}
3839
3840CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3841 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003842 if (!CXXUnit)
3843 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003844
3845 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003846 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3847}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003848
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003849void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3850 CXToken **Tokens, unsigned *NumTokens) {
3851 if (Tokens)
3852 *Tokens = 0;
3853 if (NumTokens)
3854 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003855
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003856 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3857 if (!CXXUnit || !Tokens || !NumTokens)
3858 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregorbdf60622010-03-05 21:16:25 +00003860 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3861
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003862 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003863 if (R.isInvalid())
3864 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003865
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003866 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3867 std::pair<FileID, unsigned> BeginLocInfo
3868 = SourceMgr.getDecomposedLoc(R.getBegin());
3869 std::pair<FileID, unsigned> EndLocInfo
3870 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003871
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003872 // Cannot tokenize across files.
3873 if (BeginLocInfo.first != EndLocInfo.first)
3874 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003875
3876 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003877 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003878 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003879 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003880 if (Invalid)
3881 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003882
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003883 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3884 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003885 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003886 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003888 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003889 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 llvm::SmallVector<CXToken, 32> CXTokens;
3891 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003892 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893 do {
3894 // Lex the next token
3895 Lex.LexFromRawLexer(Tok);
3896 if (Tok.is(tok::eof))
3897 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003898
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003899 // Initialize the CXToken.
3900 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003901
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003902 // - Common fields
3903 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3904 CXTok.int_data[2] = Tok.getLength();
3905 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003906
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003907 // - Kind-specific fields
3908 if (Tok.isLiteral()) {
3909 CXTok.int_data[0] = CXToken_Literal;
3910 CXTok.ptr_data = (void *)Tok.getLiteralData();
3911 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003912 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003913 std::pair<FileID, unsigned> LocInfo
3914 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003915 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003916 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003917 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3918 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003919 return;
3920
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003921 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003922 IdentifierInfo *II
3923 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003924
David Chisnall096428b2010-10-13 21:44:48 +00003925 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003926 CXTok.int_data[0] = CXToken_Keyword;
3927 }
3928 else {
3929 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3930 CXToken_Identifier
3931 : CXToken_Keyword;
3932 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003933 CXTok.ptr_data = II;
3934 } else if (Tok.is(tok::comment)) {
3935 CXTok.int_data[0] = CXToken_Comment;
3936 CXTok.ptr_data = 0;
3937 } else {
3938 CXTok.int_data[0] = CXToken_Punctuation;
3939 CXTok.ptr_data = 0;
3940 }
3941 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003942 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003943 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003944
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003945 if (CXTokens.empty())
3946 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003947
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003948 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3949 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3950 *NumTokens = CXTokens.size();
3951}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003952
Ted Kremenek6db61092010-05-05 00:55:15 +00003953void clang_disposeTokens(CXTranslationUnit TU,
3954 CXToken *Tokens, unsigned NumTokens) {
3955 free(Tokens);
3956}
3957
3958} // end: extern "C"
3959
3960//===----------------------------------------------------------------------===//
3961// Token annotation APIs.
3962//===----------------------------------------------------------------------===//
3963
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003964typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003965static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3966 CXCursor parent,
3967 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003968namespace {
3969class AnnotateTokensWorker {
3970 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003971 CXToken *Tokens;
3972 CXCursor *Cursors;
3973 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003974 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003975 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003976 CursorVisitor AnnotateVis;
3977 SourceManager &SrcMgr;
3978
3979 bool MoreTokens() const { return TokIdx < NumTokens; }
3980 unsigned NextToken() const { return TokIdx; }
3981 void AdvanceToken() { ++TokIdx; }
3982 SourceLocation GetTokenLoc(unsigned tokI) {
3983 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3984 }
3985
Ted Kremenek6db61092010-05-05 00:55:15 +00003986public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003987 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003988 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3989 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003990 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003991 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003992 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3993 Decl::MaxPCHLevel, RegionOfInterest),
3994 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003995
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003996 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003997 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003998 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003999 void AnnotateTokens() {
4000 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
4001 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004002};
4003}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004004
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004005void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4006 // Walk the AST within the region of interest, annotating tokens
4007 // along the way.
4008 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004009
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004010 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4011 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004012 if (Pos != Annotated.end() &&
4013 (clang_isInvalid(Cursors[I].kind) ||
4014 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004015 Cursors[I] = Pos->second;
4016 }
4017
4018 // Finish up annotating any tokens left.
4019 if (!MoreTokens())
4020 return;
4021
4022 const CXCursor &C = clang_getNullCursor();
4023 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4024 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4025 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004026 }
4027}
4028
Ted Kremenek6db61092010-05-05 00:55:15 +00004029enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004030AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004031 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004032 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004033 if (cursorRange.isInvalid())
4034 return CXChildVisit_Recurse;
4035
Douglas Gregor4419b672010-10-21 06:10:04 +00004036 if (clang_isPreprocessing(cursor.kind)) {
4037 // For macro instantiations, just note where the beginning of the macro
4038 // instantiation occurs.
4039 if (cursor.kind == CXCursor_MacroInstantiation) {
4040 Annotated[Loc.int_data] = cursor;
4041 return CXChildVisit_Recurse;
4042 }
4043
Douglas Gregor4419b672010-10-21 06:10:04 +00004044 // Items in the preprocessing record are kept separate from items in
4045 // declarations, so we keep a separate token index.
4046 unsigned SavedTokIdx = TokIdx;
4047 TokIdx = PreprocessingTokIdx;
4048
4049 // Skip tokens up until we catch up to the beginning of the preprocessing
4050 // entry.
4051 while (MoreTokens()) {
4052 const unsigned I = NextToken();
4053 SourceLocation TokLoc = GetTokenLoc(I);
4054 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4055 case RangeBefore:
4056 AdvanceToken();
4057 continue;
4058 case RangeAfter:
4059 case RangeOverlap:
4060 break;
4061 }
4062 break;
4063 }
4064
4065 // Look at all of the tokens within this range.
4066 while (MoreTokens()) {
4067 const unsigned I = NextToken();
4068 SourceLocation TokLoc = GetTokenLoc(I);
4069 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4070 case RangeBefore:
4071 assert(0 && "Infeasible");
4072 case RangeAfter:
4073 break;
4074 case RangeOverlap:
4075 Cursors[I] = cursor;
4076 AdvanceToken();
4077 continue;
4078 }
4079 break;
4080 }
4081
4082 // Save the preprocessing token index; restore the non-preprocessing
4083 // token index.
4084 PreprocessingTokIdx = TokIdx;
4085 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004086 return CXChildVisit_Recurse;
4087 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004088
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004089 if (cursorRange.isInvalid())
4090 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004091
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004092 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4093
Ted Kremeneka333c662010-05-12 05:29:33 +00004094 // Adjust the annotated range based specific declarations.
4095 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4096 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004097 Decl *D = cxcursor::getCursorDecl(cursor);
4098 // Don't visit synthesized ObjC methods, since they have no syntatic
4099 // representation in the source.
4100 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4101 if (MD->isSynthesized())
4102 return CXChildVisit_Continue;
4103 }
4104 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004105 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4106 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004107 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004108 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004109 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004110 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004111 }
4112 }
4113 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004114
Ted Kremenek3f404602010-08-14 01:14:06 +00004115 // If the location of the cursor occurs within a macro instantiation, record
4116 // the spelling location of the cursor in our annotation map. We can then
4117 // paper over the token labelings during a post-processing step to try and
4118 // get cursor mappings for tokens that are the *arguments* of a macro
4119 // instantiation.
4120 if (L.isMacroID()) {
4121 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4122 // Only invalidate the old annotation if it isn't part of a preprocessing
4123 // directive. Here we assume that the default construction of CXCursor
4124 // results in CXCursor.kind being an initialized value (i.e., 0). If
4125 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004126
Ted Kremenek3f404602010-08-14 01:14:06 +00004127 CXCursor &oldC = Annotated[rawEncoding];
4128 if (!clang_isPreprocessing(oldC.kind))
4129 oldC = cursor;
4130 }
4131
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004132 const enum CXCursorKind K = clang_getCursorKind(parent);
4133 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004134 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4135 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004136
4137 while (MoreTokens()) {
4138 const unsigned I = NextToken();
4139 SourceLocation TokLoc = GetTokenLoc(I);
4140 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4141 case RangeBefore:
4142 Cursors[I] = updateC;
4143 AdvanceToken();
4144 continue;
4145 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004146 case RangeOverlap:
4147 break;
4148 }
4149 break;
4150 }
4151
4152 // Visit children to get their cursor information.
4153 const unsigned BeforeChildren = NextToken();
4154 VisitChildren(cursor);
4155 const unsigned AfterChildren = NextToken();
4156
4157 // Adjust 'Last' to the last token within the extent of the cursor.
4158 while (MoreTokens()) {
4159 const unsigned I = NextToken();
4160 SourceLocation TokLoc = GetTokenLoc(I);
4161 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4162 case RangeBefore:
4163 assert(0 && "Infeasible");
4164 case RangeAfter:
4165 break;
4166 case RangeOverlap:
4167 Cursors[I] = updateC;
4168 AdvanceToken();
4169 continue;
4170 }
4171 break;
4172 }
4173 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004174
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004175 // Scan the tokens that are at the beginning of the cursor, but are not
4176 // capture by the child cursors.
4177
4178 // For AST elements within macros, rely on a post-annotate pass to
4179 // to correctly annotate the tokens with cursors. Otherwise we can
4180 // get confusing results of having tokens that map to cursors that really
4181 // are expanded by an instantiation.
4182 if (L.isMacroID())
4183 cursor = clang_getNullCursor();
4184
4185 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4186 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4187 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004188
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004189 Cursors[I] = cursor;
4190 }
4191 // Scan the tokens that are at the end of the cursor, but are not captured
4192 // but the child cursors.
4193 for (unsigned I = AfterChildren; I != Last; ++I)
4194 Cursors[I] = cursor;
4195
4196 TokIdx = Last;
4197 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004198}
4199
Ted Kremenek6db61092010-05-05 00:55:15 +00004200static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4201 CXCursor parent,
4202 CXClientData client_data) {
4203 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4204}
4205
Ted Kremenekab979612010-11-11 08:05:23 +00004206// This gets run a separate thread to avoid stack blowout.
4207static void runAnnotateTokensWorker(void *UserData) {
4208 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4209}
4210
Ted Kremenek6db61092010-05-05 00:55:15 +00004211extern "C" {
4212
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004213void clang_annotateTokens(CXTranslationUnit TU,
4214 CXToken *Tokens, unsigned NumTokens,
4215 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004216
4217 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004218 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004219
Douglas Gregor4419b672010-10-21 06:10:04 +00004220 // Any token we don't specifically annotate will have a NULL cursor.
4221 CXCursor C = clang_getNullCursor();
4222 for (unsigned I = 0; I != NumTokens; ++I)
4223 Cursors[I] = C;
4224
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004225 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004226 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004227 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004228
Douglas Gregorbdf60622010-03-05 21:16:25 +00004229 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004230
Douglas Gregor0396f462010-03-19 05:22:59 +00004231 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004232 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004233 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4234 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004235 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4236 clang_getTokenLocation(TU,
4237 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238
Douglas Gregor0396f462010-03-19 05:22:59 +00004239 // A mapping from the source locations found when re-lexing or traversing the
4240 // region of interest to the corresponding cursors.
4241 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004242
4243 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004244 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4246 std::pair<FileID, unsigned> BeginLocInfo
4247 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4248 std::pair<FileID, unsigned> EndLocInfo
4249 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004250
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004251 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004252 bool Invalid = false;
4253 if (BeginLocInfo.first == EndLocInfo.first &&
4254 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4255 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004256 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4257 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004258 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004259 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004260 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004261
4262 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004263 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004264 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004265 Token Tok;
4266 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004267
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004268 reprocess:
4269 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4270 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004271 // don't see it while preprocessing these tokens later, but keep track
4272 // of all of the token locations inside this preprocessing directive so
4273 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004274 //
4275 // FIXME: Some simple tests here could identify macro definitions and
4276 // #undefs, to provide specific cursor kinds for those.
4277 std::vector<SourceLocation> Locations;
4278 do {
4279 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004280 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004281 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004282
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004283 using namespace cxcursor;
4284 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4286 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004287 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004288 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4289 Annotated[Locations[I].getRawEncoding()] = Cursor;
4290 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004291
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004292 if (Tok.isAtStartOfLine())
4293 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004294
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004295 continue;
4296 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004297
Douglas Gregor48072312010-03-18 15:23:44 +00004298 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004299 break;
4300 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004301 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004302
Douglas Gregor0396f462010-03-19 05:22:59 +00004303 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004304 // a specific cursor.
4305 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4306 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004307
4308 // Run the worker within a CrashRecoveryContext.
4309 llvm::CrashRecoveryContext CRC;
4310 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4311 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4312 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004313}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004314} // end: extern "C"
4315
4316//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004317// Operations for querying linkage of a cursor.
4318//===----------------------------------------------------------------------===//
4319
4320extern "C" {
4321CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004322 if (!clang_isDeclaration(cursor.kind))
4323 return CXLinkage_Invalid;
4324
Ted Kremenek16b42592010-03-03 06:36:57 +00004325 Decl *D = cxcursor::getCursorDecl(cursor);
4326 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4327 switch (ND->getLinkage()) {
4328 case NoLinkage: return CXLinkage_NoLinkage;
4329 case InternalLinkage: return CXLinkage_Internal;
4330 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4331 case ExternalLinkage: return CXLinkage_External;
4332 };
4333
4334 return CXLinkage_Invalid;
4335}
4336} // end: extern "C"
4337
4338//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004339// Operations for querying language of a cursor.
4340//===----------------------------------------------------------------------===//
4341
4342static CXLanguageKind getDeclLanguage(const Decl *D) {
4343 switch (D->getKind()) {
4344 default:
4345 break;
4346 case Decl::ImplicitParam:
4347 case Decl::ObjCAtDefsField:
4348 case Decl::ObjCCategory:
4349 case Decl::ObjCCategoryImpl:
4350 case Decl::ObjCClass:
4351 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004352 case Decl::ObjCForwardProtocol:
4353 case Decl::ObjCImplementation:
4354 case Decl::ObjCInterface:
4355 case Decl::ObjCIvar:
4356 case Decl::ObjCMethod:
4357 case Decl::ObjCProperty:
4358 case Decl::ObjCPropertyImpl:
4359 case Decl::ObjCProtocol:
4360 return CXLanguage_ObjC;
4361 case Decl::CXXConstructor:
4362 case Decl::CXXConversion:
4363 case Decl::CXXDestructor:
4364 case Decl::CXXMethod:
4365 case Decl::CXXRecord:
4366 case Decl::ClassTemplate:
4367 case Decl::ClassTemplatePartialSpecialization:
4368 case Decl::ClassTemplateSpecialization:
4369 case Decl::Friend:
4370 case Decl::FriendTemplate:
4371 case Decl::FunctionTemplate:
4372 case Decl::LinkageSpec:
4373 case Decl::Namespace:
4374 case Decl::NamespaceAlias:
4375 case Decl::NonTypeTemplateParm:
4376 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004377 case Decl::TemplateTemplateParm:
4378 case Decl::TemplateTypeParm:
4379 case Decl::UnresolvedUsingTypename:
4380 case Decl::UnresolvedUsingValue:
4381 case Decl::Using:
4382 case Decl::UsingDirective:
4383 case Decl::UsingShadow:
4384 return CXLanguage_CPlusPlus;
4385 }
4386
4387 return CXLanguage_C;
4388}
4389
4390extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004391
4392enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4393 if (clang_isDeclaration(cursor.kind))
4394 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4395 if (D->hasAttr<UnavailableAttr>() ||
4396 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4397 return CXAvailability_Available;
4398
4399 if (D->hasAttr<DeprecatedAttr>())
4400 return CXAvailability_Deprecated;
4401 }
4402
4403 return CXAvailability_Available;
4404}
4405
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004406CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4407 if (clang_isDeclaration(cursor.kind))
4408 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4409
4410 return CXLanguage_Invalid;
4411}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004412
4413CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4414 if (clang_isDeclaration(cursor.kind)) {
4415 if (Decl *D = getCursorDecl(cursor)) {
4416 DeclContext *DC = D->getDeclContext();
4417 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4418 }
4419 }
4420
4421 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4422 if (Decl *D = getCursorDecl(cursor))
4423 return MakeCXCursor(D, getCursorASTUnit(cursor));
4424 }
4425
4426 return clang_getNullCursor();
4427}
4428
4429CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4430 if (clang_isDeclaration(cursor.kind)) {
4431 if (Decl *D = getCursorDecl(cursor)) {
4432 DeclContext *DC = D->getLexicalDeclContext();
4433 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4434 }
4435 }
4436
4437 // FIXME: Note that we can't easily compute the lexical context of a
4438 // statement or expression, so we return nothing.
4439 return clang_getNullCursor();
4440}
4441
Douglas Gregor9f592342010-10-01 20:25:15 +00004442static void CollectOverriddenMethods(DeclContext *Ctx,
4443 ObjCMethodDecl *Method,
4444 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4445 if (!Ctx)
4446 return;
4447
4448 // If we have a class or category implementation, jump straight to the
4449 // interface.
4450 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4451 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4452
4453 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4454 if (!Container)
4455 return;
4456
4457 // Check whether we have a matching method at this level.
4458 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4459 Method->isInstanceMethod()))
4460 if (Method != Overridden) {
4461 // We found an override at this level; there is no need to look
4462 // into other protocols or categories.
4463 Methods.push_back(Overridden);
4464 return;
4465 }
4466
4467 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4468 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4469 PEnd = Protocol->protocol_end();
4470 P != PEnd; ++P)
4471 CollectOverriddenMethods(*P, Method, Methods);
4472 }
4473
4474 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4475 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4476 PEnd = Category->protocol_end();
4477 P != PEnd; ++P)
4478 CollectOverriddenMethods(*P, Method, Methods);
4479 }
4480
4481 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4482 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4483 PEnd = Interface->protocol_end();
4484 P != PEnd; ++P)
4485 CollectOverriddenMethods(*P, Method, Methods);
4486
4487 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4488 Category; Category = Category->getNextClassCategory())
4489 CollectOverriddenMethods(Category, Method, Methods);
4490
4491 // We only look into the superclass if we haven't found anything yet.
4492 if (Methods.empty())
4493 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4494 return CollectOverriddenMethods(Super, Method, Methods);
4495 }
4496}
4497
4498void clang_getOverriddenCursors(CXCursor cursor,
4499 CXCursor **overridden,
4500 unsigned *num_overridden) {
4501 if (overridden)
4502 *overridden = 0;
4503 if (num_overridden)
4504 *num_overridden = 0;
4505 if (!overridden || !num_overridden)
4506 return;
4507
4508 if (!clang_isDeclaration(cursor.kind))
4509 return;
4510
4511 Decl *D = getCursorDecl(cursor);
4512 if (!D)
4513 return;
4514
4515 // Handle C++ member functions.
4516 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4517 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4518 *num_overridden = CXXMethod->size_overridden_methods();
4519 if (!*num_overridden)
4520 return;
4521
4522 *overridden = new CXCursor [*num_overridden];
4523 unsigned I = 0;
4524 for (CXXMethodDecl::method_iterator
4525 M = CXXMethod->begin_overridden_methods(),
4526 MEnd = CXXMethod->end_overridden_methods();
4527 M != MEnd; (void)++M, ++I)
4528 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4529 return;
4530 }
4531
4532 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4533 if (!Method)
4534 return;
4535
4536 // Handle Objective-C methods.
4537 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4538 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4539
4540 if (Methods.empty())
4541 return;
4542
4543 *num_overridden = Methods.size();
4544 *overridden = new CXCursor [Methods.size()];
4545 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4546 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4547}
4548
4549void clang_disposeOverriddenCursors(CXCursor *overridden) {
4550 delete [] overridden;
4551}
4552
Douglas Gregorecdcb882010-10-20 22:00:55 +00004553CXFile clang_getIncludedFile(CXCursor cursor) {
4554 if (cursor.kind != CXCursor_InclusionDirective)
4555 return 0;
4556
4557 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4558 return (void *)ID->getFile();
4559}
4560
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004561} // end: extern "C"
4562
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004563
4564//===----------------------------------------------------------------------===//
4565// C++ AST instrospection.
4566//===----------------------------------------------------------------------===//
4567
4568extern "C" {
4569unsigned clang_CXXMethod_isStatic(CXCursor C) {
4570 if (!clang_isDeclaration(C.kind))
4571 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004572
4573 CXXMethodDecl *Method = 0;
4574 Decl *D = cxcursor::getCursorDecl(C);
4575 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4576 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4577 else
4578 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4579 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004580}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004581
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004582} // end: extern "C"
4583
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004584//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004585// Attribute introspection.
4586//===----------------------------------------------------------------------===//
4587
4588extern "C" {
4589CXType clang_getIBOutletCollectionType(CXCursor C) {
4590 if (C.kind != CXCursor_IBOutletCollectionAttr)
4591 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4592
4593 IBOutletCollectionAttr *A =
4594 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4595
4596 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4597}
4598} // end: extern "C"
4599
4600//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004601// CXString Operations.
4602//===----------------------------------------------------------------------===//
4603
4604extern "C" {
4605const char *clang_getCString(CXString string) {
4606 return string.Spelling;
4607}
4608
4609void clang_disposeString(CXString string) {
4610 if (string.MustFreeString && string.Spelling)
4611 free((void*)string.Spelling);
4612}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004613
Ted Kremenekfb480492010-01-13 21:46:36 +00004614} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004615
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004616namespace clang { namespace cxstring {
4617CXString createCXString(const char *String, bool DupString){
4618 CXString Str;
4619 if (DupString) {
4620 Str.Spelling = strdup(String);
4621 Str.MustFreeString = 1;
4622 } else {
4623 Str.Spelling = String;
4624 Str.MustFreeString = 0;
4625 }
4626 return Str;
4627}
4628
4629CXString createCXString(llvm::StringRef String, bool DupString) {
4630 CXString Result;
4631 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4632 char *Spelling = (char *)malloc(String.size() + 1);
4633 memmove(Spelling, String.data(), String.size());
4634 Spelling[String.size()] = 0;
4635 Result.Spelling = Spelling;
4636 Result.MustFreeString = 1;
4637 } else {
4638 Result.Spelling = String.data();
4639 Result.MustFreeString = 0;
4640 }
4641 return Result;
4642}
4643}}
4644
Ted Kremenek04bb7162010-01-22 22:44:15 +00004645//===----------------------------------------------------------------------===//
4646// Misc. utility functions.
4647//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004648
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004649/// Default to using an 8 MB stack size on "safety" threads.
4650static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004651
4652namespace clang {
4653
4654bool RunSafely(llvm::CrashRecoveryContext &CRC,
4655 void (*Fn)(void*), void *UserData) {
4656 if (unsigned Size = GetSafetyThreadStackSize())
4657 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4658 return CRC.RunSafely(Fn, UserData);
4659}
4660
4661unsigned GetSafetyThreadStackSize() {
4662 return SafetyStackThreadSize;
4663}
4664
4665void SetSafetyThreadStackSize(unsigned Value) {
4666 SafetyStackThreadSize = Value;
4667}
4668
4669}
4670
Ted Kremenek04bb7162010-01-22 22:44:15 +00004671extern "C" {
4672
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004673CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004674 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004675}
4676
4677} // end: extern "C"