blob: f4cae89f8fc92482a800b58f9e724eb1be7a8ce4 [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.
107 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000108 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000109 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000110 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111 EndLoc = EndLoc.getFileLocWithOffset(Length);
112 }
113
114 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
115 R.getBegin().getRawEncoding(),
116 EndLoc.getRawEncoding() };
117 return Result;
118}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000119
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000120//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000121// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000122//===----------------------------------------------------------------------===//
123
Steve Naroff89922f82009-08-31 00:59:03 +0000124namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000125
Douglas Gregorb1373d02010-01-20 20:59:29 +0000126// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000127class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000128 public TypeLocVisitor<CursorVisitor, bool>,
129 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000130{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000132 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000135 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000136
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137 /// \brief The declaration that serves at the parent of any statement or
138 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000139 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000140
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000142 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000143
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000144 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000145 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000146
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000147 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
148 // to the visitor. Declarations with a PCH level greater than this value will
149 // be suppressed.
150 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151
152 /// \brief When valid, a source range to which the cursor should restrict
153 /// its search.
154 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000155
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000156 // FIXME: Eventually remove. This part of a hack to support proper
157 // iteration over all Decls contained lexically within an ObjC container.
158 DeclContext::decl_iterator *DI_current;
159 DeclContext::decl_iterator DE_current;
160
Douglas Gregorb1373d02010-01-20 20:59:29 +0000161 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000162 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000163 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
165 /// \brief Determine whether this particular source range comes before, comes
166 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000168 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000169 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
170
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000171 class SetParentRAII {
172 CXCursor &Parent;
173 Decl *&StmtParent;
174 CXCursor OldParent;
175
176 public:
177 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
178 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
179 {
180 Parent = NewParent;
181 if (clang_isDeclaration(Parent.kind))
182 StmtParent = getCursorDecl(Parent);
183 }
184
185 ~SetParentRAII() {
186 Parent = OldParent;
187 if (clang_isDeclaration(Parent.kind))
188 StmtParent = getCursorDecl(Parent);
189 }
190 };
191
Steve Naroff89922f82009-08-31 00:59:03 +0000192public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
194 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000196 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000197 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
198 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000199 {
200 Parent.kind = CXCursor_NoDeclFound;
201 Parent.data[0] = 0;
202 Parent.data[1] = 0;
203 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000204 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000205 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000206
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000208
209 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
210 getPreprocessedEntities();
211
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000213
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000214 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000215 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000216 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000217 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000218 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000220 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
221 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000222 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000223 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000224 bool VisitClassTemplatePartialSpecializationDecl(
225 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000226 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000227 bool VisitEnumConstantDecl(EnumConstantDecl *D);
228 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
229 bool VisitFunctionDecl(FunctionDecl *ND);
230 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000231 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000232 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000233 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000234 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000235 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000236 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
237 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
238 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
239 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000240 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000241 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
242 bool VisitObjCImplDecl(ObjCImplDecl *D);
243 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
244 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000245 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
246 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
247 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000248 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000249 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000250 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000251 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000252 bool VisitUsingDecl(UsingDecl *D);
253 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
254 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000255
Douglas Gregor01829d32010-08-31 14:41:23 +0000256 // Name visitor
257 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000258 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000259
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000260 // Template visitors
261 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000262 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000263 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
264
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000265 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000266 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000267 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000268 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000269 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
270 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000271 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000272 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000273 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000274 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
275 bool VisitPointerTypeLoc(PointerTypeLoc TL);
276 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
277 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
278 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
279 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000280 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000281 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000282 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000283 // FIXME: Implement visitors here when the unimplemented TypeLocs get
284 // implemented
285 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
286 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000287
Douglas Gregora59e3902010-01-21 23:27:09 +0000288 // Statement visitors
289 bool VisitStmt(Stmt *S);
290 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000291 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000292 bool VisitIfStmt(IfStmt *S);
293 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000294 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000295 bool VisitWhileStmt(WhileStmt *S);
296 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000297
Douglas Gregor336fd812010-01-23 00:40:08 +0000298 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000299 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000300 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000301 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000302 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000303 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000304 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000305 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000306 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000307 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000308 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000309 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000310 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
311 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000312 bool VisitInitListExpr(InitListExpr *E);
313 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000314 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000315 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000316 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000317 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
318 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000319 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000320 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000321 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000322 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000323 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000324 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000325 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000326 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000327};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000328
Ted Kremenekab188932010-01-05 19:32:54 +0000329} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000330
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000331static SourceRange getRawCursorExtent(CXCursor C);
332
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000333RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000334 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
335}
336
Douglas Gregorb1373d02010-01-20 20:59:29 +0000337/// \brief Visit the given cursor and, if requested by the visitor,
338/// its children.
339///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000340/// \param Cursor the cursor to visit.
341///
342/// \param CheckRegionOfInterest if true, then the caller already checked that
343/// this cursor is within the region of interest.
344///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000345/// \returns true if the visitation should be aborted, false if it
346/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000347bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000348 if (clang_isInvalid(Cursor.kind))
349 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000350
Douglas Gregorb1373d02010-01-20 20:59:29 +0000351 if (clang_isDeclaration(Cursor.kind)) {
352 Decl *D = getCursorDecl(Cursor);
353 assert(D && "Invalid declaration cursor");
354 if (D->getPCHLevel() > MaxPCHLevel)
355 return false;
356
357 if (D->isImplicit())
358 return false;
359 }
360
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361 // If we have a range of interest, and this cursor doesn't intersect with it,
362 // we're done.
363 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000364 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000365 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366 return false;
367 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000368
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369 switch (Visitor(Cursor, Parent, ClientData)) {
370 case CXChildVisit_Break:
371 return true;
372
373 case CXChildVisit_Continue:
374 return false;
375
376 case CXChildVisit_Recurse:
377 return VisitChildren(Cursor);
378 }
379
Douglas Gregorfd643772010-01-25 16:45:46 +0000380 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381}
382
Douglas Gregor788f5a12010-03-20 00:41:21 +0000383std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
384CursorVisitor::getPreprocessedEntities() {
385 PreprocessingRecord &PPRec
386 = *TU->getPreprocessor().getPreprocessingRecord();
387
388 bool OnlyLocalDecls
389 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
390
391 // There is no region of interest; we have to walk everything.
392 if (RegionOfInterest.isInvalid())
393 return std::make_pair(PPRec.begin(OnlyLocalDecls),
394 PPRec.end(OnlyLocalDecls));
395
396 // Find the file in which the region of interest lands.
397 SourceManager &SM = TU->getSourceManager();
398 std::pair<FileID, unsigned> Begin
399 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
400 std::pair<FileID, unsigned> End
401 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
402
403 // The region of interest spans files; we have to walk everything.
404 if (Begin.first != End.first)
405 return std::make_pair(PPRec.begin(OnlyLocalDecls),
406 PPRec.end(OnlyLocalDecls));
407
408 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
409 = TU->getPreprocessedEntitiesByFile();
410 if (ByFileMap.empty()) {
411 // Build the mapping from files to sets of preprocessed entities.
412 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
413 EEnd = PPRec.end(OnlyLocalDecls);
414 E != EEnd; ++E) {
415 std::pair<FileID, unsigned> P
416 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
417 ByFileMap[P.first].push_back(*E);
418 }
419 }
420
421 return std::make_pair(ByFileMap[Begin.first].begin(),
422 ByFileMap[Begin.first].end());
423}
424
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425/// \brief Visit the children of the given cursor.
426///
427/// \returns true if the visitation should be aborted, false if it
428/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000429bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000430 if (clang_isReference(Cursor.kind)) {
431 // By definition, references have no children.
432 return false;
433 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000434
435 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000437 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000438
Douglas Gregorb1373d02010-01-20 20:59:29 +0000439 if (clang_isDeclaration(Cursor.kind)) {
440 Decl *D = getCursorDecl(Cursor);
441 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000442 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000443 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444
Douglas Gregora59e3902010-01-21 23:27:09 +0000445 if (clang_isStatement(Cursor.kind))
446 return Visit(getCursorStmt(Cursor));
447 if (clang_isExpression(Cursor.kind))
448 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000449
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000451 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000452 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
453 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000454 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
455 TLEnd = CXXUnit->top_level_end();
456 TL != TLEnd; ++TL) {
457 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000458 return true;
459 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000460 } else if (VisitDeclContext(
461 CXXUnit->getASTContext().getTranslationUnitDecl()))
462 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000463
Douglas Gregor0396f462010-03-19 05:22:59 +0000464 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000465 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000466 // FIXME: Once we have the ability to deserialize a preprocessing record,
467 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000468 PreprocessingRecord::iterator E, EEnd;
469 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000470 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
471 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
472 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000473
Douglas Gregor0396f462010-03-19 05:22:59 +0000474 continue;
475 }
476
477 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
478 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
479 return true;
480
481 continue;
482 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000483
484 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
485 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
486 return true;
487
488 continue;
489 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000490 }
491 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000492 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000494
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496 return false;
497}
498
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000499bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000500 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
501 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000502
Ted Kremenek664cffd2010-07-22 11:30:19 +0000503 if (Stmt *Body = B->getBody())
504 return Visit(MakeCXCursor(Body, StmtParent, TU));
505
506 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000507}
508
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000509llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
510 if (RegionOfInterest.isValid()) {
511 SourceRange Range = getRawCursorExtent(Cursor);
512 if (Range.isInvalid())
513 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000514
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000515 switch (CompareRegionOfInterest(Range)) {
516 case RangeBefore:
517 // This declaration comes before the region of interest; skip it.
518 return llvm::Optional<bool>();
519
520 case RangeAfter:
521 // This declaration comes after the region of interest; we're done.
522 return false;
523
524 case RangeOverlap:
525 // This declaration overlaps the region of interest; visit it.
526 break;
527 }
528 }
529 return true;
530}
531
532bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
533 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
534
535 // FIXME: Eventually remove. This part of a hack to support proper
536 // iteration over all Decls contained lexically within an ObjC container.
537 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
538 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
539
540 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000541 Decl *D = *I;
542 if (D->getLexicalDeclContext() != DC)
543 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000544 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000545 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
546 if (!V.hasValue())
547 continue;
548 if (!V.getValue())
549 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000550 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000551 return true;
552 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000554}
555
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000556bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
557 llvm_unreachable("Translation units are visited directly by Visit()");
558 return false;
559}
560
561bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
562 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
563 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000564
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000565 return false;
566}
567
568bool CursorVisitor::VisitTagDecl(TagDecl *D) {
569 return VisitDeclContext(D);
570}
571
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000572bool CursorVisitor::VisitClassTemplateSpecializationDecl(
573 ClassTemplateSpecializationDecl *D) {
574 bool ShouldVisitBody = false;
575 switch (D->getSpecializationKind()) {
576 case TSK_Undeclared:
577 case TSK_ImplicitInstantiation:
578 // Nothing to visit
579 return false;
580
581 case TSK_ExplicitInstantiationDeclaration:
582 case TSK_ExplicitInstantiationDefinition:
583 break;
584
585 case TSK_ExplicitSpecialization:
586 ShouldVisitBody = true;
587 break;
588 }
589
590 // Visit the template arguments used in the specialization.
591 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
592 TypeLoc TL = SpecType->getTypeLoc();
593 if (TemplateSpecializationTypeLoc *TSTLoc
594 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
595 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
596 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
597 return true;
598 }
599 }
600
601 if (ShouldVisitBody && VisitCXXRecordDecl(D))
602 return true;
603
604 return false;
605}
606
Douglas Gregor74dbe642010-08-31 19:31:58 +0000607bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
608 ClassTemplatePartialSpecializationDecl *D) {
609 // FIXME: Visit the "outer" template parameter lists on the TagDecl
610 // before visiting these template parameters.
611 if (VisitTemplateParameters(D->getTemplateParameters()))
612 return true;
613
614 // Visit the partial specialization arguments.
615 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
616 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
617 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
618 return true;
619
620 return VisitCXXRecordDecl(D);
621}
622
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000623bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000624 // Visit the default argument.
625 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
626 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
627 if (Visit(DefArg->getTypeLoc()))
628 return true;
629
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000630 return false;
631}
632
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
634 if (Expr *Init = D->getInitExpr())
635 return Visit(MakeCXCursor(Init, StmtParent, TU));
636 return false;
637}
638
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000639bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
640 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
641 if (Visit(TSInfo->getTypeLoc()))
642 return true;
643
644 return false;
645}
646
Douglas Gregora67e03f2010-09-09 21:42:20 +0000647/// \brief Compare two base or member initializers based on their source order.
648static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
649 CXXBaseOrMemberInitializer const * const *X
650 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
651 CXXBaseOrMemberInitializer const * const *Y
652 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
653
654 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
655 return -1;
656 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
657 return 1;
658 else
659 return 0;
660}
661
Douglas Gregorb1373d02010-01-20 20:59:29 +0000662bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000663 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
664 // Visit the function declaration's syntactic components in the order
665 // written. This requires a bit of work.
666 TypeLoc TL = TSInfo->getTypeLoc();
667 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
668
669 // If we have a function declared directly (without the use of a typedef),
670 // visit just the return type. Otherwise, just visit the function's type
671 // now.
672 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
673 (!FTL && Visit(TL)))
674 return true;
675
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000676 // Visit the nested-name-specifier, if present.
677 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
678 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
679 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000680
681 // Visit the declaration name.
682 if (VisitDeclarationNameInfo(ND->getNameInfo()))
683 return true;
684
685 // FIXME: Visit explicitly-specified template arguments!
686
687 // Visit the function parameters, if we have a function type.
688 if (FTL && VisitFunctionTypeLoc(*FTL, true))
689 return true;
690
691 // FIXME: Attributes?
692 }
693
Douglas Gregora67e03f2010-09-09 21:42:20 +0000694 if (ND->isThisDeclarationADefinition()) {
695 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
696 // Find the initializers that were written in the source.
697 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
698 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
699 IEnd = Constructor->init_end();
700 I != IEnd; ++I) {
701 if (!(*I)->isWritten())
702 continue;
703
704 WrittenInits.push_back(*I);
705 }
706
707 // Sort the initializers in source order
708 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
709 &CompareCXXBaseOrMemberInitializers);
710
711 // Visit the initializers in source order
712 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
713 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
714 if (Init->isMemberInitializer()) {
715 if (Visit(MakeCursorMemberRef(Init->getMember(),
716 Init->getMemberLocation(), TU)))
717 return true;
718 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
719 if (Visit(BaseInfo->getTypeLoc()))
720 return true;
721 }
722
723 // Visit the initializer value.
724 if (Expr *Initializer = Init->getInit())
725 if (Visit(MakeCXCursor(Initializer, ND, TU)))
726 return true;
727 }
728 }
729
730 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
731 return true;
732 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000733
Douglas Gregorb1373d02010-01-20 20:59:29 +0000734 return false;
735}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000736
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000737bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
738 if (VisitDeclaratorDecl(D))
739 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000740
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000741 if (Expr *BitWidth = D->getBitWidth())
742 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000743
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000744 return false;
745}
746
747bool CursorVisitor::VisitVarDecl(VarDecl *D) {
748 if (VisitDeclaratorDecl(D))
749 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000750
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000751 if (Expr *Init = D->getInit())
752 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000753
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000754 return false;
755}
756
Douglas Gregor84b51d72010-09-01 20:16:53 +0000757bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
758 if (VisitDeclaratorDecl(D))
759 return true;
760
761 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
762 if (Expr *DefArg = D->getDefaultArgument())
763 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
764
765 return false;
766}
767
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000768bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
769 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
770 // before visiting these template parameters.
771 if (VisitTemplateParameters(D->getTemplateParameters()))
772 return true;
773
774 return VisitFunctionDecl(D->getTemplatedDecl());
775}
776
Douglas Gregor39d6f072010-08-31 19:02:00 +0000777bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
778 // FIXME: Visit the "outer" template parameter lists on the TagDecl
779 // before visiting these template parameters.
780 if (VisitTemplateParameters(D->getTemplateParameters()))
781 return true;
782
783 return VisitCXXRecordDecl(D->getTemplatedDecl());
784}
785
Douglas Gregor84b51d72010-09-01 20:16:53 +0000786bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
787 if (VisitTemplateParameters(D->getTemplateParameters()))
788 return true;
789
790 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
791 VisitTemplateArgumentLoc(D->getDefaultArgument()))
792 return true;
793
794 return false;
795}
796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000798 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
799 if (Visit(TSInfo->getTypeLoc()))
800 return true;
801
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000803 PEnd = ND->param_end();
804 P != PEnd; ++P) {
805 if (Visit(MakeCXCursor(*P, TU)))
806 return true;
807 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000808
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000809 if (ND->isThisDeclarationADefinition() &&
810 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
811 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000812
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000813 return false;
814}
815
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000816namespace {
817 struct ContainerDeclsSort {
818 SourceManager &SM;
819 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
820 bool operator()(Decl *A, Decl *B) {
821 SourceLocation L_A = A->getLocStart();
822 SourceLocation L_B = B->getLocStart();
823 assert(L_A.isValid() && L_B.isValid());
824 return SM.isBeforeInTranslationUnit(L_A, L_B);
825 }
826 };
827}
828
Douglas Gregora59e3902010-01-21 23:27:09 +0000829bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000830 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
831 // an @implementation can lexically contain Decls that are not properly
832 // nested in the AST. When we identify such cases, we need to retrofit
833 // this nesting here.
834 if (!DI_current)
835 return VisitDeclContext(D);
836
837 // Scan the Decls that immediately come after the container
838 // in the current DeclContext. If any fall within the
839 // container's lexical region, stash them into a vector
840 // for later processing.
841 llvm::SmallVector<Decl *, 24> DeclsInContainer;
842 SourceLocation EndLoc = D->getSourceRange().getEnd();
843 SourceManager &SM = TU->getSourceManager();
844 if (EndLoc.isValid()) {
845 DeclContext::decl_iterator next = *DI_current;
846 while (++next != DE_current) {
847 Decl *D_next = *next;
848 if (!D_next)
849 break;
850 SourceLocation L = D_next->getLocStart();
851 if (!L.isValid())
852 break;
853 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
854 *DI_current = next;
855 DeclsInContainer.push_back(D_next);
856 continue;
857 }
858 break;
859 }
860 }
861
862 // The common case.
863 if (DeclsInContainer.empty())
864 return VisitDeclContext(D);
865
866 // Get all the Decls in the DeclContext, and sort them with the
867 // additional ones we've collected. Then visit them.
868 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
869 I!=E; ++I) {
870 Decl *subDecl = *I;
871 if (!subDecl || subDecl->getLexicalDeclContext() != D)
872 continue;
873 DeclsInContainer.push_back(subDecl);
874 }
875
876 // Now sort the Decls so that they appear in lexical order.
877 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
878 ContainerDeclsSort(SM));
879
880 // Now visit the decls.
881 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
882 E = DeclsInContainer.end(); I != E; ++I) {
883 CXCursor Cursor = MakeCXCursor(*I, TU);
884 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
885 if (!V.hasValue())
886 continue;
887 if (!V.getValue())
888 return false;
889 if (Visit(Cursor, true))
890 return true;
891 }
892 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000893}
894
Douglas Gregorb1373d02010-01-20 20:59:29 +0000895bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000896 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
897 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000898 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000899
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000900 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
901 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
902 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000903 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000904 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000905
Douglas Gregora59e3902010-01-21 23:27:09 +0000906 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000907}
908
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000909bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
910 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
911 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
912 E = PID->protocol_end(); I != E; ++I, ++PL)
913 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
914 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000915
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000916 return VisitObjCContainerDecl(PID);
917}
918
Ted Kremenek23173d72010-05-18 21:09:07 +0000919bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000920 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000921 return true;
922
Ted Kremenek23173d72010-05-18 21:09:07 +0000923 // FIXME: This implements a workaround with @property declarations also being
924 // installed in the DeclContext for the @interface. Eventually this code
925 // should be removed.
926 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
927 if (!CDecl || !CDecl->IsClassExtension())
928 return false;
929
930 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
931 if (!ID)
932 return false;
933
934 IdentifierInfo *PropertyId = PD->getIdentifier();
935 ObjCPropertyDecl *prevDecl =
936 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
937
938 if (!prevDecl)
939 return false;
940
941 // Visit synthesized methods since they will be skipped when visiting
942 // the @interface.
943 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000944 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000945 if (Visit(MakeCXCursor(MD, TU)))
946 return true;
947
948 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000949 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000950 if (Visit(MakeCXCursor(MD, TU)))
951 return true;
952
953 return false;
954}
955
Douglas Gregorb1373d02010-01-20 20:59:29 +0000956bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000957 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000958 if (D->getSuperClass() &&
959 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000960 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000961 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000962 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000963
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000964 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
965 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
966 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000967 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000968 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000969
Douglas Gregora59e3902010-01-21 23:27:09 +0000970 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000971}
972
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000973bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
974 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000975}
976
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000977bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000978 // 'ID' could be null when dealing with invalid code.
979 if (ObjCInterfaceDecl *ID = D->getClassInterface())
980 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
981 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000982
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000983 return VisitObjCImplDecl(D);
984}
985
986bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
987#if 0
988 // Issue callbacks for super class.
989 // FIXME: No source location information!
990 if (D->getSuperClass() &&
991 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000993 TU)))
994 return true;
995#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000996
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000997 return VisitObjCImplDecl(D);
998}
999
1000bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1001 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1002 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1003 E = D->protocol_end();
1004 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001005 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001006 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001007
1008 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001009}
1010
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001011bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1012 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1013 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001016 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001017}
1018
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001019bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1020 return VisitDeclContext(D);
1021}
1022
Douglas Gregor69319002010-08-31 23:48:11 +00001023bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001024 // Visit nested-name-specifier.
1025 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1026 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1027 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001028
1029 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1030 D->getTargetNameLoc(), TU));
1031}
1032
Douglas Gregor7e242562010-09-01 19:52:22 +00001033bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001034 // Visit nested-name-specifier.
1035 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1036 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1037 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001038
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001039 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1040 return true;
1041
Douglas Gregor7e242562010-09-01 19:52:22 +00001042 return VisitDeclarationNameInfo(D->getNameInfo());
1043}
1044
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001045bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001046 // Visit nested-name-specifier.
1047 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1048 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1049 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001050
1051 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1052 D->getIdentLocation(), TU));
1053}
1054
Douglas Gregor7e242562010-09-01 19:52:22 +00001055bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001056 // Visit nested-name-specifier.
1057 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1058 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1059 return true;
1060
Douglas Gregor7e242562010-09-01 19:52:22 +00001061 return VisitDeclarationNameInfo(D->getNameInfo());
1062}
1063
1064bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1065 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001066 // Visit nested-name-specifier.
1067 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1068 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1069 return true;
1070
Douglas Gregor7e242562010-09-01 19:52:22 +00001071 return false;
1072}
1073
Douglas Gregor01829d32010-08-31 14:41:23 +00001074bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1075 switch (Name.getName().getNameKind()) {
1076 case clang::DeclarationName::Identifier:
1077 case clang::DeclarationName::CXXLiteralOperatorName:
1078 case clang::DeclarationName::CXXOperatorName:
1079 case clang::DeclarationName::CXXUsingDirective:
1080 return false;
1081
1082 case clang::DeclarationName::CXXConstructorName:
1083 case clang::DeclarationName::CXXDestructorName:
1084 case clang::DeclarationName::CXXConversionFunctionName:
1085 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1086 return Visit(TSInfo->getTypeLoc());
1087 return false;
1088
1089 case clang::DeclarationName::ObjCZeroArgSelector:
1090 case clang::DeclarationName::ObjCOneArgSelector:
1091 case clang::DeclarationName::ObjCMultiArgSelector:
1092 // FIXME: Per-identifier location info?
1093 return false;
1094 }
1095
1096 return false;
1097}
1098
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001099bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1100 SourceRange Range) {
1101 // FIXME: This whole routine is a hack to work around the lack of proper
1102 // source information in nested-name-specifiers (PR5791). Since we do have
1103 // a beginning source location, we can visit the first component of the
1104 // nested-name-specifier, if it's a single-token component.
1105 if (!NNS)
1106 return false;
1107
1108 // Get the first component in the nested-name-specifier.
1109 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1110 NNS = Prefix;
1111
1112 switch (NNS->getKind()) {
1113 case NestedNameSpecifier::Namespace:
1114 // FIXME: The token at this source location might actually have been a
1115 // namespace alias, but we don't model that. Lame!
1116 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1117 TU));
1118
1119 case NestedNameSpecifier::TypeSpec: {
1120 // If the type has a form where we know that the beginning of the source
1121 // range matches up with a reference cursor. Visit the appropriate reference
1122 // cursor.
1123 Type *T = NNS->getAsType();
1124 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1125 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1126 if (const TagType *Tag = dyn_cast<TagType>(T))
1127 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1128 if (const TemplateSpecializationType *TST
1129 = dyn_cast<TemplateSpecializationType>(T))
1130 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1131 break;
1132 }
1133
1134 case NestedNameSpecifier::TypeSpecWithTemplate:
1135 case NestedNameSpecifier::Global:
1136 case NestedNameSpecifier::Identifier:
1137 break;
1138 }
1139
1140 return false;
1141}
1142
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001143bool CursorVisitor::VisitTemplateParameters(
1144 const TemplateParameterList *Params) {
1145 if (!Params)
1146 return false;
1147
1148 for (TemplateParameterList::const_iterator P = Params->begin(),
1149 PEnd = Params->end();
1150 P != PEnd; ++P) {
1151 if (Visit(MakeCXCursor(*P, TU)))
1152 return true;
1153 }
1154
1155 return false;
1156}
1157
Douglas Gregor0b36e612010-08-31 20:37:03 +00001158bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1159 switch (Name.getKind()) {
1160 case TemplateName::Template:
1161 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1162
1163 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001164 // Visit the overloaded template set.
1165 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1166 return true;
1167
Douglas Gregor0b36e612010-08-31 20:37:03 +00001168 return false;
1169
1170 case TemplateName::DependentTemplate:
1171 // FIXME: Visit nested-name-specifier.
1172 return false;
1173
1174 case TemplateName::QualifiedTemplate:
1175 // FIXME: Visit nested-name-specifier.
1176 return Visit(MakeCursorTemplateRef(
1177 Name.getAsQualifiedTemplateName()->getDecl(),
1178 Loc, TU));
1179 }
1180
1181 return false;
1182}
1183
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001184bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1185 switch (TAL.getArgument().getKind()) {
1186 case TemplateArgument::Null:
1187 case TemplateArgument::Integral:
1188 return false;
1189
1190 case TemplateArgument::Pack:
1191 // FIXME: Implement when variadic templates come along.
1192 return false;
1193
1194 case TemplateArgument::Type:
1195 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1196 return Visit(TSInfo->getTypeLoc());
1197 return false;
1198
1199 case TemplateArgument::Declaration:
1200 if (Expr *E = TAL.getSourceDeclExpression())
1201 return Visit(MakeCXCursor(E, StmtParent, TU));
1202 return false;
1203
1204 case TemplateArgument::Expression:
1205 if (Expr *E = TAL.getSourceExpression())
1206 return Visit(MakeCXCursor(E, StmtParent, TU));
1207 return false;
1208
1209 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001210 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1211 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001212 }
1213
1214 return false;
1215}
1216
Ted Kremeneka0536d82010-05-07 01:04:29 +00001217bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1218 return VisitDeclContext(D);
1219}
1220
Douglas Gregor01829d32010-08-31 14:41:23 +00001221bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1222 return Visit(TL.getUnqualifiedLoc());
1223}
1224
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001225bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1226 ASTContext &Context = TU->getASTContext();
1227
1228 // Some builtin types (such as Objective-C's "id", "sel", and
1229 // "Class") have associated declarations. Create cursors for those.
1230 QualType VisitType;
1231 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001232 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001233 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001234 case BuiltinType::Char_U:
1235 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001236 case BuiltinType::Char16:
1237 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001238 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001239 case BuiltinType::UInt:
1240 case BuiltinType::ULong:
1241 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001242 case BuiltinType::UInt128:
1243 case BuiltinType::Char_S:
1244 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001245 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001246 case BuiltinType::Short:
1247 case BuiltinType::Int:
1248 case BuiltinType::Long:
1249 case BuiltinType::LongLong:
1250 case BuiltinType::Int128:
1251 case BuiltinType::Float:
1252 case BuiltinType::Double:
1253 case BuiltinType::LongDouble:
1254 case BuiltinType::NullPtr:
1255 case BuiltinType::Overload:
1256 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001257 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001258
1259 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001260 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001261
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001262 case BuiltinType::ObjCId:
1263 VisitType = Context.getObjCIdType();
1264 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001265
1266 case BuiltinType::ObjCClass:
1267 VisitType = Context.getObjCClassType();
1268 break;
1269
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270 case BuiltinType::ObjCSel:
1271 VisitType = Context.getObjCSelType();
1272 break;
1273 }
1274
1275 if (!VisitType.isNull()) {
1276 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001277 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278 TU));
1279 }
1280
1281 return false;
1282}
1283
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001284bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1285 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1286}
1287
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001288bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1289 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1290}
1291
1292bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1293 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1294}
1295
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001296bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001297 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298 // no context information with which we can match up the depth/index in the
1299 // type to the appropriate
1300 return false;
1301}
1302
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001303bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1304 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1305 return true;
1306
John McCallc12c5bb2010-05-15 11:32:37 +00001307 return false;
1308}
1309
1310bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1311 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1312 return true;
1313
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001314 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1315 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1316 TU)))
1317 return true;
1318 }
1319
1320 return false;
1321}
1322
1323bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001324 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001325}
1326
1327bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1328 return Visit(TL.getPointeeLoc());
1329}
1330
1331bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1332 return Visit(TL.getPointeeLoc());
1333}
1334
1335bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1336 return Visit(TL.getPointeeLoc());
1337}
1338
1339bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001340 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341}
1342
1343bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001344 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001345}
1346
Douglas Gregor01829d32010-08-31 14:41:23 +00001347bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1348 bool SkipResultType) {
1349 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001350 return true;
1351
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001352 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001353 if (Decl *D = TL.getArg(I))
1354 if (Visit(MakeCXCursor(D, TU)))
1355 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001356
1357 return false;
1358}
1359
1360bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1361 if (Visit(TL.getElementLoc()))
1362 return true;
1363
1364 if (Expr *Size = TL.getSizeExpr())
1365 return Visit(MakeCXCursor(Size, StmtParent, TU));
1366
1367 return false;
1368}
1369
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001370bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1371 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001372 // Visit the template name.
1373 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1374 TL.getTemplateNameLoc()))
1375 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001376
1377 // Visit the template arguments.
1378 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1379 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1380 return true;
1381
1382 return false;
1383}
1384
Douglas Gregor2332c112010-01-21 20:48:56 +00001385bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1386 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1387}
1388
1389bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1390 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1391 return Visit(TSInfo->getTypeLoc());
1392
1393 return false;
1394}
1395
Douglas Gregora59e3902010-01-21 23:27:09 +00001396bool CursorVisitor::VisitStmt(Stmt *S) {
1397 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1398 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001399 if (Stmt *C = *Child)
1400 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1401 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001402 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001403
Douglas Gregora59e3902010-01-21 23:27:09 +00001404 return false;
1405}
1406
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001407bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1408 // Specially handle CaseStmts because they can be nested, e.g.:
1409 //
1410 // case 1:
1411 // case 2:
1412 //
1413 // In this case the second CaseStmt is the child of the first. Walking
1414 // these recursively can blow out the stack.
1415 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1416 while (true) {
1417 // Set the Parent field to Cursor, then back to its old value once we're
1418 // done.
1419 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1420
1421 if (Stmt *LHS = S->getLHS())
1422 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1423 return true;
1424 if (Stmt *RHS = S->getRHS())
1425 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1426 return true;
1427 if (Stmt *SubStmt = S->getSubStmt()) {
1428 if (!isa<CaseStmt>(SubStmt))
1429 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1430
1431 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1432 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1433 Cursor = MakeCXCursor(CS, StmtParent, TU);
1434 if (RegionOfInterest.isValid()) {
1435 SourceRange Range = CS->getSourceRange();
1436 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1437 return false;
1438 }
1439
1440 switch (Visitor(Cursor, Parent, ClientData)) {
1441 case CXChildVisit_Break: return true;
1442 case CXChildVisit_Continue: return false;
1443 case CXChildVisit_Recurse:
1444 // Perform tail-recursion manually.
1445 S = CS;
1446 continue;
1447 }
1448 }
1449 return false;
1450 }
1451}
1452
Douglas Gregora59e3902010-01-21 23:27:09 +00001453bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001454 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001455 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1456 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001457 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001458 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001459 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001461
Douglas Gregora59e3902010-01-21 23:27:09 +00001462 return false;
1463}
1464
Douglas Gregor36897b02010-09-10 00:22:18 +00001465bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1466 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1467}
1468
Douglas Gregorf5bab412010-01-22 01:00:11 +00001469bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1470 if (VarDecl *Var = S->getConditionVariable()) {
1471 if (Visit(MakeCXCursor(Var, TU)))
1472 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001473 }
1474
Douglas Gregor263b47b2010-01-25 16:12:32 +00001475 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1476 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001477 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1478 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001479 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1480 return true;
1481
1482 return false;
1483}
1484
1485bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1486 if (VarDecl *Var = S->getConditionVariable()) {
1487 if (Visit(MakeCXCursor(Var, TU)))
1488 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001489 }
1490
Douglas Gregor263b47b2010-01-25 16:12:32 +00001491 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1492 return true;
1493 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1494 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001495
Douglas Gregor263b47b2010-01-25 16:12:32 +00001496 return false;
1497}
1498
1499bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1500 if (VarDecl *Var = S->getConditionVariable()) {
1501 if (Visit(MakeCXCursor(Var, TU)))
1502 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001503 }
1504
Douglas Gregor263b47b2010-01-25 16:12:32 +00001505 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1506 return true;
1507 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001508 return true;
1509
Douglas Gregor263b47b2010-01-25 16:12:32 +00001510 return false;
1511}
1512
1513bool CursorVisitor::VisitForStmt(ForStmt *S) {
1514 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1515 return true;
1516 if (VarDecl *Var = S->getConditionVariable()) {
1517 if (Visit(MakeCXCursor(Var, TU)))
1518 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001519 }
1520
Douglas Gregor263b47b2010-01-25 16:12:32 +00001521 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1522 return true;
1523 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1524 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001525 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1526 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001527
Douglas Gregorf5bab412010-01-22 01:00:11 +00001528 return false;
1529}
1530
Douglas Gregor8947a752010-09-02 20:35:02 +00001531bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1532 // Visit nested-name-specifier, if present.
1533 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1534 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1535 return true;
1536
1537 // Visit declaration name.
1538 if (VisitDeclarationNameInfo(E->getNameInfo()))
1539 return true;
1540
1541 // Visit explicitly-specified template arguments.
1542 if (E->hasExplicitTemplateArgs()) {
1543 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1544 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1545 *ArgEnd = Arg + Args.NumTemplateArgs;
1546 Arg != ArgEnd; ++Arg)
1547 if (VisitTemplateArgumentLoc(*Arg))
1548 return true;
1549 }
1550
1551 return false;
1552}
1553
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001554bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1555 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1556 return true;
1557
1558 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1559 return true;
1560
1561 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1562 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1563 return true;
1564
1565 return false;
1566}
1567
Ted Kremenek3064ef92010-08-27 21:34:58 +00001568bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1569 if (D->isDefinition()) {
1570 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1571 E = D->bases_end(); I != E; ++I) {
1572 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1573 return true;
1574 }
1575 }
1576
1577 return VisitTagDecl(D);
1578}
1579
1580
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001581bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1582 return Visit(B->getBlockDecl());
1583}
1584
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001585bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001586 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001587 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1588 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001589
1590 // Visit the components of the offsetof expression.
1591 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1592 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1593 const OffsetOfNode &Node = E->getComponent(I);
1594 switch (Node.getKind()) {
1595 case OffsetOfNode::Array:
1596 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1597 StmtParent, TU)))
1598 return true;
1599 break;
1600
1601 case OffsetOfNode::Field:
1602 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1603 TU)))
1604 return true;
1605 break;
1606
1607 case OffsetOfNode::Identifier:
1608 case OffsetOfNode::Base:
1609 continue;
1610 }
1611 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001612
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001613 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001614}
1615
Douglas Gregor336fd812010-01-23 00:40:08 +00001616bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1617 if (E->isArgumentType()) {
1618 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1619 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001620
Douglas Gregor336fd812010-01-23 00:40:08 +00001621 return false;
1622 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001623
Douglas Gregor336fd812010-01-23 00:40:08 +00001624 return VisitExpr(E);
1625}
1626
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001627bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1628 // Visit the base expression.
1629 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1630 return true;
1631
1632 // Visit the nested-name-specifier
1633 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1634 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1635 return true;
1636
1637 // Visit the declaration name.
1638 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1639 return true;
1640
1641 // Visit the explicitly-specified template arguments, if any.
1642 if (E->hasExplicitTemplateArgs()) {
1643 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1644 *ArgEnd = Arg + E->getNumTemplateArgs();
1645 Arg != ArgEnd;
1646 ++Arg) {
1647 if (VisitTemplateArgumentLoc(*Arg))
1648 return true;
1649 }
1650 }
1651
1652 return false;
1653}
1654
Douglas Gregor336fd812010-01-23 00:40:08 +00001655bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1656 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1657 if (Visit(TSInfo->getTypeLoc()))
1658 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001659
Douglas Gregor336fd812010-01-23 00:40:08 +00001660 return VisitCastExpr(E);
1661}
1662
1663bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1664 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1665 if (Visit(TSInfo->getTypeLoc()))
1666 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001667
Douglas Gregor336fd812010-01-23 00:40:08 +00001668 return VisitExpr(E);
1669}
1670
Douglas Gregor36897b02010-09-10 00:22:18 +00001671bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1672 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1673}
1674
Douglas Gregor648220e2010-08-10 15:02:34 +00001675bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1676 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1677 Visit(E->getArgTInfo2()->getTypeLoc());
1678}
1679
1680bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1681 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1682 return true;
1683
1684 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1685}
1686
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001687bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1688 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001689 if (InitListExpr *Syntactic = E->getSyntacticForm())
1690 return VisitExpr(Syntactic);
1691
1692 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001693}
1694
1695bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1696 // Visit the designators.
1697 typedef DesignatedInitExpr::Designator Designator;
1698 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1699 DEnd = E->designators_end();
1700 D != DEnd; ++D) {
1701 if (D->isFieldDesignator()) {
1702 if (FieldDecl *Field = D->getField())
1703 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1704 return true;
1705
1706 continue;
1707 }
1708
1709 if (D->isArrayDesignator()) {
1710 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1711 return true;
1712
1713 continue;
1714 }
1715
1716 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1717 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1718 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1719 return true;
1720 }
1721
1722 // Visit the initializer value itself.
1723 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1724}
1725
Douglas Gregor94802292010-09-02 21:20:16 +00001726bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1727 if (E->isTypeOperand()) {
1728 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1729 return Visit(TSInfo->getTypeLoc());
1730
1731 return false;
1732 }
1733
1734 return VisitExpr(E);
1735}
1736
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001737bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1738 if (E->isTypeOperand()) {
1739 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1740 return Visit(TSInfo->getTypeLoc());
1741
1742 return false;
1743 }
1744
1745 return VisitExpr(E);
1746}
1747
Douglas Gregorab6677e2010-09-08 00:15:04 +00001748bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1749 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1750 return Visit(TSInfo->getTypeLoc());
1751
1752 return VisitExpr(E);
1753}
1754
1755bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1756 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1757 return Visit(TSInfo->getTypeLoc());
1758
1759 return false;
1760}
1761
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001762bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1763 // Visit placement arguments.
1764 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1765 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1766 return true;
1767
1768 // Visit the allocated type.
1769 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1770 if (Visit(TSInfo->getTypeLoc()))
1771 return true;
1772
1773 // Visit the array size, if any.
1774 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1775 return true;
1776
1777 // Visit the initializer or constructor arguments.
1778 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1779 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1780 return true;
1781
1782 return false;
1783}
1784
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001785bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1786 // Visit base expression.
1787 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1788 return true;
1789
1790 // Visit the nested-name-specifier.
1791 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1792 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1793 return true;
1794
1795 // Visit the scope type that looks disturbingly like the nested-name-specifier
1796 // but isn't.
1797 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1798 if (Visit(TSInfo->getTypeLoc()))
1799 return true;
1800
1801 // Visit the name of the type being destroyed.
1802 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1803 if (Visit(TSInfo->getTypeLoc()))
1804 return true;
1805
1806 return false;
1807}
1808
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001809bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1810 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1811}
1812
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001813bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001814 // Visit the nested-name-specifier.
1815 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1816 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1817 return true;
1818
1819 // Visit the declaration name.
1820 if (VisitDeclarationNameInfo(E->getNameInfo()))
1821 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001822
1823 // Visit the overloaded declaration reference.
1824 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1825 return true;
1826
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001827 // Visit the explicitly-specified template arguments.
1828 if (const ExplicitTemplateArgumentList *ArgList
1829 = E->getOptionalExplicitTemplateArgs()) {
1830 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1831 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1832 Arg != ArgEnd; ++Arg) {
1833 if (VisitTemplateArgumentLoc(*Arg))
1834 return true;
1835 }
1836 }
1837
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001838 return false;
1839}
1840
Douglas Gregorbfebed22010-09-03 17:24:10 +00001841bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1842 DependentScopeDeclRefExpr *E) {
1843 // Visit the nested-name-specifier.
1844 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1845 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1846 return true;
1847
1848 // Visit the declaration name.
1849 if (VisitDeclarationNameInfo(E->getNameInfo()))
1850 return true;
1851
1852 // Visit the explicitly-specified template arguments.
1853 if (const ExplicitTemplateArgumentList *ArgList
1854 = E->getOptionalExplicitTemplateArgs()) {
1855 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1856 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1857 Arg != ArgEnd; ++Arg) {
1858 if (VisitTemplateArgumentLoc(*Arg))
1859 return true;
1860 }
1861 }
1862
1863 return false;
1864}
1865
Douglas Gregorab6677e2010-09-08 00:15:04 +00001866bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1867 CXXUnresolvedConstructExpr *E) {
1868 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1869 if (Visit(TSInfo->getTypeLoc()))
1870 return true;
1871
1872 return VisitExpr(E);
1873}
1874
Douglas Gregor25d63622010-09-03 17:35:34 +00001875bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1876 CXXDependentScopeMemberExpr *E) {
1877 // Visit the base expression, if there is one.
1878 if (!E->isImplicitAccess() &&
1879 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1880 return true;
1881
1882 // Visit the nested-name-specifier.
1883 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1884 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1885 return true;
1886
1887 // Visit the declaration name.
1888 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1889 return true;
1890
1891 // Visit the explicitly-specified template arguments.
1892 if (const ExplicitTemplateArgumentList *ArgList
1893 = E->getOptionalExplicitTemplateArgs()) {
1894 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1895 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1896 Arg != ArgEnd; ++Arg) {
1897 if (VisitTemplateArgumentLoc(*Arg))
1898 return true;
1899 }
1900 }
1901
1902 return false;
1903}
1904
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001905bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1906 // Visit the base expression, if there is one.
1907 if (!E->isImplicitAccess() &&
1908 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1909 return true;
1910
1911 return VisitOverloadExpr(E);
1912}
Douglas Gregor25d63622010-09-03 17:35:34 +00001913
Douglas Gregorc2350e52010-03-08 16:40:19 +00001914bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001915 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1916 if (Visit(TSInfo->getTypeLoc()))
1917 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001918
1919 return VisitExpr(E);
1920}
1921
Douglas Gregor81d34662010-04-20 15:39:42 +00001922bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1923 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1924}
1925
1926
Ted Kremenek09dfa372010-02-18 05:46:33 +00001927bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001928 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1929 i != e; ++i)
1930 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001931 return true;
1932
1933 return false;
1934}
1935
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001936static llvm::sys::Mutex EnableMultithreadingMutex;
1937static bool EnabledMultithreading;
1938
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001939extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001940CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1941 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00001942 // Disable pretty stack trace functionality, which will otherwise be a very
1943 // poor citizen of the world and set up all sorts of signal handlers.
1944 llvm::DisablePrettyStackTrace = true;
1945
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001946 // We use crash recovery to make some of our APIs more reliable, implicitly
1947 // enable it.
1948 llvm::CrashRecoveryContext::Enable();
1949
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001950 // Enable support for multithreading in LLVM.
1951 {
1952 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
1953 if (!EnabledMultithreading) {
1954 llvm::llvm_start_multithreaded();
1955 EnabledMultithreading = true;
1956 }
1957 }
1958
Douglas Gregora030b7c2010-01-22 20:35:53 +00001959 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001960 if (excludeDeclarationsFromPCH)
1961 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001962 if (displayDiagnostics)
1963 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001964 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001965}
1966
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001967void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001968 if (CIdx)
1969 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001970}
1971
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001972CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001973 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001974 if (!CIdx)
1975 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001976
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001977 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001978
Douglas Gregor28019772010-04-05 23:52:57 +00001979 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001980 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001981 CXXIdx->getOnlyLocalDecls(),
1982 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001983}
1984
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001985unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00001986 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00001987 CXTranslationUnit_CacheCompletionResults |
1988 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001989}
1990
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001991CXTranslationUnit
1992clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1993 const char *source_filename,
1994 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001995 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001996 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001997 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001998 return clang_parseTranslationUnit(CIdx, source_filename,
1999 command_line_args, num_command_line_args,
2000 unsaved_files, num_unsaved_files,
2001 CXTranslationUnit_DetailedPreprocessingRecord);
2002}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002003
2004struct ParseTranslationUnitInfo {
2005 CXIndex CIdx;
2006 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002007 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002008 int num_command_line_args;
2009 struct CXUnsavedFile *unsaved_files;
2010 unsigned num_unsaved_files;
2011 unsigned options;
2012 CXTranslationUnit result;
2013};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002014static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002015 ParseTranslationUnitInfo *PTUI =
2016 static_cast<ParseTranslationUnitInfo*>(UserData);
2017 CXIndex CIdx = PTUI->CIdx;
2018 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002019 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002020 int num_command_line_args = PTUI->num_command_line_args;
2021 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2022 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2023 unsigned options = PTUI->options;
2024 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002025
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002026 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002027 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002028
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002029 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2030
Douglas Gregor44c181a2010-07-23 00:33:23 +00002031 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002032 bool CompleteTranslationUnit
2033 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002034 bool CacheCodeCompetionResults
2035 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002036 bool CXXPrecompilePreamble
2037 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2038 bool CXXChainedPCH
2039 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002040
Douglas Gregor5352ac02010-01-28 00:27:43 +00002041 // Configure the diagnostics.
2042 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002043 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2044 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002045
Douglas Gregor4db64a42010-01-23 00:14:00 +00002046 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2047 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002048 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002049 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002050 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002051 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2052 Buffer));
2053 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002054
Douglas Gregorb10daed2010-10-11 16:52:23 +00002055 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002056
Ted Kremenek139ba862009-10-22 00:03:57 +00002057 // The 'source_filename' argument is optional. If the caller does not
2058 // specify it then it is assumed that the source file is specified
2059 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002060 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002061 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002062
2063 // Since the Clang C library is primarily used by batch tools dealing with
2064 // (often very broken) source code, where spell-checking can have a
2065 // significant negative impact on performance (particularly when
2066 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002067 // Only do this if we haven't found a spell-checking-related argument.
2068 bool FoundSpellCheckingArgument = false;
2069 for (int I = 0; I != num_command_line_args; ++I) {
2070 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2071 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2072 FoundSpellCheckingArgument = true;
2073 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002074 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002075 }
2076 if (!FoundSpellCheckingArgument)
2077 Args.push_back("-fno-spell-checking");
2078
2079 Args.insert(Args.end(), command_line_args,
2080 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002081
Douglas Gregor44c181a2010-07-23 00:33:23 +00002082 // Do we need the detailed preprocessing record?
2083 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002084 Args.push_back("-Xclang");
2085 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002086 }
2087
Douglas Gregorb10daed2010-10-11 16:52:23 +00002088 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002089 llvm::OwningPtr<ASTUnit> Unit(
2090 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2091 Diags,
2092 CXXIdx->getClangResourcesPath(),
2093 CXXIdx->getOnlyLocalDecls(),
2094 RemappedFiles.data(),
2095 RemappedFiles.size(),
2096 /*CaptureDiagnostics=*/true,
2097 PrecompilePreamble,
2098 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002099 CacheCodeCompetionResults,
2100 CXXPrecompilePreamble,
2101 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002102
Douglas Gregorb10daed2010-10-11 16:52:23 +00002103 if (NumErrors != Diags->getNumErrors()) {
2104 // Make sure to check that 'Unit' is non-NULL.
2105 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2106 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2107 DEnd = Unit->stored_diag_end();
2108 D != DEnd; ++D) {
2109 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2110 CXString Msg = clang_formatDiagnostic(&Diag,
2111 clang_defaultDiagnosticDisplayOptions());
2112 fprintf(stderr, "%s\n", clang_getCString(Msg));
2113 clang_disposeString(Msg);
2114 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002115#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002116 // On Windows, force a flush, since there may be multiple copies of
2117 // stderr and stdout in the file system, all with different buffers
2118 // but writing to the same device.
2119 fflush(stderr);
2120#endif
2121 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002122 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002123
Douglas Gregorb10daed2010-10-11 16:52:23 +00002124 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002125}
2126CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2127 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002128 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002129 int num_command_line_args,
2130 struct CXUnsavedFile *unsaved_files,
2131 unsigned num_unsaved_files,
2132 unsigned options) {
2133 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2134 num_command_line_args, unsaved_files, num_unsaved_files,
2135 options, 0 };
2136 llvm::CrashRecoveryContext CRC;
2137
2138 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002139 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2140 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2141 fprintf(stderr, " 'command_line_args' : [");
2142 for (int i = 0; i != num_command_line_args; ++i) {
2143 if (i)
2144 fprintf(stderr, ", ");
2145 fprintf(stderr, "'%s'", command_line_args[i]);
2146 }
2147 fprintf(stderr, "],\n");
2148 fprintf(stderr, " 'unsaved_files' : [");
2149 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2150 if (i)
2151 fprintf(stderr, ", ");
2152 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2153 unsaved_files[i].Length);
2154 }
2155 fprintf(stderr, "],\n");
2156 fprintf(stderr, " 'options' : %d,\n", options);
2157 fprintf(stderr, "}\n");
2158
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002159 return 0;
2160 }
2161
2162 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002163}
2164
Douglas Gregor19998442010-08-13 15:35:05 +00002165unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2166 return CXSaveTranslationUnit_None;
2167}
2168
2169int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2170 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002171 if (!TU)
2172 return 1;
2173
2174 return static_cast<ASTUnit *>(TU)->Save(FileName);
2175}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002176
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002177void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002178 if (CTUnit) {
2179 // If the translation unit has been marked as unsafe to free, just discard
2180 // it.
2181 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2182 return;
2183
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002184 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002185 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002186}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002187
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002188unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2189 return CXReparse_None;
2190}
2191
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002192struct ReparseTranslationUnitInfo {
2193 CXTranslationUnit TU;
2194 unsigned num_unsaved_files;
2195 struct CXUnsavedFile *unsaved_files;
2196 unsigned options;
2197 int result;
2198};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002199
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002200static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002201 ReparseTranslationUnitInfo *RTUI =
2202 static_cast<ReparseTranslationUnitInfo*>(UserData);
2203 CXTranslationUnit TU = RTUI->TU;
2204 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2205 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2206 unsigned options = RTUI->options;
2207 (void) options;
2208 RTUI->result = 1;
2209
Douglas Gregorabc563f2010-07-19 21:46:24 +00002210 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002211 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002212
2213 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2214 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002215
2216 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2217 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2218 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2219 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002220 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002221 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2222 Buffer));
2223 }
2224
Douglas Gregor593b0c12010-09-23 18:47:53 +00002225 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2226 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002227}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002228
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002229int clang_reparseTranslationUnit(CXTranslationUnit TU,
2230 unsigned num_unsaved_files,
2231 struct CXUnsavedFile *unsaved_files,
2232 unsigned options) {
2233 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2234 options, 0 };
2235 llvm::CrashRecoveryContext CRC;
2236
2237 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002238 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002239 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2240 return 1;
2241 }
2242
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002243
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002244 return RTUI.result;
2245}
2246
Douglas Gregordf95a132010-08-09 20:45:32 +00002247
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002248CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002249 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002250 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002251
Steve Naroff77accc12009-09-03 18:19:54 +00002252 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002253 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002254}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002255
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002256CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002257 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002258 return Result;
2259}
2260
Ted Kremenekfb480492010-01-13 21:46:36 +00002261} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002262
Ted Kremenekfb480492010-01-13 21:46:36 +00002263//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002264// CXSourceLocation and CXSourceRange Operations.
2265//===----------------------------------------------------------------------===//
2266
Douglas Gregorb9790342010-01-22 21:44:22 +00002267extern "C" {
2268CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002269 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002270 return Result;
2271}
2272
2273unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002274 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2275 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2276 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002277}
2278
2279CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2280 CXFile file,
2281 unsigned line,
2282 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002283 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002284 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002285
Douglas Gregorb9790342010-01-22 21:44:22 +00002286 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2287 SourceLocation SLoc
2288 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002289 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002290 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002291 if (SLoc.isInvalid()) return clang_getNullLocation();
2292
2293 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2294}
2295
2296CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2297 CXFile file,
2298 unsigned offset) {
2299 if (!tu || !file)
2300 return clang_getNullLocation();
2301
2302 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2303 SourceLocation Start
2304 = CXXUnit->getSourceManager().getLocation(
2305 static_cast<const FileEntry *>(file),
2306 1, 1);
2307 if (Start.isInvalid()) return clang_getNullLocation();
2308
2309 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2310
2311 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002312
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002313 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002314}
2315
Douglas Gregor5352ac02010-01-28 00:27:43 +00002316CXSourceRange clang_getNullRange() {
2317 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2318 return Result;
2319}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002320
Douglas Gregor5352ac02010-01-28 00:27:43 +00002321CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2322 if (begin.ptr_data[0] != end.ptr_data[0] ||
2323 begin.ptr_data[1] != end.ptr_data[1])
2324 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002325
2326 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002327 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002328 return Result;
2329}
2330
Douglas Gregor46766dc2010-01-26 19:19:08 +00002331void clang_getInstantiationLocation(CXSourceLocation location,
2332 CXFile *file,
2333 unsigned *line,
2334 unsigned *column,
2335 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002336 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2337
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002338 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002339 if (file)
2340 *file = 0;
2341 if (line)
2342 *line = 0;
2343 if (column)
2344 *column = 0;
2345 if (offset)
2346 *offset = 0;
2347 return;
2348 }
2349
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002350 const SourceManager &SM =
2351 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002352 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002353
2354 if (file)
2355 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2356 if (line)
2357 *line = SM.getInstantiationLineNumber(InstLoc);
2358 if (column)
2359 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002360 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002361 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002362}
2363
Douglas Gregor1db19de2010-01-19 21:36:55 +00002364CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002365 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002366 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002367 return Result;
2368}
2369
2370CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002371 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002372 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002373 return Result;
2374}
2375
Douglas Gregorb9790342010-01-22 21:44:22 +00002376} // end: extern "C"
2377
Douglas Gregor1db19de2010-01-19 21:36:55 +00002378//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002379// CXFile Operations.
2380//===----------------------------------------------------------------------===//
2381
2382extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002383CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002384 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002385 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002386
Steve Naroff88145032009-10-27 14:35:18 +00002387 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002388 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002389}
2390
2391time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002392 if (!SFile)
2393 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002394
Steve Naroff88145032009-10-27 14:35:18 +00002395 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2396 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002397}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002398
Douglas Gregorb9790342010-01-22 21:44:22 +00002399CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2400 if (!tu)
2401 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002402
Douglas Gregorb9790342010-01-22 21:44:22 +00002403 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002404
Douglas Gregorb9790342010-01-22 21:44:22 +00002405 FileManager &FMgr = CXXUnit->getFileManager();
2406 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2407 return const_cast<FileEntry *>(File);
2408}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002409
Ted Kremenekfb480492010-01-13 21:46:36 +00002410} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002411
Ted Kremenekfb480492010-01-13 21:46:36 +00002412//===----------------------------------------------------------------------===//
2413// CXCursor Operations.
2414//===----------------------------------------------------------------------===//
2415
Ted Kremenekfb480492010-01-13 21:46:36 +00002416static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002417 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2418 return getDeclFromExpr(CE->getSubExpr());
2419
Ted Kremenekfb480492010-01-13 21:46:36 +00002420 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2421 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002422 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2423 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002424 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2425 return ME->getMemberDecl();
2426 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2427 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002428 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2429 return PRE->getProperty();
2430
Ted Kremenekfb480492010-01-13 21:46:36 +00002431 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2432 return getDeclFromExpr(CE->getCallee());
Ted Kremenekfb480492010-01-13 21:46:36 +00002433 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2434 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002435
Douglas Gregordb1314e2010-10-01 21:11:22 +00002436 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2437 return PE->getProtocol();
2438
Ted Kremenekfb480492010-01-13 21:46:36 +00002439 return 0;
2440}
2441
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002442static SourceLocation getLocationFromExpr(Expr *E) {
2443 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2444 return /*FIXME:*/Msg->getLeftLoc();
2445 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2446 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002447 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2448 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002449 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2450 return Member->getMemberLoc();
2451 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2452 return Ivar->getLocation();
2453 return E->getLocStart();
2454}
2455
Ted Kremenekfb480492010-01-13 21:46:36 +00002456extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
2458unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002459 CXCursorVisitor visitor,
2460 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002461 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002462
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002463 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2464 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002465 return CursorVis.VisitChildren(parent);
2466}
2467
Douglas Gregor78205d42010-01-20 21:45:58 +00002468static CXString getDeclSpelling(Decl *D) {
2469 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2470 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002471 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002472
Douglas Gregor78205d42010-01-20 21:45:58 +00002473 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002474 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002475
Douglas Gregor78205d42010-01-20 21:45:58 +00002476 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2477 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2478 // and returns different names. NamedDecl returns the class name and
2479 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002480 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002481
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002482 if (isa<UsingDirectiveDecl>(D))
2483 return createCXString("");
2484
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002485 llvm::SmallString<1024> S;
2486 llvm::raw_svector_ostream os(S);
2487 ND->printName(os);
2488
2489 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002490}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002491
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002492CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002493 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002494 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002495
Steve Narofff334b4e2009-09-02 18:26:48 +00002496 if (clang_isReference(C.kind)) {
2497 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002498 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002499 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002500 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002501 }
2502 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002503 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002504 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002505 }
2506 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002507 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002508 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002509 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002510 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002511 case CXCursor_CXXBaseSpecifier: {
2512 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2513 return createCXString(B->getType().getAsString());
2514 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002515 case CXCursor_TypeRef: {
2516 TypeDecl *Type = getCursorTypeRef(C).first;
2517 assert(Type && "Missing type decl");
2518
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002519 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2520 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002521 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002522 case CXCursor_TemplateRef: {
2523 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002524 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002525
2526 return createCXString(Template->getNameAsString());
2527 }
Douglas Gregor69319002010-08-31 23:48:11 +00002528
2529 case CXCursor_NamespaceRef: {
2530 NamedDecl *NS = getCursorNamespaceRef(C).first;
2531 assert(NS && "Missing namespace decl");
2532
2533 return createCXString(NS->getNameAsString());
2534 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002535
Douglas Gregora67e03f2010-09-09 21:42:20 +00002536 case CXCursor_MemberRef: {
2537 FieldDecl *Field = getCursorMemberRef(C).first;
2538 assert(Field && "Missing member decl");
2539
2540 return createCXString(Field->getNameAsString());
2541 }
2542
Douglas Gregor36897b02010-09-10 00:22:18 +00002543 case CXCursor_LabelRef: {
2544 LabelStmt *Label = getCursorLabelRef(C).first;
2545 assert(Label && "Missing label");
2546
2547 return createCXString(Label->getID()->getName());
2548 }
2549
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002550 case CXCursor_OverloadedDeclRef: {
2551 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2552 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2553 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2554 return createCXString(ND->getNameAsString());
2555 return createCXString("");
2556 }
2557 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2558 return createCXString(E->getName().getAsString());
2559 OverloadedTemplateStorage *Ovl
2560 = Storage.get<OverloadedTemplateStorage*>();
2561 if (Ovl->size() == 0)
2562 return createCXString("");
2563 return createCXString((*Ovl->begin())->getNameAsString());
2564 }
2565
Daniel Dunbaracca7252009-11-30 20:42:49 +00002566 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002567 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002568 }
2569 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002570
2571 if (clang_isExpression(C.kind)) {
2572 Decl *D = getDeclFromExpr(getCursorExpr(C));
2573 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002574 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002575 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002576 }
2577
Douglas Gregor36897b02010-09-10 00:22:18 +00002578 if (clang_isStatement(C.kind)) {
2579 Stmt *S = getCursorStmt(C);
2580 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2581 return createCXString(Label->getID()->getName());
2582
2583 return createCXString("");
2584 }
2585
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002586 if (C.kind == CXCursor_MacroInstantiation)
2587 return createCXString(getCursorMacroInstantiation(C)->getName()
2588 ->getNameStart());
2589
Douglas Gregor572feb22010-03-18 18:04:21 +00002590 if (C.kind == CXCursor_MacroDefinition)
2591 return createCXString(getCursorMacroDefinition(C)->getName()
2592 ->getNameStart());
2593
Douglas Gregorecdcb882010-10-20 22:00:55 +00002594 if (C.kind == CXCursor_InclusionDirective)
2595 return createCXString(getCursorInclusionDirective(C)->getFileName());
2596
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002597 if (clang_isDeclaration(C.kind))
2598 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002599
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002600 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002601}
2602
Douglas Gregor358559d2010-10-02 22:49:11 +00002603CXString clang_getCursorDisplayName(CXCursor C) {
2604 if (!clang_isDeclaration(C.kind))
2605 return clang_getCursorSpelling(C);
2606
2607 Decl *D = getCursorDecl(C);
2608 if (!D)
2609 return createCXString("");
2610
2611 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2612 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2613 D = FunTmpl->getTemplatedDecl();
2614
2615 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2616 llvm::SmallString<64> Str;
2617 llvm::raw_svector_ostream OS(Str);
2618 OS << Function->getNameAsString();
2619 if (Function->getPrimaryTemplate())
2620 OS << "<>";
2621 OS << "(";
2622 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2623 if (I)
2624 OS << ", ";
2625 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2626 }
2627
2628 if (Function->isVariadic()) {
2629 if (Function->getNumParams())
2630 OS << ", ";
2631 OS << "...";
2632 }
2633 OS << ")";
2634 return createCXString(OS.str());
2635 }
2636
2637 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2638 llvm::SmallString<64> Str;
2639 llvm::raw_svector_ostream OS(Str);
2640 OS << ClassTemplate->getNameAsString();
2641 OS << "<";
2642 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2643 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2644 if (I)
2645 OS << ", ";
2646
2647 NamedDecl *Param = Params->getParam(I);
2648 if (Param->getIdentifier()) {
2649 OS << Param->getIdentifier()->getName();
2650 continue;
2651 }
2652
2653 // There is no parameter name, which makes this tricky. Try to come up
2654 // with something useful that isn't too long.
2655 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2656 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2657 else if (NonTypeTemplateParmDecl *NTTP
2658 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2659 OS << NTTP->getType().getAsString(Policy);
2660 else
2661 OS << "template<...> class";
2662 }
2663
2664 OS << ">";
2665 return createCXString(OS.str());
2666 }
2667
2668 if (ClassTemplateSpecializationDecl *ClassSpec
2669 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2670 // If the type was explicitly written, use that.
2671 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2672 return createCXString(TSInfo->getType().getAsString(Policy));
2673
2674 llvm::SmallString<64> Str;
2675 llvm::raw_svector_ostream OS(Str);
2676 OS << ClassSpec->getNameAsString();
2677 OS << TemplateSpecializationType::PrintTemplateArgumentList(
2678 ClassSpec->getTemplateArgs().getFlatArgumentList(),
2679 ClassSpec->getTemplateArgs().flat_size(),
2680 Policy);
2681 return createCXString(OS.str());
2682 }
2683
2684 return clang_getCursorSpelling(C);
2685}
2686
Ted Kremeneke68fff62010-02-17 00:41:32 +00002687CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002688 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002689 case CXCursor_FunctionDecl:
2690 return createCXString("FunctionDecl");
2691 case CXCursor_TypedefDecl:
2692 return createCXString("TypedefDecl");
2693 case CXCursor_EnumDecl:
2694 return createCXString("EnumDecl");
2695 case CXCursor_EnumConstantDecl:
2696 return createCXString("EnumConstantDecl");
2697 case CXCursor_StructDecl:
2698 return createCXString("StructDecl");
2699 case CXCursor_UnionDecl:
2700 return createCXString("UnionDecl");
2701 case CXCursor_ClassDecl:
2702 return createCXString("ClassDecl");
2703 case CXCursor_FieldDecl:
2704 return createCXString("FieldDecl");
2705 case CXCursor_VarDecl:
2706 return createCXString("VarDecl");
2707 case CXCursor_ParmDecl:
2708 return createCXString("ParmDecl");
2709 case CXCursor_ObjCInterfaceDecl:
2710 return createCXString("ObjCInterfaceDecl");
2711 case CXCursor_ObjCCategoryDecl:
2712 return createCXString("ObjCCategoryDecl");
2713 case CXCursor_ObjCProtocolDecl:
2714 return createCXString("ObjCProtocolDecl");
2715 case CXCursor_ObjCPropertyDecl:
2716 return createCXString("ObjCPropertyDecl");
2717 case CXCursor_ObjCIvarDecl:
2718 return createCXString("ObjCIvarDecl");
2719 case CXCursor_ObjCInstanceMethodDecl:
2720 return createCXString("ObjCInstanceMethodDecl");
2721 case CXCursor_ObjCClassMethodDecl:
2722 return createCXString("ObjCClassMethodDecl");
2723 case CXCursor_ObjCImplementationDecl:
2724 return createCXString("ObjCImplementationDecl");
2725 case CXCursor_ObjCCategoryImplDecl:
2726 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002727 case CXCursor_CXXMethod:
2728 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002729 case CXCursor_UnexposedDecl:
2730 return createCXString("UnexposedDecl");
2731 case CXCursor_ObjCSuperClassRef:
2732 return createCXString("ObjCSuperClassRef");
2733 case CXCursor_ObjCProtocolRef:
2734 return createCXString("ObjCProtocolRef");
2735 case CXCursor_ObjCClassRef:
2736 return createCXString("ObjCClassRef");
2737 case CXCursor_TypeRef:
2738 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002739 case CXCursor_TemplateRef:
2740 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002741 case CXCursor_NamespaceRef:
2742 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002743 case CXCursor_MemberRef:
2744 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002745 case CXCursor_LabelRef:
2746 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002747 case CXCursor_OverloadedDeclRef:
2748 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002749 case CXCursor_UnexposedExpr:
2750 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002751 case CXCursor_BlockExpr:
2752 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002753 case CXCursor_DeclRefExpr:
2754 return createCXString("DeclRefExpr");
2755 case CXCursor_MemberRefExpr:
2756 return createCXString("MemberRefExpr");
2757 case CXCursor_CallExpr:
2758 return createCXString("CallExpr");
2759 case CXCursor_ObjCMessageExpr:
2760 return createCXString("ObjCMessageExpr");
2761 case CXCursor_UnexposedStmt:
2762 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002763 case CXCursor_LabelStmt:
2764 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002765 case CXCursor_InvalidFile:
2766 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002767 case CXCursor_InvalidCode:
2768 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002769 case CXCursor_NoDeclFound:
2770 return createCXString("NoDeclFound");
2771 case CXCursor_NotImplemented:
2772 return createCXString("NotImplemented");
2773 case CXCursor_TranslationUnit:
2774 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002775 case CXCursor_UnexposedAttr:
2776 return createCXString("UnexposedAttr");
2777 case CXCursor_IBActionAttr:
2778 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002779 case CXCursor_IBOutletAttr:
2780 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002781 case CXCursor_IBOutletCollectionAttr:
2782 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002783 case CXCursor_PreprocessingDirective:
2784 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002785 case CXCursor_MacroDefinition:
2786 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002787 case CXCursor_MacroInstantiation:
2788 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002789 case CXCursor_InclusionDirective:
2790 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002791 case CXCursor_Namespace:
2792 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002793 case CXCursor_LinkageSpec:
2794 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002795 case CXCursor_CXXBaseSpecifier:
2796 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002797 case CXCursor_Constructor:
2798 return createCXString("CXXConstructor");
2799 case CXCursor_Destructor:
2800 return createCXString("CXXDestructor");
2801 case CXCursor_ConversionFunction:
2802 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002803 case CXCursor_TemplateTypeParameter:
2804 return createCXString("TemplateTypeParameter");
2805 case CXCursor_NonTypeTemplateParameter:
2806 return createCXString("NonTypeTemplateParameter");
2807 case CXCursor_TemplateTemplateParameter:
2808 return createCXString("TemplateTemplateParameter");
2809 case CXCursor_FunctionTemplate:
2810 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002811 case CXCursor_ClassTemplate:
2812 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002813 case CXCursor_ClassTemplatePartialSpecialization:
2814 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002815 case CXCursor_NamespaceAlias:
2816 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002817 case CXCursor_UsingDirective:
2818 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002819 case CXCursor_UsingDeclaration:
2820 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002821 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002822
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002823 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002824 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002825}
Steve Naroff89922f82009-08-31 00:59:03 +00002826
Ted Kremeneke68fff62010-02-17 00:41:32 +00002827enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2828 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002829 CXClientData client_data) {
2830 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2831 *BestCursor = cursor;
2832 return CXChildVisit_Recurse;
2833}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002834
Douglas Gregorb9790342010-01-22 21:44:22 +00002835CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2836 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002837 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002838
Douglas Gregorb9790342010-01-22 21:44:22 +00002839 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002840 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2841
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002842 // Translate the given source location to make it point at the beginning of
2843 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002844 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002845
2846 // Guard against an invalid SourceLocation, or we may assert in one
2847 // of the following calls.
2848 if (SLoc.isInvalid())
2849 return clang_getNullCursor();
2850
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002851 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2852 CXXUnit->getASTContext().getLangOptions());
2853
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002854 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2855 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002856 // FIXME: Would be great to have a "hint" cursor, then walk from that
2857 // hint cursor upward until we find a cursor whose source range encloses
2858 // the region of interest, rather than starting from the translation unit.
2859 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002860 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002861 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002862 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002863 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002864 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002865}
2866
Ted Kremenek73885552009-11-17 19:28:59 +00002867CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002868 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002869}
2870
2871unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002872 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002873}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002874
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002875unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002876 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2877}
2878
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002879unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002880 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2881}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002882
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002883unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002884 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2885}
2886
Douglas Gregor97b98722010-01-19 23:20:36 +00002887unsigned clang_isExpression(enum CXCursorKind K) {
2888 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2889}
2890
2891unsigned clang_isStatement(enum CXCursorKind K) {
2892 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2893}
2894
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002895unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2896 return K == CXCursor_TranslationUnit;
2897}
2898
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002899unsigned clang_isPreprocessing(enum CXCursorKind K) {
2900 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2901}
2902
Ted Kremenekad6eff62010-03-08 21:17:29 +00002903unsigned clang_isUnexposed(enum CXCursorKind K) {
2904 switch (K) {
2905 case CXCursor_UnexposedDecl:
2906 case CXCursor_UnexposedExpr:
2907 case CXCursor_UnexposedStmt:
2908 case CXCursor_UnexposedAttr:
2909 return true;
2910 default:
2911 return false;
2912 }
2913}
2914
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002915CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002916 return C.kind;
2917}
2918
Douglas Gregor98258af2010-01-18 22:46:11 +00002919CXSourceLocation clang_getCursorLocation(CXCursor C) {
2920 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002921 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002922 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002923 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2924 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002925 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002926 }
2927
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002928 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002929 std::pair<ObjCProtocolDecl *, SourceLocation> P
2930 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002931 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002932 }
2933
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002934 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002935 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2936 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002937 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002938 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002939
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002940 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002941 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002942 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002943 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002944
2945 case CXCursor_TemplateRef: {
2946 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2947 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2948 }
2949
Douglas Gregor69319002010-08-31 23:48:11 +00002950 case CXCursor_NamespaceRef: {
2951 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2952 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2953 }
2954
Douglas Gregora67e03f2010-09-09 21:42:20 +00002955 case CXCursor_MemberRef: {
2956 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2957 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2958 }
2959
Ted Kremenek3064ef92010-08-27 21:34:58 +00002960 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00002961 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
2962 if (!BaseSpec)
2963 return clang_getNullLocation();
2964
2965 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
2966 return cxloc::translateSourceLocation(getCursorContext(C),
2967 TSInfo->getTypeLoc().getBeginLoc());
2968
2969 return cxloc::translateSourceLocation(getCursorContext(C),
2970 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00002971 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002972
Douglas Gregor36897b02010-09-10 00:22:18 +00002973 case CXCursor_LabelRef: {
2974 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
2975 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
2976 }
2977
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002978 case CXCursor_OverloadedDeclRef:
2979 return cxloc::translateSourceLocation(getCursorContext(C),
2980 getCursorOverloadedDeclRef(C).second);
2981
Douglas Gregorf46034a2010-01-18 23:41:10 +00002982 default:
2983 // FIXME: Need a way to enumerate all non-reference cases.
2984 llvm_unreachable("Missed a reference kind");
2985 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002986 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002987
2988 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002989 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002990 getLocationFromExpr(getCursorExpr(C)));
2991
Douglas Gregor36897b02010-09-10 00:22:18 +00002992 if (clang_isStatement(C.kind))
2993 return cxloc::translateSourceLocation(getCursorContext(C),
2994 getCursorStmt(C)->getLocStart());
2995
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002996 if (C.kind == CXCursor_PreprocessingDirective) {
2997 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2998 return cxloc::translateSourceLocation(getCursorContext(C), L);
2999 }
Douglas Gregor48072312010-03-18 15:23:44 +00003000
3001 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003002 SourceLocation L
3003 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003004 return cxloc::translateSourceLocation(getCursorContext(C), L);
3005 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003006
3007 if (C.kind == CXCursor_MacroDefinition) {
3008 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3009 return cxloc::translateSourceLocation(getCursorContext(C), L);
3010 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003011
3012 if (C.kind == CXCursor_InclusionDirective) {
3013 SourceLocation L
3014 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3015 return cxloc::translateSourceLocation(getCursorContext(C), L);
3016 }
3017
Ted Kremenek9a700d22010-05-12 06:16:13 +00003018 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003019 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003020
Douglas Gregorf46034a2010-01-18 23:41:10 +00003021 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003022 SourceLocation Loc = D->getLocation();
3023 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3024 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003025 // FIXME: Multiple variables declared in a single declaration
3026 // currently lack the information needed to correctly determine their
3027 // ranges when accounting for the type-specifier. We use context
3028 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3029 // and if so, whether it is the first decl.
3030 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3031 if (!cxcursor::isFirstInDeclGroup(C))
3032 Loc = VD->getLocation();
3033 }
3034
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003035 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003036}
Douglas Gregora7bde202010-01-19 00:34:46 +00003037
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003038} // end extern "C"
3039
3040static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003041 if (clang_isReference(C.kind)) {
3042 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003043 case CXCursor_ObjCSuperClassRef:
3044 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003045
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003046 case CXCursor_ObjCProtocolRef:
3047 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003048
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003049 case CXCursor_ObjCClassRef:
3050 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003051
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003052 case CXCursor_TypeRef:
3053 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003054
3055 case CXCursor_TemplateRef:
3056 return getCursorTemplateRef(C).second;
3057
Douglas Gregor69319002010-08-31 23:48:11 +00003058 case CXCursor_NamespaceRef:
3059 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003060
3061 case CXCursor_MemberRef:
3062 return getCursorMemberRef(C).second;
3063
Ted Kremenek3064ef92010-08-27 21:34:58 +00003064 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003065 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003066
Douglas Gregor36897b02010-09-10 00:22:18 +00003067 case CXCursor_LabelRef:
3068 return getCursorLabelRef(C).second;
3069
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003070 case CXCursor_OverloadedDeclRef:
3071 return getCursorOverloadedDeclRef(C).second;
3072
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003073 default:
3074 // FIXME: Need a way to enumerate all non-reference cases.
3075 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003076 }
3077 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003078
3079 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003080 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003081
3082 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003083 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003084
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003085 if (C.kind == CXCursor_PreprocessingDirective)
3086 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003087
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003088 if (C.kind == CXCursor_MacroInstantiation)
3089 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003090
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003091 if (C.kind == CXCursor_MacroDefinition)
3092 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003093
3094 if (C.kind == CXCursor_InclusionDirective)
3095 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3096
Ted Kremenek007a7c92010-11-01 23:26:51 +00003097 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3098 Decl *D = cxcursor::getCursorDecl(C);
3099 SourceRange R = D->getSourceRange();
3100 // FIXME: Multiple variables declared in a single declaration
3101 // currently lack the information needed to correctly determine their
3102 // ranges when accounting for the type-specifier. We use context
3103 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3104 // and if so, whether it is the first decl.
3105 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3106 if (!cxcursor::isFirstInDeclGroup(C))
3107 R.setBegin(VD->getLocation());
3108 }
3109 return R;
3110 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003111 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003112
3113extern "C" {
3114
3115CXSourceRange clang_getCursorExtent(CXCursor C) {
3116 SourceRange R = getRawCursorExtent(C);
3117 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003118 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003119
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003120 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003121}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003122
3123CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003124 if (clang_isInvalid(C.kind))
3125 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003126
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003127 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003128 if (clang_isDeclaration(C.kind)) {
3129 Decl *D = getCursorDecl(C);
3130 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3131 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3132 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3133 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3134 if (ObjCForwardProtocolDecl *Protocols
3135 = dyn_cast<ObjCForwardProtocolDecl>(D))
3136 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3137
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003138 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003139 }
3140
Douglas Gregor97b98722010-01-19 23:20:36 +00003141 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003142 Expr *E = getCursorExpr(C);
3143 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003144 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003145 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003146
3147 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3148 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3149
Douglas Gregor97b98722010-01-19 23:20:36 +00003150 return clang_getNullCursor();
3151 }
3152
Douglas Gregor36897b02010-09-10 00:22:18 +00003153 if (clang_isStatement(C.kind)) {
3154 Stmt *S = getCursorStmt(C);
3155 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3156 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3157 getCursorASTUnit(C));
3158
3159 return clang_getNullCursor();
3160 }
3161
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003162 if (C.kind == CXCursor_MacroInstantiation) {
3163 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3164 return MakeMacroDefinitionCursor(Def, CXXUnit);
3165 }
3166
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003167 if (!clang_isReference(C.kind))
3168 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003169
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003170 switch (C.kind) {
3171 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003172 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003173
3174 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003175 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003176
3177 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003178 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003179
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003180 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003181 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003182
3183 case CXCursor_TemplateRef:
3184 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3185
Douglas Gregor69319002010-08-31 23:48:11 +00003186 case CXCursor_NamespaceRef:
3187 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3188
Douglas Gregora67e03f2010-09-09 21:42:20 +00003189 case CXCursor_MemberRef:
3190 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3191
Ted Kremenek3064ef92010-08-27 21:34:58 +00003192 case CXCursor_CXXBaseSpecifier: {
3193 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3194 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3195 CXXUnit));
3196 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003197
Douglas Gregor36897b02010-09-10 00:22:18 +00003198 case CXCursor_LabelRef:
3199 // FIXME: We end up faking the "parent" declaration here because we
3200 // don't want to make CXCursor larger.
3201 return MakeCXCursor(getCursorLabelRef(C).first,
3202 CXXUnit->getASTContext().getTranslationUnitDecl(),
3203 CXXUnit);
3204
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003205 case CXCursor_OverloadedDeclRef:
3206 return C;
3207
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003208 default:
3209 // We would prefer to enumerate all non-reference cursor kinds here.
3210 llvm_unreachable("Unhandled reference cursor kind");
3211 break;
3212 }
3213 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003214
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003215 return clang_getNullCursor();
3216}
3217
Douglas Gregorb6998662010-01-19 19:34:47 +00003218CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003219 if (clang_isInvalid(C.kind))
3220 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003221
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003222 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003223
Douglas Gregorb6998662010-01-19 19:34:47 +00003224 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003225 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003226 C = clang_getCursorReferenced(C);
3227 WasReference = true;
3228 }
3229
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003230 if (C.kind == CXCursor_MacroInstantiation)
3231 return clang_getCursorReferenced(C);
3232
Douglas Gregorb6998662010-01-19 19:34:47 +00003233 if (!clang_isDeclaration(C.kind))
3234 return clang_getNullCursor();
3235
3236 Decl *D = getCursorDecl(C);
3237 if (!D)
3238 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003239
Douglas Gregorb6998662010-01-19 19:34:47 +00003240 switch (D->getKind()) {
3241 // Declaration kinds that don't really separate the notions of
3242 // declaration and definition.
3243 case Decl::Namespace:
3244 case Decl::Typedef:
3245 case Decl::TemplateTypeParm:
3246 case Decl::EnumConstant:
3247 case Decl::Field:
3248 case Decl::ObjCIvar:
3249 case Decl::ObjCAtDefsField:
3250 case Decl::ImplicitParam:
3251 case Decl::ParmVar:
3252 case Decl::NonTypeTemplateParm:
3253 case Decl::TemplateTemplateParm:
3254 case Decl::ObjCCategoryImpl:
3255 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003256 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003257 case Decl::LinkageSpec:
3258 case Decl::ObjCPropertyImpl:
3259 case Decl::FileScopeAsm:
3260 case Decl::StaticAssert:
3261 case Decl::Block:
3262 return C;
3263
3264 // Declaration kinds that don't make any sense here, but are
3265 // nonetheless harmless.
3266 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003267 break;
3268
3269 // Declaration kinds for which the definition is not resolvable.
3270 case Decl::UnresolvedUsingTypename:
3271 case Decl::UnresolvedUsingValue:
3272 break;
3273
3274 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003275 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3276 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003277
3278 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003279 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003280
3281 case Decl::Enum:
3282 case Decl::Record:
3283 case Decl::CXXRecord:
3284 case Decl::ClassTemplateSpecialization:
3285 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003286 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003287 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003288 return clang_getNullCursor();
3289
3290 case Decl::Function:
3291 case Decl::CXXMethod:
3292 case Decl::CXXConstructor:
3293 case Decl::CXXDestructor:
3294 case Decl::CXXConversion: {
3295 const FunctionDecl *Def = 0;
3296 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003297 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003298 return clang_getNullCursor();
3299 }
3300
3301 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003302 // Ask the variable if it has a definition.
3303 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3304 return MakeCXCursor(Def, CXXUnit);
3305 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003306 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003307
Douglas Gregorb6998662010-01-19 19:34:47 +00003308 case Decl::FunctionTemplate: {
3309 const FunctionDecl *Def = 0;
3310 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003311 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003312 return clang_getNullCursor();
3313 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003314
Douglas Gregorb6998662010-01-19 19:34:47 +00003315 case Decl::ClassTemplate: {
3316 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003317 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003318 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003319 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003320 return clang_getNullCursor();
3321 }
3322
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003323 case Decl::Using:
3324 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3325 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003326
3327 case Decl::UsingShadow:
3328 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003329 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003330 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003331
3332 case Decl::ObjCMethod: {
3333 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3334 if (Method->isThisDeclarationADefinition())
3335 return C;
3336
3337 // Dig out the method definition in the associated
3338 // @implementation, if we have it.
3339 // FIXME: The ASTs should make finding the definition easier.
3340 if (ObjCInterfaceDecl *Class
3341 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3342 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3343 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3344 Method->isInstanceMethod()))
3345 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003346 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003347
3348 return clang_getNullCursor();
3349 }
3350
3351 case Decl::ObjCCategory:
3352 if (ObjCCategoryImplDecl *Impl
3353 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003354 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003355 return clang_getNullCursor();
3356
3357 case Decl::ObjCProtocol:
3358 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3359 return C;
3360 return clang_getNullCursor();
3361
3362 case Decl::ObjCInterface:
3363 // There are two notions of a "definition" for an Objective-C
3364 // class: the interface and its implementation. When we resolved a
3365 // reference to an Objective-C class, produce the @interface as
3366 // the definition; when we were provided with the interface,
3367 // produce the @implementation as the definition.
3368 if (WasReference) {
3369 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3370 return C;
3371 } else if (ObjCImplementationDecl *Impl
3372 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003373 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003374 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003375
Douglas Gregorb6998662010-01-19 19:34:47 +00003376 case Decl::ObjCProperty:
3377 // FIXME: We don't really know where to find the
3378 // ObjCPropertyImplDecls that implement this property.
3379 return clang_getNullCursor();
3380
3381 case Decl::ObjCCompatibleAlias:
3382 if (ObjCInterfaceDecl *Class
3383 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3384 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003385 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003386
Douglas Gregorb6998662010-01-19 19:34:47 +00003387 return clang_getNullCursor();
3388
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003389 case Decl::ObjCForwardProtocol:
3390 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3391 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003392
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003393 case Decl::ObjCClass:
3394 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3395 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003396
3397 case Decl::Friend:
3398 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003399 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003400 return clang_getNullCursor();
3401
3402 case Decl::FriendTemplate:
3403 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003404 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003405 return clang_getNullCursor();
3406 }
3407
3408 return clang_getNullCursor();
3409}
3410
3411unsigned clang_isCursorDefinition(CXCursor C) {
3412 if (!clang_isDeclaration(C.kind))
3413 return 0;
3414
3415 return clang_getCursorDefinition(C) == C;
3416}
3417
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003418unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003419 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003420 return 0;
3421
3422 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3423 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3424 return E->getNumDecls();
3425
3426 if (OverloadedTemplateStorage *S
3427 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3428 return S->size();
3429
3430 Decl *D = Storage.get<Decl*>();
3431 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3432 return Using->getNumShadowDecls();
3433 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3434 return Classes->size();
3435 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3436 return Protocols->protocol_size();
3437
3438 return 0;
3439}
3440
3441CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003442 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003443 return clang_getNullCursor();
3444
3445 if (index >= clang_getNumOverloadedDecls(cursor))
3446 return clang_getNullCursor();
3447
3448 ASTUnit *Unit = getCursorASTUnit(cursor);
3449 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3450 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3451 return MakeCXCursor(E->decls_begin()[index], Unit);
3452
3453 if (OverloadedTemplateStorage *S
3454 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3455 return MakeCXCursor(S->begin()[index], Unit);
3456
3457 Decl *D = Storage.get<Decl*>();
3458 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3459 // FIXME: This is, unfortunately, linear time.
3460 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3461 std::advance(Pos, index);
3462 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3463 }
3464
3465 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3466 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3467
3468 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3469 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3470
3471 return clang_getNullCursor();
3472}
3473
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003474void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003475 const char **startBuf,
3476 const char **endBuf,
3477 unsigned *startLine,
3478 unsigned *startColumn,
3479 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003480 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003481 assert(getCursorDecl(C) && "CXCursor has null decl");
3482 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003483 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3484 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003485
Steve Naroff4ade6d62009-09-23 17:52:52 +00003486 SourceManager &SM = FD->getASTContext().getSourceManager();
3487 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3488 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3489 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3490 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3491 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3492 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3493}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003494
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003495void clang_enableStackTraces(void) {
3496 llvm::sys::PrintStackTraceOnErrorSignal();
3497}
3498
Ted Kremenekfb480492010-01-13 21:46:36 +00003499} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003500
Ted Kremenekfb480492010-01-13 21:46:36 +00003501//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003502// Token-based Operations.
3503//===----------------------------------------------------------------------===//
3504
3505/* CXToken layout:
3506 * int_data[0]: a CXTokenKind
3507 * int_data[1]: starting token location
3508 * int_data[2]: token length
3509 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003510 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003511 * otherwise unused.
3512 */
3513extern "C" {
3514
3515CXTokenKind clang_getTokenKind(CXToken CXTok) {
3516 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3517}
3518
3519CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3520 switch (clang_getTokenKind(CXTok)) {
3521 case CXToken_Identifier:
3522 case CXToken_Keyword:
3523 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003524 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3525 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003526
3527 case CXToken_Literal: {
3528 // We have stashed the starting pointer in the ptr_data field. Use it.
3529 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003530 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003531 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003532
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003533 case CXToken_Punctuation:
3534 case CXToken_Comment:
3535 break;
3536 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003537
3538 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003539 // deconstructing the source location.
3540 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3541 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003542 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003543
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003544 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3545 std::pair<FileID, unsigned> LocInfo
3546 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003547 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003548 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003549 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3550 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003551 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003552
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003553 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003554}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003555
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003556CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3557 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3558 if (!CXXUnit)
3559 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003560
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003561 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3562 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3563}
3564
3565CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3566 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003567 if (!CXXUnit)
3568 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003569
3570 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003571 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3572}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003573
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003574void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3575 CXToken **Tokens, unsigned *NumTokens) {
3576 if (Tokens)
3577 *Tokens = 0;
3578 if (NumTokens)
3579 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003580
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003581 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3582 if (!CXXUnit || !Tokens || !NumTokens)
3583 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003584
Douglas Gregorbdf60622010-03-05 21:16:25 +00003585 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3586
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003587 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003588 if (R.isInvalid())
3589 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003590
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003591 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3592 std::pair<FileID, unsigned> BeginLocInfo
3593 = SourceMgr.getDecomposedLoc(R.getBegin());
3594 std::pair<FileID, unsigned> EndLocInfo
3595 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003596
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003597 // Cannot tokenize across files.
3598 if (BeginLocInfo.first != EndLocInfo.first)
3599 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003600
3601 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003602 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003603 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003604 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003605 if (Invalid)
3606 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003607
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003608 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3609 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003610 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003611 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003612
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003613 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003614 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003615 llvm::SmallVector<CXToken, 32> CXTokens;
3616 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003617 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003618 do {
3619 // Lex the next token
3620 Lex.LexFromRawLexer(Tok);
3621 if (Tok.is(tok::eof))
3622 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003623
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003624 // Initialize the CXToken.
3625 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003626
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003627 // - Common fields
3628 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3629 CXTok.int_data[2] = Tok.getLength();
3630 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003631
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003632 // - Kind-specific fields
3633 if (Tok.isLiteral()) {
3634 CXTok.int_data[0] = CXToken_Literal;
3635 CXTok.ptr_data = (void *)Tok.getLiteralData();
3636 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003637 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003638 std::pair<FileID, unsigned> LocInfo
3639 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003640 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003641 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003642 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3643 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003644 return;
3645
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003646 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003647 IdentifierInfo *II
3648 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003649
David Chisnall096428b2010-10-13 21:44:48 +00003650 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003651 CXTok.int_data[0] = CXToken_Keyword;
3652 }
3653 else {
3654 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3655 CXToken_Identifier
3656 : CXToken_Keyword;
3657 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003658 CXTok.ptr_data = II;
3659 } else if (Tok.is(tok::comment)) {
3660 CXTok.int_data[0] = CXToken_Comment;
3661 CXTok.ptr_data = 0;
3662 } else {
3663 CXTok.int_data[0] = CXToken_Punctuation;
3664 CXTok.ptr_data = 0;
3665 }
3666 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003667 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003668 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003669
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003670 if (CXTokens.empty())
3671 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003672
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003673 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3674 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3675 *NumTokens = CXTokens.size();
3676}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003677
Ted Kremenek6db61092010-05-05 00:55:15 +00003678void clang_disposeTokens(CXTranslationUnit TU,
3679 CXToken *Tokens, unsigned NumTokens) {
3680 free(Tokens);
3681}
3682
3683} // end: extern "C"
3684
3685//===----------------------------------------------------------------------===//
3686// Token annotation APIs.
3687//===----------------------------------------------------------------------===//
3688
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003689typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003690static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3691 CXCursor parent,
3692 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003693namespace {
3694class AnnotateTokensWorker {
3695 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003696 CXToken *Tokens;
3697 CXCursor *Cursors;
3698 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003699 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003700 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003701 CursorVisitor AnnotateVis;
3702 SourceManager &SrcMgr;
3703
3704 bool MoreTokens() const { return TokIdx < NumTokens; }
3705 unsigned NextToken() const { return TokIdx; }
3706 void AdvanceToken() { ++TokIdx; }
3707 SourceLocation GetTokenLoc(unsigned tokI) {
3708 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3709 }
3710
Ted Kremenek6db61092010-05-05 00:55:15 +00003711public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003712 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003713 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3714 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003715 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003716 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003717 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3718 Decl::MaxPCHLevel, RegionOfInterest),
3719 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003720
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003721 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003722 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003723 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003724};
3725}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003726
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003727void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3728 // Walk the AST within the region of interest, annotating tokens
3729 // along the way.
3730 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003731
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003732 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3733 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003734 if (Pos != Annotated.end() &&
3735 (clang_isInvalid(Cursors[I].kind) ||
3736 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003737 Cursors[I] = Pos->second;
3738 }
3739
3740 // Finish up annotating any tokens left.
3741 if (!MoreTokens())
3742 return;
3743
3744 const CXCursor &C = clang_getNullCursor();
3745 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3746 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3747 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003748 }
3749}
3750
Ted Kremenek6db61092010-05-05 00:55:15 +00003751enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003752AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003753 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003754 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003755 if (cursorRange.isInvalid())
3756 return CXChildVisit_Recurse;
3757
Douglas Gregor4419b672010-10-21 06:10:04 +00003758 if (clang_isPreprocessing(cursor.kind)) {
3759 // For macro instantiations, just note where the beginning of the macro
3760 // instantiation occurs.
3761 if (cursor.kind == CXCursor_MacroInstantiation) {
3762 Annotated[Loc.int_data] = cursor;
3763 return CXChildVisit_Recurse;
3764 }
3765
Douglas Gregor4419b672010-10-21 06:10:04 +00003766 // Items in the preprocessing record are kept separate from items in
3767 // declarations, so we keep a separate token index.
3768 unsigned SavedTokIdx = TokIdx;
3769 TokIdx = PreprocessingTokIdx;
3770
3771 // Skip tokens up until we catch up to the beginning of the preprocessing
3772 // entry.
3773 while (MoreTokens()) {
3774 const unsigned I = NextToken();
3775 SourceLocation TokLoc = GetTokenLoc(I);
3776 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3777 case RangeBefore:
3778 AdvanceToken();
3779 continue;
3780 case RangeAfter:
3781 case RangeOverlap:
3782 break;
3783 }
3784 break;
3785 }
3786
3787 // Look at all of the tokens within this range.
3788 while (MoreTokens()) {
3789 const unsigned I = NextToken();
3790 SourceLocation TokLoc = GetTokenLoc(I);
3791 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3792 case RangeBefore:
3793 assert(0 && "Infeasible");
3794 case RangeAfter:
3795 break;
3796 case RangeOverlap:
3797 Cursors[I] = cursor;
3798 AdvanceToken();
3799 continue;
3800 }
3801 break;
3802 }
3803
3804 // Save the preprocessing token index; restore the non-preprocessing
3805 // token index.
3806 PreprocessingTokIdx = TokIdx;
3807 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003808 return CXChildVisit_Recurse;
3809 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003810
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003811 if (cursorRange.isInvalid())
3812 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003813
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003814 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3815
Ted Kremeneka333c662010-05-12 05:29:33 +00003816 // Adjust the annotated range based specific declarations.
3817 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3818 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003819 Decl *D = cxcursor::getCursorDecl(cursor);
3820 // Don't visit synthesized ObjC methods, since they have no syntatic
3821 // representation in the source.
3822 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3823 if (MD->isSynthesized())
3824 return CXChildVisit_Continue;
3825 }
3826 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003827 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3828 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003829 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00003830 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003831 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003832 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003833 }
3834 }
3835 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00003836
Ted Kremenek3f404602010-08-14 01:14:06 +00003837 // If the location of the cursor occurs within a macro instantiation, record
3838 // the spelling location of the cursor in our annotation map. We can then
3839 // paper over the token labelings during a post-processing step to try and
3840 // get cursor mappings for tokens that are the *arguments* of a macro
3841 // instantiation.
3842 if (L.isMacroID()) {
3843 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3844 // Only invalidate the old annotation if it isn't part of a preprocessing
3845 // directive. Here we assume that the default construction of CXCursor
3846 // results in CXCursor.kind being an initialized value (i.e., 0). If
3847 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00003848
Ted Kremenek3f404602010-08-14 01:14:06 +00003849 CXCursor &oldC = Annotated[rawEncoding];
3850 if (!clang_isPreprocessing(oldC.kind))
3851 oldC = cursor;
3852 }
3853
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003854 const enum CXCursorKind K = clang_getCursorKind(parent);
3855 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003856 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3857 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003858
3859 while (MoreTokens()) {
3860 const unsigned I = NextToken();
3861 SourceLocation TokLoc = GetTokenLoc(I);
3862 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3863 case RangeBefore:
3864 Cursors[I] = updateC;
3865 AdvanceToken();
3866 continue;
3867 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003868 case RangeOverlap:
3869 break;
3870 }
3871 break;
3872 }
3873
3874 // Visit children to get their cursor information.
3875 const unsigned BeforeChildren = NextToken();
3876 VisitChildren(cursor);
3877 const unsigned AfterChildren = NextToken();
3878
3879 // Adjust 'Last' to the last token within the extent of the cursor.
3880 while (MoreTokens()) {
3881 const unsigned I = NextToken();
3882 SourceLocation TokLoc = GetTokenLoc(I);
3883 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3884 case RangeBefore:
3885 assert(0 && "Infeasible");
3886 case RangeAfter:
3887 break;
3888 case RangeOverlap:
3889 Cursors[I] = updateC;
3890 AdvanceToken();
3891 continue;
3892 }
3893 break;
3894 }
3895 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003896
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003897 // Scan the tokens that are at the beginning of the cursor, but are not
3898 // capture by the child cursors.
3899
3900 // For AST elements within macros, rely on a post-annotate pass to
3901 // to correctly annotate the tokens with cursors. Otherwise we can
3902 // get confusing results of having tokens that map to cursors that really
3903 // are expanded by an instantiation.
3904 if (L.isMacroID())
3905 cursor = clang_getNullCursor();
3906
3907 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3908 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3909 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00003910
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003911 Cursors[I] = cursor;
3912 }
3913 // Scan the tokens that are at the end of the cursor, but are not captured
3914 // but the child cursors.
3915 for (unsigned I = AfterChildren; I != Last; ++I)
3916 Cursors[I] = cursor;
3917
3918 TokIdx = Last;
3919 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003920}
3921
Ted Kremenek6db61092010-05-05 00:55:15 +00003922static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3923 CXCursor parent,
3924 CXClientData client_data) {
3925 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3926}
3927
3928extern "C" {
3929
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003930void clang_annotateTokens(CXTranslationUnit TU,
3931 CXToken *Tokens, unsigned NumTokens,
3932 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003933
3934 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003935 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003936
Douglas Gregor4419b672010-10-21 06:10:04 +00003937 // Any token we don't specifically annotate will have a NULL cursor.
3938 CXCursor C = clang_getNullCursor();
3939 for (unsigned I = 0; I != NumTokens; ++I)
3940 Cursors[I] = C;
3941
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003942 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00003943 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003944 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003945
Douglas Gregorbdf60622010-03-05 21:16:25 +00003946 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003947
Douglas Gregor0396f462010-03-19 05:22:59 +00003948 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003949 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003950 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3951 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003952 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3953 clang_getTokenLocation(TU,
3954 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003955
Douglas Gregor0396f462010-03-19 05:22:59 +00003956 // A mapping from the source locations found when re-lexing or traversing the
3957 // region of interest to the corresponding cursors.
3958 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003959
3960 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003961 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003962 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3963 std::pair<FileID, unsigned> BeginLocInfo
3964 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3965 std::pair<FileID, unsigned> EndLocInfo
3966 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003967
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003968 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003969 bool Invalid = false;
3970 if (BeginLocInfo.first == EndLocInfo.first &&
3971 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3972 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003973 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3974 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003975 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003976 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003977 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003978
3979 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003980 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003981 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003982 Token Tok;
3983 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003984
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003985 reprocess:
3986 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3987 // We have found a preprocessing directive. Gobble it up so that we
3988 // don't see it while preprocessing these tokens later, but keep track of
3989 // all of the token locations inside this preprocessing directive so that
3990 // we can annotate them appropriately.
3991 //
3992 // FIXME: Some simple tests here could identify macro definitions and
3993 // #undefs, to provide specific cursor kinds for those.
3994 std::vector<SourceLocation> Locations;
3995 do {
3996 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003997 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003998 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003999
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004000 using namespace cxcursor;
4001 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004002 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4003 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004004 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004005 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4006 Annotated[Locations[I].getRawEncoding()] = Cursor;
4007 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004008
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004009 if (Tok.isAtStartOfLine())
4010 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004011
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004012 continue;
4013 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004014
Douglas Gregor48072312010-03-18 15:23:44 +00004015 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004016 break;
4017 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004018 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004019
Douglas Gregor0396f462010-03-19 05:22:59 +00004020 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004021 // a specific cursor.
4022 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4023 CXXUnit, RegionOfInterest);
4024 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004025}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004026} // end: extern "C"
4027
4028//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004029// Operations for querying linkage of a cursor.
4030//===----------------------------------------------------------------------===//
4031
4032extern "C" {
4033CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004034 if (!clang_isDeclaration(cursor.kind))
4035 return CXLinkage_Invalid;
4036
Ted Kremenek16b42592010-03-03 06:36:57 +00004037 Decl *D = cxcursor::getCursorDecl(cursor);
4038 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4039 switch (ND->getLinkage()) {
4040 case NoLinkage: return CXLinkage_NoLinkage;
4041 case InternalLinkage: return CXLinkage_Internal;
4042 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4043 case ExternalLinkage: return CXLinkage_External;
4044 };
4045
4046 return CXLinkage_Invalid;
4047}
4048} // end: extern "C"
4049
4050//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004051// Operations for querying language of a cursor.
4052//===----------------------------------------------------------------------===//
4053
4054static CXLanguageKind getDeclLanguage(const Decl *D) {
4055 switch (D->getKind()) {
4056 default:
4057 break;
4058 case Decl::ImplicitParam:
4059 case Decl::ObjCAtDefsField:
4060 case Decl::ObjCCategory:
4061 case Decl::ObjCCategoryImpl:
4062 case Decl::ObjCClass:
4063 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004064 case Decl::ObjCForwardProtocol:
4065 case Decl::ObjCImplementation:
4066 case Decl::ObjCInterface:
4067 case Decl::ObjCIvar:
4068 case Decl::ObjCMethod:
4069 case Decl::ObjCProperty:
4070 case Decl::ObjCPropertyImpl:
4071 case Decl::ObjCProtocol:
4072 return CXLanguage_ObjC;
4073 case Decl::CXXConstructor:
4074 case Decl::CXXConversion:
4075 case Decl::CXXDestructor:
4076 case Decl::CXXMethod:
4077 case Decl::CXXRecord:
4078 case Decl::ClassTemplate:
4079 case Decl::ClassTemplatePartialSpecialization:
4080 case Decl::ClassTemplateSpecialization:
4081 case Decl::Friend:
4082 case Decl::FriendTemplate:
4083 case Decl::FunctionTemplate:
4084 case Decl::LinkageSpec:
4085 case Decl::Namespace:
4086 case Decl::NamespaceAlias:
4087 case Decl::NonTypeTemplateParm:
4088 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004089 case Decl::TemplateTemplateParm:
4090 case Decl::TemplateTypeParm:
4091 case Decl::UnresolvedUsingTypename:
4092 case Decl::UnresolvedUsingValue:
4093 case Decl::Using:
4094 case Decl::UsingDirective:
4095 case Decl::UsingShadow:
4096 return CXLanguage_CPlusPlus;
4097 }
4098
4099 return CXLanguage_C;
4100}
4101
4102extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004103
4104enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4105 if (clang_isDeclaration(cursor.kind))
4106 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4107 if (D->hasAttr<UnavailableAttr>() ||
4108 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4109 return CXAvailability_Available;
4110
4111 if (D->hasAttr<DeprecatedAttr>())
4112 return CXAvailability_Deprecated;
4113 }
4114
4115 return CXAvailability_Available;
4116}
4117
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004118CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4119 if (clang_isDeclaration(cursor.kind))
4120 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4121
4122 return CXLanguage_Invalid;
4123}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004124
4125CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4126 if (clang_isDeclaration(cursor.kind)) {
4127 if (Decl *D = getCursorDecl(cursor)) {
4128 DeclContext *DC = D->getDeclContext();
4129 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4130 }
4131 }
4132
4133 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4134 if (Decl *D = getCursorDecl(cursor))
4135 return MakeCXCursor(D, getCursorASTUnit(cursor));
4136 }
4137
4138 return clang_getNullCursor();
4139}
4140
4141CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4142 if (clang_isDeclaration(cursor.kind)) {
4143 if (Decl *D = getCursorDecl(cursor)) {
4144 DeclContext *DC = D->getLexicalDeclContext();
4145 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4146 }
4147 }
4148
4149 // FIXME: Note that we can't easily compute the lexical context of a
4150 // statement or expression, so we return nothing.
4151 return clang_getNullCursor();
4152}
4153
Douglas Gregor9f592342010-10-01 20:25:15 +00004154static void CollectOverriddenMethods(DeclContext *Ctx,
4155 ObjCMethodDecl *Method,
4156 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4157 if (!Ctx)
4158 return;
4159
4160 // If we have a class or category implementation, jump straight to the
4161 // interface.
4162 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4163 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4164
4165 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4166 if (!Container)
4167 return;
4168
4169 // Check whether we have a matching method at this level.
4170 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4171 Method->isInstanceMethod()))
4172 if (Method != Overridden) {
4173 // We found an override at this level; there is no need to look
4174 // into other protocols or categories.
4175 Methods.push_back(Overridden);
4176 return;
4177 }
4178
4179 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4180 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4181 PEnd = Protocol->protocol_end();
4182 P != PEnd; ++P)
4183 CollectOverriddenMethods(*P, Method, Methods);
4184 }
4185
4186 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4187 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4188 PEnd = Category->protocol_end();
4189 P != PEnd; ++P)
4190 CollectOverriddenMethods(*P, Method, Methods);
4191 }
4192
4193 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4194 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4195 PEnd = Interface->protocol_end();
4196 P != PEnd; ++P)
4197 CollectOverriddenMethods(*P, Method, Methods);
4198
4199 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4200 Category; Category = Category->getNextClassCategory())
4201 CollectOverriddenMethods(Category, Method, Methods);
4202
4203 // We only look into the superclass if we haven't found anything yet.
4204 if (Methods.empty())
4205 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4206 return CollectOverriddenMethods(Super, Method, Methods);
4207 }
4208}
4209
4210void clang_getOverriddenCursors(CXCursor cursor,
4211 CXCursor **overridden,
4212 unsigned *num_overridden) {
4213 if (overridden)
4214 *overridden = 0;
4215 if (num_overridden)
4216 *num_overridden = 0;
4217 if (!overridden || !num_overridden)
4218 return;
4219
4220 if (!clang_isDeclaration(cursor.kind))
4221 return;
4222
4223 Decl *D = getCursorDecl(cursor);
4224 if (!D)
4225 return;
4226
4227 // Handle C++ member functions.
4228 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4229 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4230 *num_overridden = CXXMethod->size_overridden_methods();
4231 if (!*num_overridden)
4232 return;
4233
4234 *overridden = new CXCursor [*num_overridden];
4235 unsigned I = 0;
4236 for (CXXMethodDecl::method_iterator
4237 M = CXXMethod->begin_overridden_methods(),
4238 MEnd = CXXMethod->end_overridden_methods();
4239 M != MEnd; (void)++M, ++I)
4240 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4241 return;
4242 }
4243
4244 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4245 if (!Method)
4246 return;
4247
4248 // Handle Objective-C methods.
4249 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4250 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4251
4252 if (Methods.empty())
4253 return;
4254
4255 *num_overridden = Methods.size();
4256 *overridden = new CXCursor [Methods.size()];
4257 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4258 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4259}
4260
4261void clang_disposeOverriddenCursors(CXCursor *overridden) {
4262 delete [] overridden;
4263}
4264
Douglas Gregorecdcb882010-10-20 22:00:55 +00004265CXFile clang_getIncludedFile(CXCursor cursor) {
4266 if (cursor.kind != CXCursor_InclusionDirective)
4267 return 0;
4268
4269 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4270 return (void *)ID->getFile();
4271}
4272
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004273} // end: extern "C"
4274
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004275
4276//===----------------------------------------------------------------------===//
4277// C++ AST instrospection.
4278//===----------------------------------------------------------------------===//
4279
4280extern "C" {
4281unsigned clang_CXXMethod_isStatic(CXCursor C) {
4282 if (!clang_isDeclaration(C.kind))
4283 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004284
4285 CXXMethodDecl *Method = 0;
4286 Decl *D = cxcursor::getCursorDecl(C);
4287 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4288 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4289 else
4290 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4291 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004292}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004293
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004294} // end: extern "C"
4295
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004296//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004297// Attribute introspection.
4298//===----------------------------------------------------------------------===//
4299
4300extern "C" {
4301CXType clang_getIBOutletCollectionType(CXCursor C) {
4302 if (C.kind != CXCursor_IBOutletCollectionAttr)
4303 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4304
4305 IBOutletCollectionAttr *A =
4306 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4307
4308 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4309}
4310} // end: extern "C"
4311
4312//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004313// CXString Operations.
4314//===----------------------------------------------------------------------===//
4315
4316extern "C" {
4317const char *clang_getCString(CXString string) {
4318 return string.Spelling;
4319}
4320
4321void clang_disposeString(CXString string) {
4322 if (string.MustFreeString && string.Spelling)
4323 free((void*)string.Spelling);
4324}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004325
Ted Kremenekfb480492010-01-13 21:46:36 +00004326} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004327
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004328namespace clang { namespace cxstring {
4329CXString createCXString(const char *String, bool DupString){
4330 CXString Str;
4331 if (DupString) {
4332 Str.Spelling = strdup(String);
4333 Str.MustFreeString = 1;
4334 } else {
4335 Str.Spelling = String;
4336 Str.MustFreeString = 0;
4337 }
4338 return Str;
4339}
4340
4341CXString createCXString(llvm::StringRef String, bool DupString) {
4342 CXString Result;
4343 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4344 char *Spelling = (char *)malloc(String.size() + 1);
4345 memmove(Spelling, String.data(), String.size());
4346 Spelling[String.size()] = 0;
4347 Result.Spelling = Spelling;
4348 Result.MustFreeString = 1;
4349 } else {
4350 Result.Spelling = String.data();
4351 Result.MustFreeString = 0;
4352 }
4353 return Result;
4354}
4355}}
4356
Ted Kremenek04bb7162010-01-22 22:44:15 +00004357//===----------------------------------------------------------------------===//
4358// Misc. utility functions.
4359//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004360
Ted Kremenek04bb7162010-01-22 22:44:15 +00004361extern "C" {
4362
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004363CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004364 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004365}
4366
4367} // end: extern "C"