blob: 279e0fb3a2cce3d2ddddedca3edc4a797f59569b [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"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000034#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000035#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000036#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000037#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000038#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000039#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000040#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000041#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000042#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000043
Benjamin Kramerc2a98162010-03-13 21:22:49 +000044// Needed to define L_TMPNAM on some systems.
45#include <cstdio>
46
Steve Naroff50398192009-08-28 15:28:48 +000047using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000048using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000049using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000050
Douglas Gregor33e9abd2010-01-22 19:49:59 +000051/// \brief The result of comparing two source ranges.
52enum RangeComparisonResult {
53 /// \brief Either the ranges overlap or one of the ranges is invalid.
54 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000055
Douglas Gregor33e9abd2010-01-22 19:49:59 +000056 /// \brief The first range ends before the second range starts.
57 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000058
Douglas Gregor33e9abd2010-01-22 19:49:59 +000059 /// \brief The first range starts after the second range ends.
60 RangeAfter
61};
62
Ted Kremenekf0e23e82010-02-17 00:41:40 +000063/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000064/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065static RangeComparisonResult RangeCompare(SourceManager &SM,
66 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000067 SourceRange R2) {
68 assert(R1.isValid() && "First range is invalid?");
69 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000070 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000071 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000072 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000073 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000074 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075 return RangeAfter;
76 return RangeOverlap;
77}
78
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000079/// \brief Determine if a source location falls within, before, or after a
80/// a given source range.
81static RangeComparisonResult LocationCompare(SourceManager &SM,
82 SourceLocation L, SourceRange R) {
83 assert(R.isValid() && "First range is invalid?");
84 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000085 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000086 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000087 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
88 return RangeBefore;
89 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
90 return RangeAfter;
91 return RangeOverlap;
92}
93
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000094/// \brief Translate a Clang source range into a CIndex source range.
95///
96/// Clang internally represents ranges where the end location points to the
97/// start of the token at the end. However, for external clients it is more
98/// useful to have a CXSourceRange be a proper half-open interval. This routine
99/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000100CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000101 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000102 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000104 // location accordingly.
105 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000106 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000107 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000108 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000109 EndLoc = EndLoc.getFileLocWithOffset(Length);
110 }
111
112 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
113 R.getBegin().getRawEncoding(),
114 EndLoc.getRawEncoding() };
115 return Result;
116}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000117
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000118//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000119// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000120//===----------------------------------------------------------------------===//
121
Steve Naroff89922f82009-08-31 00:59:03 +0000122namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000123
Douglas Gregorb1373d02010-01-20 20:59:29 +0000124// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000125class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000126 public TypeLocVisitor<CursorVisitor, bool>,
127 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000128{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000129 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000130 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000133 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The declaration that serves at the parent of any statement or
136 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000137 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000138
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000139 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000140 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000142 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000143 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000144
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000145 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
146 // to the visitor. Declarations with a PCH level greater than this value will
147 // be suppressed.
148 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000149
150 /// \brief When valid, a source range to which the cursor should restrict
151 /// its search.
152 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000153
Douglas Gregorb1373d02010-01-20 20:59:29 +0000154 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000155 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000156 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000157
158 /// \brief Determine whether this particular source range comes before, comes
159 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000160 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000161 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000162 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
163
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000164 class SetParentRAII {
165 CXCursor &Parent;
166 Decl *&StmtParent;
167 CXCursor OldParent;
168
169 public:
170 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
171 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
172 {
173 Parent = NewParent;
174 if (clang_isDeclaration(Parent.kind))
175 StmtParent = getCursorDecl(Parent);
176 }
177
178 ~SetParentRAII() {
179 Parent = OldParent;
180 if (clang_isDeclaration(Parent.kind))
181 StmtParent = getCursorDecl(Parent);
182 }
183 };
184
Steve Naroff89922f82009-08-31 00:59:03 +0000185public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000186 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
187 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000189 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000191 {
192 Parent.kind = CXCursor_NoDeclFound;
193 Parent.data[0] = 0;
194 Parent.data[1] = 0;
195 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000196 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000197 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000198
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000199 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000200
201 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
202 getPreprocessedEntities();
203
Douglas Gregorb1373d02010-01-20 20:59:29 +0000204 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000206 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000207 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000208 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000209 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000210 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000211 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
212 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000213 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000214 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000215 bool VisitClassTemplatePartialSpecializationDecl(
216 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000217 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000218 bool VisitEnumConstantDecl(EnumConstantDecl *D);
219 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
220 bool VisitFunctionDecl(FunctionDecl *ND);
221 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000222 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000223 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000224 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000225 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000226 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000227 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
228 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
229 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
230 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000231 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000232 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
233 bool VisitObjCImplDecl(ObjCImplDecl *D);
234 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
235 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000236 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
237 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
238 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000239 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000240 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000241 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000242 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000243 bool VisitUsingDecl(UsingDecl *D);
244 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
245 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000246
Douglas Gregor01829d32010-08-31 14:41:23 +0000247 // Name visitor
248 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000249 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000250
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000251 // Template visitors
252 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000253 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000254 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
255
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000256 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000257 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000258 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000259 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000260 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
261 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000262 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000263 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000264 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000265 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
266 bool VisitPointerTypeLoc(PointerTypeLoc TL);
267 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
268 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
269 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
270 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000271 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000272 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000273 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000274 // FIXME: Implement visitors here when the unimplemented TypeLocs get
275 // implemented
276 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
277 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000278
Douglas Gregora59e3902010-01-21 23:27:09 +0000279 // Statement visitors
280 bool VisitStmt(Stmt *S);
281 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000282 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000283 bool VisitIfStmt(IfStmt *S);
284 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000285 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000286 bool VisitWhileStmt(WhileStmt *S);
287 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000288
Douglas Gregor336fd812010-01-23 00:40:08 +0000289 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000290 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000291 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000292 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000293 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000294 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000295 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000296 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000297 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000298 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000299 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000300 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000301 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
302 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000303 bool VisitInitListExpr(InitListExpr *E);
304 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000305 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000306 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000307 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000308 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
309 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000310 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000311 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000312 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000313 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000314 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000315 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000316 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000317 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000318};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000319
Ted Kremenekab188932010-01-05 19:32:54 +0000320} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000321
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000322static SourceRange getRawCursorExtent(CXCursor C);
323
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000324RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000325 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
326}
327
Douglas Gregorb1373d02010-01-20 20:59:29 +0000328/// \brief Visit the given cursor and, if requested by the visitor,
329/// its children.
330///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000331/// \param Cursor the cursor to visit.
332///
333/// \param CheckRegionOfInterest if true, then the caller already checked that
334/// this cursor is within the region of interest.
335///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000336/// \returns true if the visitation should be aborted, false if it
337/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000338bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000339 if (clang_isInvalid(Cursor.kind))
340 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000341
Douglas Gregorb1373d02010-01-20 20:59:29 +0000342 if (clang_isDeclaration(Cursor.kind)) {
343 Decl *D = getCursorDecl(Cursor);
344 assert(D && "Invalid declaration cursor");
345 if (D->getPCHLevel() > MaxPCHLevel)
346 return false;
347
348 if (D->isImplicit())
349 return false;
350 }
351
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000352 // If we have a range of interest, and this cursor doesn't intersect with it,
353 // we're done.
354 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000355 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000356 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357 return false;
358 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000359
Douglas Gregorb1373d02010-01-20 20:59:29 +0000360 switch (Visitor(Cursor, Parent, ClientData)) {
361 case CXChildVisit_Break:
362 return true;
363
364 case CXChildVisit_Continue:
365 return false;
366
367 case CXChildVisit_Recurse:
368 return VisitChildren(Cursor);
369 }
370
Douglas Gregorfd643772010-01-25 16:45:46 +0000371 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372}
373
Douglas Gregor788f5a12010-03-20 00:41:21 +0000374std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
375CursorVisitor::getPreprocessedEntities() {
376 PreprocessingRecord &PPRec
377 = *TU->getPreprocessor().getPreprocessingRecord();
378
379 bool OnlyLocalDecls
380 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
381
382 // There is no region of interest; we have to walk everything.
383 if (RegionOfInterest.isInvalid())
384 return std::make_pair(PPRec.begin(OnlyLocalDecls),
385 PPRec.end(OnlyLocalDecls));
386
387 // Find the file in which the region of interest lands.
388 SourceManager &SM = TU->getSourceManager();
389 std::pair<FileID, unsigned> Begin
390 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
391 std::pair<FileID, unsigned> End
392 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
393
394 // The region of interest spans files; we have to walk everything.
395 if (Begin.first != End.first)
396 return std::make_pair(PPRec.begin(OnlyLocalDecls),
397 PPRec.end(OnlyLocalDecls));
398
399 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
400 = TU->getPreprocessedEntitiesByFile();
401 if (ByFileMap.empty()) {
402 // Build the mapping from files to sets of preprocessed entities.
403 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
404 EEnd = PPRec.end(OnlyLocalDecls);
405 E != EEnd; ++E) {
406 std::pair<FileID, unsigned> P
407 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
408 ByFileMap[P.first].push_back(*E);
409 }
410 }
411
412 return std::make_pair(ByFileMap[Begin.first].begin(),
413 ByFileMap[Begin.first].end());
414}
415
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416/// \brief Visit the children of the given cursor.
417///
418/// \returns true if the visitation should be aborted, false if it
419/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000420bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000421 if (clang_isReference(Cursor.kind)) {
422 // By definition, references have no children.
423 return false;
424 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000425
426 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000428 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000429
Douglas Gregorb1373d02010-01-20 20:59:29 +0000430 if (clang_isDeclaration(Cursor.kind)) {
431 Decl *D = getCursorDecl(Cursor);
432 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000433 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000435
Douglas Gregora59e3902010-01-21 23:27:09 +0000436 if (clang_isStatement(Cursor.kind))
437 return Visit(getCursorStmt(Cursor));
438 if (clang_isExpression(Cursor.kind))
439 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000440
Douglas Gregorb1373d02010-01-20 20:59:29 +0000441 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000442 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000443 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
444 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000445 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
446 TLEnd = CXXUnit->top_level_end();
447 TL != TLEnd; ++TL) {
448 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000449 return true;
450 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000451 } else if (VisitDeclContext(
452 CXXUnit->getASTContext().getTranslationUnitDecl()))
453 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000454
Douglas Gregor0396f462010-03-19 05:22:59 +0000455 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000456 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000457 // FIXME: Once we have the ability to deserialize a preprocessing record,
458 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000459 PreprocessingRecord::iterator E, EEnd;
460 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000461 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
462 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
463 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000464
Douglas Gregor0396f462010-03-19 05:22:59 +0000465 continue;
466 }
467
468 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
469 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
470 return true;
471
472 continue;
473 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000474
475 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
476 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
477 return true;
478
479 continue;
480 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000481 }
482 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000483 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000485
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487 return false;
488}
489
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000490bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000491 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
492 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000493
Ted Kremenek664cffd2010-07-22 11:30:19 +0000494 if (Stmt *Body = B->getBody())
495 return Visit(MakeCXCursor(Body, StmtParent, TU));
496
497 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000498}
499
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000501 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000503
Ted Kremenek23173d72010-05-18 21:09:07 +0000504 Decl *D = *I;
505 if (D->getLexicalDeclContext() != DC)
506 continue;
507
508 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000509
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000510 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000511 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000512 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000513 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000514
515 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000516 case RangeBefore:
517 // This declaration comes before the region of interest; skip it.
518 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000519
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000520 case RangeAfter:
521 // This declaration comes after the region of interest; we're done.
522 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000523
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000524 case RangeOverlap:
525 // This declaration overlaps the region of interest; visit it.
526 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000527 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000528 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000529
Daniel Dunbard52864b2010-02-14 10:02:57 +0000530 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000531 return true;
532 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000533
Douglas Gregorb1373d02010-01-20 20:59:29 +0000534 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000535}
536
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000537bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
538 llvm_unreachable("Translation units are visited directly by Visit()");
539 return false;
540}
541
542bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
543 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
544 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000545
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000546 return false;
547}
548
549bool CursorVisitor::VisitTagDecl(TagDecl *D) {
550 return VisitDeclContext(D);
551}
552
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000553bool CursorVisitor::VisitClassTemplateSpecializationDecl(
554 ClassTemplateSpecializationDecl *D) {
555 bool ShouldVisitBody = false;
556 switch (D->getSpecializationKind()) {
557 case TSK_Undeclared:
558 case TSK_ImplicitInstantiation:
559 // Nothing to visit
560 return false;
561
562 case TSK_ExplicitInstantiationDeclaration:
563 case TSK_ExplicitInstantiationDefinition:
564 break;
565
566 case TSK_ExplicitSpecialization:
567 ShouldVisitBody = true;
568 break;
569 }
570
571 // Visit the template arguments used in the specialization.
572 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
573 TypeLoc TL = SpecType->getTypeLoc();
574 if (TemplateSpecializationTypeLoc *TSTLoc
575 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
576 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
577 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
578 return true;
579 }
580 }
581
582 if (ShouldVisitBody && VisitCXXRecordDecl(D))
583 return true;
584
585 return false;
586}
587
Douglas Gregor74dbe642010-08-31 19:31:58 +0000588bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
589 ClassTemplatePartialSpecializationDecl *D) {
590 // FIXME: Visit the "outer" template parameter lists on the TagDecl
591 // before visiting these template parameters.
592 if (VisitTemplateParameters(D->getTemplateParameters()))
593 return true;
594
595 // Visit the partial specialization arguments.
596 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
597 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
598 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
599 return true;
600
601 return VisitCXXRecordDecl(D);
602}
603
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000604bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000605 // Visit the default argument.
606 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
607 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
608 if (Visit(DefArg->getTypeLoc()))
609 return true;
610
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000611 return false;
612}
613
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
615 if (Expr *Init = D->getInitExpr())
616 return Visit(MakeCXCursor(Init, StmtParent, TU));
617 return false;
618}
619
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000620bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
621 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
622 if (Visit(TSInfo->getTypeLoc()))
623 return true;
624
625 return false;
626}
627
Douglas Gregora67e03f2010-09-09 21:42:20 +0000628/// \brief Compare two base or member initializers based on their source order.
629static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
630 CXXBaseOrMemberInitializer const * const *X
631 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
632 CXXBaseOrMemberInitializer const * const *Y
633 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
634
635 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
636 return -1;
637 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
638 return 1;
639 else
640 return 0;
641}
642
Douglas Gregorb1373d02010-01-20 20:59:29 +0000643bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000644 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
645 // Visit the function declaration's syntactic components in the order
646 // written. This requires a bit of work.
647 TypeLoc TL = TSInfo->getTypeLoc();
648 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
649
650 // If we have a function declared directly (without the use of a typedef),
651 // visit just the return type. Otherwise, just visit the function's type
652 // now.
653 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
654 (!FTL && Visit(TL)))
655 return true;
656
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000657 // Visit the nested-name-specifier, if present.
658 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
659 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
660 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000661
662 // Visit the declaration name.
663 if (VisitDeclarationNameInfo(ND->getNameInfo()))
664 return true;
665
666 // FIXME: Visit explicitly-specified template arguments!
667
668 // Visit the function parameters, if we have a function type.
669 if (FTL && VisitFunctionTypeLoc(*FTL, true))
670 return true;
671
672 // FIXME: Attributes?
673 }
674
Douglas Gregora67e03f2010-09-09 21:42:20 +0000675 if (ND->isThisDeclarationADefinition()) {
676 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
677 // Find the initializers that were written in the source.
678 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
679 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
680 IEnd = Constructor->init_end();
681 I != IEnd; ++I) {
682 if (!(*I)->isWritten())
683 continue;
684
685 WrittenInits.push_back(*I);
686 }
687
688 // Sort the initializers in source order
689 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
690 &CompareCXXBaseOrMemberInitializers);
691
692 // Visit the initializers in source order
693 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
694 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
695 if (Init->isMemberInitializer()) {
696 if (Visit(MakeCursorMemberRef(Init->getMember(),
697 Init->getMemberLocation(), TU)))
698 return true;
699 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
700 if (Visit(BaseInfo->getTypeLoc()))
701 return true;
702 }
703
704 // Visit the initializer value.
705 if (Expr *Initializer = Init->getInit())
706 if (Visit(MakeCXCursor(Initializer, ND, TU)))
707 return true;
708 }
709 }
710
711 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
712 return true;
713 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000714
Douglas Gregorb1373d02010-01-20 20:59:29 +0000715 return false;
716}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000717
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000718bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
719 if (VisitDeclaratorDecl(D))
720 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000721
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000722 if (Expr *BitWidth = D->getBitWidth())
723 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000724
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000725 return false;
726}
727
728bool CursorVisitor::VisitVarDecl(VarDecl *D) {
729 if (VisitDeclaratorDecl(D))
730 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000731
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000732 if (Expr *Init = D->getInit())
733 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000734
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000735 return false;
736}
737
Douglas Gregor84b51d72010-09-01 20:16:53 +0000738bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
739 if (VisitDeclaratorDecl(D))
740 return true;
741
742 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
743 if (Expr *DefArg = D->getDefaultArgument())
744 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
745
746 return false;
747}
748
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000749bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
750 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
751 // before visiting these template parameters.
752 if (VisitTemplateParameters(D->getTemplateParameters()))
753 return true;
754
755 return VisitFunctionDecl(D->getTemplatedDecl());
756}
757
Douglas Gregor39d6f072010-08-31 19:02:00 +0000758bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
759 // FIXME: Visit the "outer" template parameter lists on the TagDecl
760 // before visiting these template parameters.
761 if (VisitTemplateParameters(D->getTemplateParameters()))
762 return true;
763
764 return VisitCXXRecordDecl(D->getTemplatedDecl());
765}
766
Douglas Gregor84b51d72010-09-01 20:16:53 +0000767bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
768 if (VisitTemplateParameters(D->getTemplateParameters()))
769 return true;
770
771 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
772 VisitTemplateArgumentLoc(D->getDefaultArgument()))
773 return true;
774
775 return false;
776}
777
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000778bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000779 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
780 if (Visit(TSInfo->getTypeLoc()))
781 return true;
782
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 PEnd = ND->param_end();
785 P != PEnd; ++P) {
786 if (Visit(MakeCXCursor(*P, TU)))
787 return true;
788 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000789
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000790 if (ND->isThisDeclarationADefinition() &&
791 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
792 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000793
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000794 return false;
795}
796
Douglas Gregora59e3902010-01-21 23:27:09 +0000797bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
798 return VisitDeclContext(D);
799}
800
Douglas Gregorb1373d02010-01-20 20:59:29 +0000801bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000802 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
803 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000804 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000806 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
807 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
808 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000809 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000810 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000811
Douglas Gregora59e3902010-01-21 23:27:09 +0000812 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000813}
814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
816 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
817 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
818 E = PID->protocol_end(); I != E; ++I, ++PL)
819 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
820 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000821
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000822 return VisitObjCContainerDecl(PID);
823}
824
Ted Kremenek23173d72010-05-18 21:09:07 +0000825bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000826 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000827 return true;
828
Ted Kremenek23173d72010-05-18 21:09:07 +0000829 // FIXME: This implements a workaround with @property declarations also being
830 // installed in the DeclContext for the @interface. Eventually this code
831 // should be removed.
832 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
833 if (!CDecl || !CDecl->IsClassExtension())
834 return false;
835
836 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
837 if (!ID)
838 return false;
839
840 IdentifierInfo *PropertyId = PD->getIdentifier();
841 ObjCPropertyDecl *prevDecl =
842 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
843
844 if (!prevDecl)
845 return false;
846
847 // Visit synthesized methods since they will be skipped when visiting
848 // the @interface.
849 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000850 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000851 if (Visit(MakeCXCursor(MD, TU)))
852 return true;
853
854 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000855 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000856 if (Visit(MakeCXCursor(MD, TU)))
857 return true;
858
859 return false;
860}
861
Douglas Gregorb1373d02010-01-20 20:59:29 +0000862bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000863 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000864 if (D->getSuperClass() &&
865 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000867 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000868 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000869
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000870 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
871 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
872 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000873 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000874 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000875
Douglas Gregora59e3902010-01-21 23:27:09 +0000876 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000877}
878
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000879bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
880 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000881}
882
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000883bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000884 // 'ID' could be null when dealing with invalid code.
885 if (ObjCInterfaceDecl *ID = D->getClassInterface())
886 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
887 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000888
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000889 return VisitObjCImplDecl(D);
890}
891
892bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
893#if 0
894 // Issue callbacks for super class.
895 // FIXME: No source location information!
896 if (D->getSuperClass() &&
897 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000898 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000899 TU)))
900 return true;
901#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000903 return VisitObjCImplDecl(D);
904}
905
906bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
907 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
908 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
909 E = D->protocol_end();
910 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000911 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000912 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000913
914 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000915}
916
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000917bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
918 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
919 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
920 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000921
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000922 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000923}
924
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000925bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
926 return VisitDeclContext(D);
927}
928
Douglas Gregor69319002010-08-31 23:48:11 +0000929bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000930 // Visit nested-name-specifier.
931 if (NestedNameSpecifier *Qualifier = D->getQualifier())
932 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
933 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000934
935 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
936 D->getTargetNameLoc(), TU));
937}
938
Douglas Gregor7e242562010-09-01 19:52:22 +0000939bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000940 // Visit nested-name-specifier.
941 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
942 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
943 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000944
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000945 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
946 return true;
947
Douglas Gregor7e242562010-09-01 19:52:22 +0000948 return VisitDeclarationNameInfo(D->getNameInfo());
949}
950
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000951bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000952 // Visit nested-name-specifier.
953 if (NestedNameSpecifier *Qualifier = D->getQualifier())
954 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
955 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000956
957 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
958 D->getIdentLocation(), TU));
959}
960
Douglas Gregor7e242562010-09-01 19:52:22 +0000961bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000962 // Visit nested-name-specifier.
963 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
964 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
965 return true;
966
Douglas Gregor7e242562010-09-01 19:52:22 +0000967 return VisitDeclarationNameInfo(D->getNameInfo());
968}
969
970bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
971 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000972 // Visit nested-name-specifier.
973 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
974 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
975 return true;
976
Douglas Gregor7e242562010-09-01 19:52:22 +0000977 return false;
978}
979
Douglas Gregor01829d32010-08-31 14:41:23 +0000980bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
981 switch (Name.getName().getNameKind()) {
982 case clang::DeclarationName::Identifier:
983 case clang::DeclarationName::CXXLiteralOperatorName:
984 case clang::DeclarationName::CXXOperatorName:
985 case clang::DeclarationName::CXXUsingDirective:
986 return false;
987
988 case clang::DeclarationName::CXXConstructorName:
989 case clang::DeclarationName::CXXDestructorName:
990 case clang::DeclarationName::CXXConversionFunctionName:
991 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
992 return Visit(TSInfo->getTypeLoc());
993 return false;
994
995 case clang::DeclarationName::ObjCZeroArgSelector:
996 case clang::DeclarationName::ObjCOneArgSelector:
997 case clang::DeclarationName::ObjCMultiArgSelector:
998 // FIXME: Per-identifier location info?
999 return false;
1000 }
1001
1002 return false;
1003}
1004
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001005bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1006 SourceRange Range) {
1007 // FIXME: This whole routine is a hack to work around the lack of proper
1008 // source information in nested-name-specifiers (PR5791). Since we do have
1009 // a beginning source location, we can visit the first component of the
1010 // nested-name-specifier, if it's a single-token component.
1011 if (!NNS)
1012 return false;
1013
1014 // Get the first component in the nested-name-specifier.
1015 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1016 NNS = Prefix;
1017
1018 switch (NNS->getKind()) {
1019 case NestedNameSpecifier::Namespace:
1020 // FIXME: The token at this source location might actually have been a
1021 // namespace alias, but we don't model that. Lame!
1022 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1023 TU));
1024
1025 case NestedNameSpecifier::TypeSpec: {
1026 // If the type has a form where we know that the beginning of the source
1027 // range matches up with a reference cursor. Visit the appropriate reference
1028 // cursor.
1029 Type *T = NNS->getAsType();
1030 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1031 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1032 if (const TagType *Tag = dyn_cast<TagType>(T))
1033 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1034 if (const TemplateSpecializationType *TST
1035 = dyn_cast<TemplateSpecializationType>(T))
1036 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1037 break;
1038 }
1039
1040 case NestedNameSpecifier::TypeSpecWithTemplate:
1041 case NestedNameSpecifier::Global:
1042 case NestedNameSpecifier::Identifier:
1043 break;
1044 }
1045
1046 return false;
1047}
1048
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001049bool CursorVisitor::VisitTemplateParameters(
1050 const TemplateParameterList *Params) {
1051 if (!Params)
1052 return false;
1053
1054 for (TemplateParameterList::const_iterator P = Params->begin(),
1055 PEnd = Params->end();
1056 P != PEnd; ++P) {
1057 if (Visit(MakeCXCursor(*P, TU)))
1058 return true;
1059 }
1060
1061 return false;
1062}
1063
Douglas Gregor0b36e612010-08-31 20:37:03 +00001064bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1065 switch (Name.getKind()) {
1066 case TemplateName::Template:
1067 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1068
1069 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001070 // Visit the overloaded template set.
1071 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1072 return true;
1073
Douglas Gregor0b36e612010-08-31 20:37:03 +00001074 return false;
1075
1076 case TemplateName::DependentTemplate:
1077 // FIXME: Visit nested-name-specifier.
1078 return false;
1079
1080 case TemplateName::QualifiedTemplate:
1081 // FIXME: Visit nested-name-specifier.
1082 return Visit(MakeCursorTemplateRef(
1083 Name.getAsQualifiedTemplateName()->getDecl(),
1084 Loc, TU));
1085 }
1086
1087 return false;
1088}
1089
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001090bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1091 switch (TAL.getArgument().getKind()) {
1092 case TemplateArgument::Null:
1093 case TemplateArgument::Integral:
1094 return false;
1095
1096 case TemplateArgument::Pack:
1097 // FIXME: Implement when variadic templates come along.
1098 return false;
1099
1100 case TemplateArgument::Type:
1101 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1102 return Visit(TSInfo->getTypeLoc());
1103 return false;
1104
1105 case TemplateArgument::Declaration:
1106 if (Expr *E = TAL.getSourceDeclExpression())
1107 return Visit(MakeCXCursor(E, StmtParent, TU));
1108 return false;
1109
1110 case TemplateArgument::Expression:
1111 if (Expr *E = TAL.getSourceExpression())
1112 return Visit(MakeCXCursor(E, StmtParent, TU));
1113 return false;
1114
1115 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001116 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1117 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001118 }
1119
1120 return false;
1121}
1122
Ted Kremeneka0536d82010-05-07 01:04:29 +00001123bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1124 return VisitDeclContext(D);
1125}
1126
Douglas Gregor01829d32010-08-31 14:41:23 +00001127bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1128 return Visit(TL.getUnqualifiedLoc());
1129}
1130
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001131bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1132 ASTContext &Context = TU->getASTContext();
1133
1134 // Some builtin types (such as Objective-C's "id", "sel", and
1135 // "Class") have associated declarations. Create cursors for those.
1136 QualType VisitType;
1137 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001138 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001139 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001140 case BuiltinType::Char_U:
1141 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001142 case BuiltinType::Char16:
1143 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001144 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001145 case BuiltinType::UInt:
1146 case BuiltinType::ULong:
1147 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001148 case BuiltinType::UInt128:
1149 case BuiltinType::Char_S:
1150 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001151 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001152 case BuiltinType::Short:
1153 case BuiltinType::Int:
1154 case BuiltinType::Long:
1155 case BuiltinType::LongLong:
1156 case BuiltinType::Int128:
1157 case BuiltinType::Float:
1158 case BuiltinType::Double:
1159 case BuiltinType::LongDouble:
1160 case BuiltinType::NullPtr:
1161 case BuiltinType::Overload:
1162 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001163 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001164
1165 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001166 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001167
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001168 case BuiltinType::ObjCId:
1169 VisitType = Context.getObjCIdType();
1170 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001171
1172 case BuiltinType::ObjCClass:
1173 VisitType = Context.getObjCClassType();
1174 break;
1175
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001176 case BuiltinType::ObjCSel:
1177 VisitType = Context.getObjCSelType();
1178 break;
1179 }
1180
1181 if (!VisitType.isNull()) {
1182 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001183 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001184 TU));
1185 }
1186
1187 return false;
1188}
1189
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001190bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1191 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1192}
1193
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001194bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1195 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1196}
1197
1198bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1199 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1200}
1201
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001202bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001203 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001204 // no context information with which we can match up the depth/index in the
1205 // type to the appropriate
1206 return false;
1207}
1208
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001209bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1210 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1211 return true;
1212
John McCallc12c5bb2010-05-15 11:32:37 +00001213 return false;
1214}
1215
1216bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1217 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1218 return true;
1219
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001220 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1221 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1222 TU)))
1223 return true;
1224 }
1225
1226 return false;
1227}
1228
1229bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001230 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001231}
1232
1233bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1234 return Visit(TL.getPointeeLoc());
1235}
1236
1237bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1238 return Visit(TL.getPointeeLoc());
1239}
1240
1241bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1242 return Visit(TL.getPointeeLoc());
1243}
1244
1245bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001246 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001247}
1248
1249bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001250 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001251}
1252
Douglas Gregor01829d32010-08-31 14:41:23 +00001253bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1254 bool SkipResultType) {
1255 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001256 return true;
1257
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001258 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001259 if (Decl *D = TL.getArg(I))
1260 if (Visit(MakeCXCursor(D, TU)))
1261 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001262
1263 return false;
1264}
1265
1266bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1267 if (Visit(TL.getElementLoc()))
1268 return true;
1269
1270 if (Expr *Size = TL.getSizeExpr())
1271 return Visit(MakeCXCursor(Size, StmtParent, TU));
1272
1273 return false;
1274}
1275
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001276bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1277 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001278 // Visit the template name.
1279 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1280 TL.getTemplateNameLoc()))
1281 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001282
1283 // Visit the template arguments.
1284 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1285 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1286 return true;
1287
1288 return false;
1289}
1290
Douglas Gregor2332c112010-01-21 20:48:56 +00001291bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1292 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1293}
1294
1295bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1296 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1297 return Visit(TSInfo->getTypeLoc());
1298
1299 return false;
1300}
1301
Douglas Gregora59e3902010-01-21 23:27:09 +00001302bool CursorVisitor::VisitStmt(Stmt *S) {
1303 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1304 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001305 if (Stmt *C = *Child)
1306 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1307 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001308 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001309
Douglas Gregora59e3902010-01-21 23:27:09 +00001310 return false;
1311}
1312
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001313bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1314 // Specially handle CaseStmts because they can be nested, e.g.:
1315 //
1316 // case 1:
1317 // case 2:
1318 //
1319 // In this case the second CaseStmt is the child of the first. Walking
1320 // these recursively can blow out the stack.
1321 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1322 while (true) {
1323 // Set the Parent field to Cursor, then back to its old value once we're
1324 // done.
1325 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1326
1327 if (Stmt *LHS = S->getLHS())
1328 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1329 return true;
1330 if (Stmt *RHS = S->getRHS())
1331 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1332 return true;
1333 if (Stmt *SubStmt = S->getSubStmt()) {
1334 if (!isa<CaseStmt>(SubStmt))
1335 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1336
1337 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1338 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1339 Cursor = MakeCXCursor(CS, StmtParent, TU);
1340 if (RegionOfInterest.isValid()) {
1341 SourceRange Range = CS->getSourceRange();
1342 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1343 return false;
1344 }
1345
1346 switch (Visitor(Cursor, Parent, ClientData)) {
1347 case CXChildVisit_Break: return true;
1348 case CXChildVisit_Continue: return false;
1349 case CXChildVisit_Recurse:
1350 // Perform tail-recursion manually.
1351 S = CS;
1352 continue;
1353 }
1354 }
1355 return false;
1356 }
1357}
1358
Douglas Gregora59e3902010-01-21 23:27:09 +00001359bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1360 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1361 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001362 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001363 return true;
1364 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001365
Douglas Gregora59e3902010-01-21 23:27:09 +00001366 return false;
1367}
1368
Douglas Gregor36897b02010-09-10 00:22:18 +00001369bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1370 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1371}
1372
Douglas Gregorf5bab412010-01-22 01:00:11 +00001373bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1374 if (VarDecl *Var = S->getConditionVariable()) {
1375 if (Visit(MakeCXCursor(Var, TU)))
1376 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377 }
1378
Douglas Gregor263b47b2010-01-25 16:12:32 +00001379 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1380 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001381 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1382 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001383 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1384 return true;
1385
1386 return false;
1387}
1388
1389bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1390 if (VarDecl *Var = S->getConditionVariable()) {
1391 if (Visit(MakeCXCursor(Var, TU)))
1392 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393 }
1394
Douglas Gregor263b47b2010-01-25 16:12:32 +00001395 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1396 return true;
1397 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1398 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001399
Douglas Gregor263b47b2010-01-25 16:12:32 +00001400 return false;
1401}
1402
1403bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1404 if (VarDecl *Var = S->getConditionVariable()) {
1405 if (Visit(MakeCXCursor(Var, TU)))
1406 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001407 }
1408
Douglas Gregor263b47b2010-01-25 16:12:32 +00001409 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1410 return true;
1411 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001412 return true;
1413
Douglas Gregor263b47b2010-01-25 16:12:32 +00001414 return false;
1415}
1416
1417bool CursorVisitor::VisitForStmt(ForStmt *S) {
1418 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1419 return true;
1420 if (VarDecl *Var = S->getConditionVariable()) {
1421 if (Visit(MakeCXCursor(Var, TU)))
1422 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001423 }
1424
Douglas Gregor263b47b2010-01-25 16:12:32 +00001425 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1426 return true;
1427 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1428 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001429 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1430 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001431
Douglas Gregorf5bab412010-01-22 01:00:11 +00001432 return false;
1433}
1434
Douglas Gregor8947a752010-09-02 20:35:02 +00001435bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1436 // Visit nested-name-specifier, if present.
1437 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1438 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1439 return true;
1440
1441 // Visit declaration name.
1442 if (VisitDeclarationNameInfo(E->getNameInfo()))
1443 return true;
1444
1445 // Visit explicitly-specified template arguments.
1446 if (E->hasExplicitTemplateArgs()) {
1447 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1448 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1449 *ArgEnd = Arg + Args.NumTemplateArgs;
1450 Arg != ArgEnd; ++Arg)
1451 if (VisitTemplateArgumentLoc(*Arg))
1452 return true;
1453 }
1454
1455 return false;
1456}
1457
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001458bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1459 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1460 return true;
1461
1462 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1463 return true;
1464
1465 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1466 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1467 return true;
1468
1469 return false;
1470}
1471
Ted Kremenek3064ef92010-08-27 21:34:58 +00001472bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1473 if (D->isDefinition()) {
1474 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1475 E = D->bases_end(); I != E; ++I) {
1476 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1477 return true;
1478 }
1479 }
1480
1481 return VisitTagDecl(D);
1482}
1483
1484
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001485bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1486 return Visit(B->getBlockDecl());
1487}
1488
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001489bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001490 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001491 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1492 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001493
1494 // Visit the components of the offsetof expression.
1495 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1496 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1497 const OffsetOfNode &Node = E->getComponent(I);
1498 switch (Node.getKind()) {
1499 case OffsetOfNode::Array:
1500 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1501 StmtParent, TU)))
1502 return true;
1503 break;
1504
1505 case OffsetOfNode::Field:
1506 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1507 TU)))
1508 return true;
1509 break;
1510
1511 case OffsetOfNode::Identifier:
1512 case OffsetOfNode::Base:
1513 continue;
1514 }
1515 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001516
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001517 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001518}
1519
Douglas Gregor336fd812010-01-23 00:40:08 +00001520bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1521 if (E->isArgumentType()) {
1522 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1523 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001524
Douglas Gregor336fd812010-01-23 00:40:08 +00001525 return false;
1526 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001527
Douglas Gregor336fd812010-01-23 00:40:08 +00001528 return VisitExpr(E);
1529}
1530
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001531bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1532 // Visit the base expression.
1533 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1534 return true;
1535
1536 // Visit the nested-name-specifier
1537 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1538 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1539 return true;
1540
1541 // Visit the declaration name.
1542 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1543 return true;
1544
1545 // Visit the explicitly-specified template arguments, if any.
1546 if (E->hasExplicitTemplateArgs()) {
1547 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1548 *ArgEnd = Arg + E->getNumTemplateArgs();
1549 Arg != ArgEnd;
1550 ++Arg) {
1551 if (VisitTemplateArgumentLoc(*Arg))
1552 return true;
1553 }
1554 }
1555
1556 return false;
1557}
1558
Douglas Gregor336fd812010-01-23 00:40:08 +00001559bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1560 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1561 if (Visit(TSInfo->getTypeLoc()))
1562 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001563
Douglas Gregor336fd812010-01-23 00:40:08 +00001564 return VisitCastExpr(E);
1565}
1566
1567bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1568 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1569 if (Visit(TSInfo->getTypeLoc()))
1570 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001571
Douglas Gregor336fd812010-01-23 00:40:08 +00001572 return VisitExpr(E);
1573}
1574
Douglas Gregor36897b02010-09-10 00:22:18 +00001575bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1576 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1577}
1578
Douglas Gregor648220e2010-08-10 15:02:34 +00001579bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1580 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1581 Visit(E->getArgTInfo2()->getTypeLoc());
1582}
1583
1584bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1585 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1586 return true;
1587
1588 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1589}
1590
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001591bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1592 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001593 if (InitListExpr *Syntactic = E->getSyntacticForm())
1594 return VisitExpr(Syntactic);
1595
1596 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001597}
1598
1599bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1600 // Visit the designators.
1601 typedef DesignatedInitExpr::Designator Designator;
1602 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1603 DEnd = E->designators_end();
1604 D != DEnd; ++D) {
1605 if (D->isFieldDesignator()) {
1606 if (FieldDecl *Field = D->getField())
1607 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1608 return true;
1609
1610 continue;
1611 }
1612
1613 if (D->isArrayDesignator()) {
1614 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1615 return true;
1616
1617 continue;
1618 }
1619
1620 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1621 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1622 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1623 return true;
1624 }
1625
1626 // Visit the initializer value itself.
1627 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1628}
1629
Douglas Gregor94802292010-09-02 21:20:16 +00001630bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1631 if (E->isTypeOperand()) {
1632 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1633 return Visit(TSInfo->getTypeLoc());
1634
1635 return false;
1636 }
1637
1638 return VisitExpr(E);
1639}
1640
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001641bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1642 if (E->isTypeOperand()) {
1643 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1644 return Visit(TSInfo->getTypeLoc());
1645
1646 return false;
1647 }
1648
1649 return VisitExpr(E);
1650}
1651
Douglas Gregorab6677e2010-09-08 00:15:04 +00001652bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1653 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1654 return Visit(TSInfo->getTypeLoc());
1655
1656 return VisitExpr(E);
1657}
1658
1659bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1660 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1661 return Visit(TSInfo->getTypeLoc());
1662
1663 return false;
1664}
1665
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001666bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1667 // Visit placement arguments.
1668 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1669 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1670 return true;
1671
1672 // Visit the allocated type.
1673 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1674 if (Visit(TSInfo->getTypeLoc()))
1675 return true;
1676
1677 // Visit the array size, if any.
1678 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1679 return true;
1680
1681 // Visit the initializer or constructor arguments.
1682 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1683 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1684 return true;
1685
1686 return false;
1687}
1688
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001689bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1690 // Visit base expression.
1691 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1692 return true;
1693
1694 // Visit the nested-name-specifier.
1695 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1696 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1697 return true;
1698
1699 // Visit the scope type that looks disturbingly like the nested-name-specifier
1700 // but isn't.
1701 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1702 if (Visit(TSInfo->getTypeLoc()))
1703 return true;
1704
1705 // Visit the name of the type being destroyed.
1706 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1707 if (Visit(TSInfo->getTypeLoc()))
1708 return true;
1709
1710 return false;
1711}
1712
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001713bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1714 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1715}
1716
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001717bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001718 // Visit the nested-name-specifier.
1719 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1720 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1721 return true;
1722
1723 // Visit the declaration name.
1724 if (VisitDeclarationNameInfo(E->getNameInfo()))
1725 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001726
1727 // Visit the overloaded declaration reference.
1728 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1729 return true;
1730
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001731 // Visit the explicitly-specified template arguments.
1732 if (const ExplicitTemplateArgumentList *ArgList
1733 = E->getOptionalExplicitTemplateArgs()) {
1734 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1735 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1736 Arg != ArgEnd; ++Arg) {
1737 if (VisitTemplateArgumentLoc(*Arg))
1738 return true;
1739 }
1740 }
1741
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001742 return false;
1743}
1744
Douglas Gregorbfebed22010-09-03 17:24:10 +00001745bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1746 DependentScopeDeclRefExpr *E) {
1747 // Visit the nested-name-specifier.
1748 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1749 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1750 return true;
1751
1752 // Visit the declaration name.
1753 if (VisitDeclarationNameInfo(E->getNameInfo()))
1754 return true;
1755
1756 // Visit the explicitly-specified template arguments.
1757 if (const ExplicitTemplateArgumentList *ArgList
1758 = E->getOptionalExplicitTemplateArgs()) {
1759 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1760 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1761 Arg != ArgEnd; ++Arg) {
1762 if (VisitTemplateArgumentLoc(*Arg))
1763 return true;
1764 }
1765 }
1766
1767 return false;
1768}
1769
Douglas Gregorab6677e2010-09-08 00:15:04 +00001770bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1771 CXXUnresolvedConstructExpr *E) {
1772 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1773 if (Visit(TSInfo->getTypeLoc()))
1774 return true;
1775
1776 return VisitExpr(E);
1777}
1778
Douglas Gregor25d63622010-09-03 17:35:34 +00001779bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1780 CXXDependentScopeMemberExpr *E) {
1781 // Visit the base expression, if there is one.
1782 if (!E->isImplicitAccess() &&
1783 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1784 return true;
1785
1786 // Visit the nested-name-specifier.
1787 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1788 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1789 return true;
1790
1791 // Visit the declaration name.
1792 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1793 return true;
1794
1795 // Visit the explicitly-specified template arguments.
1796 if (const ExplicitTemplateArgumentList *ArgList
1797 = E->getOptionalExplicitTemplateArgs()) {
1798 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1799 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1800 Arg != ArgEnd; ++Arg) {
1801 if (VisitTemplateArgumentLoc(*Arg))
1802 return true;
1803 }
1804 }
1805
1806 return false;
1807}
1808
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001809bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1810 // Visit the base expression, if there is one.
1811 if (!E->isImplicitAccess() &&
1812 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1813 return true;
1814
1815 return VisitOverloadExpr(E);
1816}
Douglas Gregor25d63622010-09-03 17:35:34 +00001817
Douglas Gregorc2350e52010-03-08 16:40:19 +00001818bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001819 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1820 if (Visit(TSInfo->getTypeLoc()))
1821 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001822
1823 return VisitExpr(E);
1824}
1825
Douglas Gregor81d34662010-04-20 15:39:42 +00001826bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1827 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1828}
1829
1830
Ted Kremenek09dfa372010-02-18 05:46:33 +00001831bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001832 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1833 i != e; ++i)
1834 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001835 return true;
1836
1837 return false;
1838}
1839
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001840static llvm::sys::Mutex EnableMultithreadingMutex;
1841static bool EnabledMultithreading;
1842
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001843extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001844CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1845 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00001846 // Disable pretty stack trace functionality, which will otherwise be a very
1847 // poor citizen of the world and set up all sorts of signal handlers.
1848 llvm::DisablePrettyStackTrace = true;
1849
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001850 // We use crash recovery to make some of our APIs more reliable, implicitly
1851 // enable it.
1852 llvm::CrashRecoveryContext::Enable();
1853
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001854 // Enable support for multithreading in LLVM.
1855 {
1856 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
1857 if (!EnabledMultithreading) {
1858 llvm::llvm_start_multithreaded();
1859 EnabledMultithreading = true;
1860 }
1861 }
1862
Douglas Gregora030b7c2010-01-22 20:35:53 +00001863 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001864 if (excludeDeclarationsFromPCH)
1865 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001866 if (displayDiagnostics)
1867 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001868 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001869}
1870
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001871void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001872 if (CIdx)
1873 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001874}
1875
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001876CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001877 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001878 if (!CIdx)
1879 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001880
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001881 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001882
Douglas Gregor28019772010-04-05 23:52:57 +00001883 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001884 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001885 CXXIdx->getOnlyLocalDecls(),
1886 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001887}
1888
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001889unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00001890 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00001891 CXTranslationUnit_CacheCompletionResults |
1892 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001893}
1894
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001895CXTranslationUnit
1896clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1897 const char *source_filename,
1898 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001899 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001900 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001901 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001902 return clang_parseTranslationUnit(CIdx, source_filename,
1903 command_line_args, num_command_line_args,
1904 unsaved_files, num_unsaved_files,
1905 CXTranslationUnit_DetailedPreprocessingRecord);
1906}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001907
1908struct ParseTranslationUnitInfo {
1909 CXIndex CIdx;
1910 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001911 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001912 int num_command_line_args;
1913 struct CXUnsavedFile *unsaved_files;
1914 unsigned num_unsaved_files;
1915 unsigned options;
1916 CXTranslationUnit result;
1917};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001918static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001919 ParseTranslationUnitInfo *PTUI =
1920 static_cast<ParseTranslationUnitInfo*>(UserData);
1921 CXIndex CIdx = PTUI->CIdx;
1922 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001923 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001924 int num_command_line_args = PTUI->num_command_line_args;
1925 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1926 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1927 unsigned options = PTUI->options;
1928 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001929
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001930 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001931 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001932
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001933 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1934
Douglas Gregor44c181a2010-07-23 00:33:23 +00001935 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001936 bool CompleteTranslationUnit
1937 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001938 bool CacheCodeCompetionResults
1939 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001940 bool CXXPrecompilePreamble
1941 = options & CXTranslationUnit_CXXPrecompiledPreamble;
1942 bool CXXChainedPCH
1943 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001944
Douglas Gregor5352ac02010-01-28 00:27:43 +00001945 // Configure the diagnostics.
1946 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001947 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1948 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001949
Douglas Gregor4db64a42010-01-23 00:14:00 +00001950 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1951 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001952 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001953 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001954 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001955 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1956 Buffer));
1957 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001958
Douglas Gregorb10daed2010-10-11 16:52:23 +00001959 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001960
Ted Kremenek139ba862009-10-22 00:03:57 +00001961 // The 'source_filename' argument is optional. If the caller does not
1962 // specify it then it is assumed that the source file is specified
1963 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001964 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00001965 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001966
1967 // Since the Clang C library is primarily used by batch tools dealing with
1968 // (often very broken) source code, where spell-checking can have a
1969 // significant negative impact on performance (particularly when
1970 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00001971 // Only do this if we haven't found a spell-checking-related argument.
1972 bool FoundSpellCheckingArgument = false;
1973 for (int I = 0; I != num_command_line_args; ++I) {
1974 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
1975 strcmp(command_line_args[I], "-fspell-checking") == 0) {
1976 FoundSpellCheckingArgument = true;
1977 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001978 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00001979 }
1980 if (!FoundSpellCheckingArgument)
1981 Args.push_back("-fno-spell-checking");
1982
1983 Args.insert(Args.end(), command_line_args,
1984 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00001985
Douglas Gregor44c181a2010-07-23 00:33:23 +00001986 // Do we need the detailed preprocessing record?
1987 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00001988 Args.push_back("-Xclang");
1989 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001990 }
1991
Douglas Gregorb10daed2010-10-11 16:52:23 +00001992 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00001993 llvm::OwningPtr<ASTUnit> Unit(
1994 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
1995 Diags,
1996 CXXIdx->getClangResourcesPath(),
1997 CXXIdx->getOnlyLocalDecls(),
1998 RemappedFiles.data(),
1999 RemappedFiles.size(),
2000 /*CaptureDiagnostics=*/true,
2001 PrecompilePreamble,
2002 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002003 CacheCodeCompetionResults,
2004 CXXPrecompilePreamble,
2005 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002006
Douglas Gregorb10daed2010-10-11 16:52:23 +00002007 if (NumErrors != Diags->getNumErrors()) {
2008 // Make sure to check that 'Unit' is non-NULL.
2009 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2010 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2011 DEnd = Unit->stored_diag_end();
2012 D != DEnd; ++D) {
2013 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2014 CXString Msg = clang_formatDiagnostic(&Diag,
2015 clang_defaultDiagnosticDisplayOptions());
2016 fprintf(stderr, "%s\n", clang_getCString(Msg));
2017 clang_disposeString(Msg);
2018 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002019#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002020 // On Windows, force a flush, since there may be multiple copies of
2021 // stderr and stdout in the file system, all with different buffers
2022 // but writing to the same device.
2023 fflush(stderr);
2024#endif
2025 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002026 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002027
Douglas Gregorb10daed2010-10-11 16:52:23 +00002028 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002029}
2030CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2031 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002032 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002033 int num_command_line_args,
2034 struct CXUnsavedFile *unsaved_files,
2035 unsigned num_unsaved_files,
2036 unsigned options) {
2037 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2038 num_command_line_args, unsaved_files, num_unsaved_files,
2039 options, 0 };
2040 llvm::CrashRecoveryContext CRC;
2041
2042 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002043 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2044 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2045 fprintf(stderr, " 'command_line_args' : [");
2046 for (int i = 0; i != num_command_line_args; ++i) {
2047 if (i)
2048 fprintf(stderr, ", ");
2049 fprintf(stderr, "'%s'", command_line_args[i]);
2050 }
2051 fprintf(stderr, "],\n");
2052 fprintf(stderr, " 'unsaved_files' : [");
2053 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2054 if (i)
2055 fprintf(stderr, ", ");
2056 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2057 unsaved_files[i].Length);
2058 }
2059 fprintf(stderr, "],\n");
2060 fprintf(stderr, " 'options' : %d,\n", options);
2061 fprintf(stderr, "}\n");
2062
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002063 return 0;
2064 }
2065
2066 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002067}
2068
Douglas Gregor19998442010-08-13 15:35:05 +00002069unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2070 return CXSaveTranslationUnit_None;
2071}
2072
2073int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2074 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002075 if (!TU)
2076 return 1;
2077
2078 return static_cast<ASTUnit *>(TU)->Save(FileName);
2079}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002080
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002081void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002082 if (CTUnit) {
2083 // If the translation unit has been marked as unsafe to free, just discard
2084 // it.
2085 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2086 return;
2087
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002088 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002089 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002090}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002091
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002092unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2093 return CXReparse_None;
2094}
2095
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002096struct ReparseTranslationUnitInfo {
2097 CXTranslationUnit TU;
2098 unsigned num_unsaved_files;
2099 struct CXUnsavedFile *unsaved_files;
2100 unsigned options;
2101 int result;
2102};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002103
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002104static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002105 ReparseTranslationUnitInfo *RTUI =
2106 static_cast<ReparseTranslationUnitInfo*>(UserData);
2107 CXTranslationUnit TU = RTUI->TU;
2108 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2109 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2110 unsigned options = RTUI->options;
2111 (void) options;
2112 RTUI->result = 1;
2113
Douglas Gregorabc563f2010-07-19 21:46:24 +00002114 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002115 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002116
2117 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2118 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002119
2120 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2121 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2122 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2123 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002124 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002125 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2126 Buffer));
2127 }
2128
Douglas Gregor593b0c12010-09-23 18:47:53 +00002129 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2130 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002131}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002132
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002133int clang_reparseTranslationUnit(CXTranslationUnit TU,
2134 unsigned num_unsaved_files,
2135 struct CXUnsavedFile *unsaved_files,
2136 unsigned options) {
2137 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2138 options, 0 };
2139 llvm::CrashRecoveryContext CRC;
2140
2141 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002142 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002143 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2144 return 1;
2145 }
2146
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002147
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002148 return RTUI.result;
2149}
2150
Douglas Gregordf95a132010-08-09 20:45:32 +00002151
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002152CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002153 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002154 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002155
Steve Naroff77accc12009-09-03 18:19:54 +00002156 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002157 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002158}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002159
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002160CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002161 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002162 return Result;
2163}
2164
Ted Kremenekfb480492010-01-13 21:46:36 +00002165} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002166
Ted Kremenekfb480492010-01-13 21:46:36 +00002167//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002168// CXSourceLocation and CXSourceRange Operations.
2169//===----------------------------------------------------------------------===//
2170
Douglas Gregorb9790342010-01-22 21:44:22 +00002171extern "C" {
2172CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002173 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002174 return Result;
2175}
2176
2177unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002178 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2179 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2180 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002181}
2182
2183CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2184 CXFile file,
2185 unsigned line,
2186 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002187 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002188 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002189
Douglas Gregorb9790342010-01-22 21:44:22 +00002190 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2191 SourceLocation SLoc
2192 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002193 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002194 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002195 if (SLoc.isInvalid()) return clang_getNullLocation();
2196
2197 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2198}
2199
2200CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2201 CXFile file,
2202 unsigned offset) {
2203 if (!tu || !file)
2204 return clang_getNullLocation();
2205
2206 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2207 SourceLocation Start
2208 = CXXUnit->getSourceManager().getLocation(
2209 static_cast<const FileEntry *>(file),
2210 1, 1);
2211 if (Start.isInvalid()) return clang_getNullLocation();
2212
2213 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2214
2215 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002216
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002217 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002218}
2219
Douglas Gregor5352ac02010-01-28 00:27:43 +00002220CXSourceRange clang_getNullRange() {
2221 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2222 return Result;
2223}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002224
Douglas Gregor5352ac02010-01-28 00:27:43 +00002225CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2226 if (begin.ptr_data[0] != end.ptr_data[0] ||
2227 begin.ptr_data[1] != end.ptr_data[1])
2228 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002229
2230 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002231 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002232 return Result;
2233}
2234
Douglas Gregor46766dc2010-01-26 19:19:08 +00002235void clang_getInstantiationLocation(CXSourceLocation location,
2236 CXFile *file,
2237 unsigned *line,
2238 unsigned *column,
2239 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002240 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2241
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002242 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002243 if (file)
2244 *file = 0;
2245 if (line)
2246 *line = 0;
2247 if (column)
2248 *column = 0;
2249 if (offset)
2250 *offset = 0;
2251 return;
2252 }
2253
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002254 const SourceManager &SM =
2255 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002256 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002257
2258 if (file)
2259 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2260 if (line)
2261 *line = SM.getInstantiationLineNumber(InstLoc);
2262 if (column)
2263 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002264 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002265 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002266}
2267
Douglas Gregor1db19de2010-01-19 21:36:55 +00002268CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002269 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002270 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002271 return Result;
2272}
2273
2274CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002275 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002276 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002277 return Result;
2278}
2279
Douglas Gregorb9790342010-01-22 21:44:22 +00002280} // end: extern "C"
2281
Douglas Gregor1db19de2010-01-19 21:36:55 +00002282//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002283// CXFile Operations.
2284//===----------------------------------------------------------------------===//
2285
2286extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002287CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002288 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002289 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002290
Steve Naroff88145032009-10-27 14:35:18 +00002291 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002292 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002293}
2294
2295time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002296 if (!SFile)
2297 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002298
Steve Naroff88145032009-10-27 14:35:18 +00002299 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2300 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002301}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002302
Douglas Gregorb9790342010-01-22 21:44:22 +00002303CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2304 if (!tu)
2305 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002306
Douglas Gregorb9790342010-01-22 21:44:22 +00002307 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002308
Douglas Gregorb9790342010-01-22 21:44:22 +00002309 FileManager &FMgr = CXXUnit->getFileManager();
2310 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2311 return const_cast<FileEntry *>(File);
2312}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002313
Ted Kremenekfb480492010-01-13 21:46:36 +00002314} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002315
Ted Kremenekfb480492010-01-13 21:46:36 +00002316//===----------------------------------------------------------------------===//
2317// CXCursor Operations.
2318//===----------------------------------------------------------------------===//
2319
Ted Kremenekfb480492010-01-13 21:46:36 +00002320static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002321 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2322 return getDeclFromExpr(CE->getSubExpr());
2323
Ted Kremenekfb480492010-01-13 21:46:36 +00002324 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2325 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002326 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2327 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002328 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2329 return ME->getMemberDecl();
2330 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2331 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002332 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2333 return PRE->getProperty();
2334
Ted Kremenekfb480492010-01-13 21:46:36 +00002335 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2336 return getDeclFromExpr(CE->getCallee());
Ted Kremenekfb480492010-01-13 21:46:36 +00002337 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2338 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002339
Douglas Gregordb1314e2010-10-01 21:11:22 +00002340 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2341 return PE->getProtocol();
2342
Ted Kremenekfb480492010-01-13 21:46:36 +00002343 return 0;
2344}
2345
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002346static SourceLocation getLocationFromExpr(Expr *E) {
2347 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2348 return /*FIXME:*/Msg->getLeftLoc();
2349 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2350 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002351 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2352 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002353 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2354 return Member->getMemberLoc();
2355 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2356 return Ivar->getLocation();
2357 return E->getLocStart();
2358}
2359
Ted Kremenekfb480492010-01-13 21:46:36 +00002360extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002361
2362unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002363 CXCursorVisitor visitor,
2364 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002365 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002366
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002367 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2368 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002369 return CursorVis.VisitChildren(parent);
2370}
2371
Douglas Gregor78205d42010-01-20 21:45:58 +00002372static CXString getDeclSpelling(Decl *D) {
2373 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2374 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002375 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002376
Douglas Gregor78205d42010-01-20 21:45:58 +00002377 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002378 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002379
Douglas Gregor78205d42010-01-20 21:45:58 +00002380 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2381 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2382 // and returns different names. NamedDecl returns the class name and
2383 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002384 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002385
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002386 if (isa<UsingDirectiveDecl>(D))
2387 return createCXString("");
2388
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002389 llvm::SmallString<1024> S;
2390 llvm::raw_svector_ostream os(S);
2391 ND->printName(os);
2392
2393 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002394}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002395
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002396CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002397 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002398 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002399
Steve Narofff334b4e2009-09-02 18:26:48 +00002400 if (clang_isReference(C.kind)) {
2401 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002402 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002403 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002404 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002405 }
2406 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002407 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002408 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002409 }
2410 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002411 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002412 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002413 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002414 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002415 case CXCursor_CXXBaseSpecifier: {
2416 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2417 return createCXString(B->getType().getAsString());
2418 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002419 case CXCursor_TypeRef: {
2420 TypeDecl *Type = getCursorTypeRef(C).first;
2421 assert(Type && "Missing type decl");
2422
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002423 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2424 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002425 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002426 case CXCursor_TemplateRef: {
2427 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002428 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002429
2430 return createCXString(Template->getNameAsString());
2431 }
Douglas Gregor69319002010-08-31 23:48:11 +00002432
2433 case CXCursor_NamespaceRef: {
2434 NamedDecl *NS = getCursorNamespaceRef(C).first;
2435 assert(NS && "Missing namespace decl");
2436
2437 return createCXString(NS->getNameAsString());
2438 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002439
Douglas Gregora67e03f2010-09-09 21:42:20 +00002440 case CXCursor_MemberRef: {
2441 FieldDecl *Field = getCursorMemberRef(C).first;
2442 assert(Field && "Missing member decl");
2443
2444 return createCXString(Field->getNameAsString());
2445 }
2446
Douglas Gregor36897b02010-09-10 00:22:18 +00002447 case CXCursor_LabelRef: {
2448 LabelStmt *Label = getCursorLabelRef(C).first;
2449 assert(Label && "Missing label");
2450
2451 return createCXString(Label->getID()->getName());
2452 }
2453
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002454 case CXCursor_OverloadedDeclRef: {
2455 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2456 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2457 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2458 return createCXString(ND->getNameAsString());
2459 return createCXString("");
2460 }
2461 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2462 return createCXString(E->getName().getAsString());
2463 OverloadedTemplateStorage *Ovl
2464 = Storage.get<OverloadedTemplateStorage*>();
2465 if (Ovl->size() == 0)
2466 return createCXString("");
2467 return createCXString((*Ovl->begin())->getNameAsString());
2468 }
2469
Daniel Dunbaracca7252009-11-30 20:42:49 +00002470 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002471 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002472 }
2473 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002474
2475 if (clang_isExpression(C.kind)) {
2476 Decl *D = getDeclFromExpr(getCursorExpr(C));
2477 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002478 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002479 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002480 }
2481
Douglas Gregor36897b02010-09-10 00:22:18 +00002482 if (clang_isStatement(C.kind)) {
2483 Stmt *S = getCursorStmt(C);
2484 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2485 return createCXString(Label->getID()->getName());
2486
2487 return createCXString("");
2488 }
2489
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002490 if (C.kind == CXCursor_MacroInstantiation)
2491 return createCXString(getCursorMacroInstantiation(C)->getName()
2492 ->getNameStart());
2493
Douglas Gregor572feb22010-03-18 18:04:21 +00002494 if (C.kind == CXCursor_MacroDefinition)
2495 return createCXString(getCursorMacroDefinition(C)->getName()
2496 ->getNameStart());
2497
Douglas Gregorecdcb882010-10-20 22:00:55 +00002498 if (C.kind == CXCursor_InclusionDirective)
2499 return createCXString(getCursorInclusionDirective(C)->getFileName());
2500
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002501 if (clang_isDeclaration(C.kind))
2502 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002503
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002504 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002505}
2506
Douglas Gregor358559d2010-10-02 22:49:11 +00002507CXString clang_getCursorDisplayName(CXCursor C) {
2508 if (!clang_isDeclaration(C.kind))
2509 return clang_getCursorSpelling(C);
2510
2511 Decl *D = getCursorDecl(C);
2512 if (!D)
2513 return createCXString("");
2514
2515 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2516 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2517 D = FunTmpl->getTemplatedDecl();
2518
2519 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2520 llvm::SmallString<64> Str;
2521 llvm::raw_svector_ostream OS(Str);
2522 OS << Function->getNameAsString();
2523 if (Function->getPrimaryTemplate())
2524 OS << "<>";
2525 OS << "(";
2526 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2527 if (I)
2528 OS << ", ";
2529 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2530 }
2531
2532 if (Function->isVariadic()) {
2533 if (Function->getNumParams())
2534 OS << ", ";
2535 OS << "...";
2536 }
2537 OS << ")";
2538 return createCXString(OS.str());
2539 }
2540
2541 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2542 llvm::SmallString<64> Str;
2543 llvm::raw_svector_ostream OS(Str);
2544 OS << ClassTemplate->getNameAsString();
2545 OS << "<";
2546 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2547 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2548 if (I)
2549 OS << ", ";
2550
2551 NamedDecl *Param = Params->getParam(I);
2552 if (Param->getIdentifier()) {
2553 OS << Param->getIdentifier()->getName();
2554 continue;
2555 }
2556
2557 // There is no parameter name, which makes this tricky. Try to come up
2558 // with something useful that isn't too long.
2559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2560 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2561 else if (NonTypeTemplateParmDecl *NTTP
2562 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2563 OS << NTTP->getType().getAsString(Policy);
2564 else
2565 OS << "template<...> class";
2566 }
2567
2568 OS << ">";
2569 return createCXString(OS.str());
2570 }
2571
2572 if (ClassTemplateSpecializationDecl *ClassSpec
2573 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2574 // If the type was explicitly written, use that.
2575 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2576 return createCXString(TSInfo->getType().getAsString(Policy));
2577
2578 llvm::SmallString<64> Str;
2579 llvm::raw_svector_ostream OS(Str);
2580 OS << ClassSpec->getNameAsString();
2581 OS << TemplateSpecializationType::PrintTemplateArgumentList(
2582 ClassSpec->getTemplateArgs().getFlatArgumentList(),
2583 ClassSpec->getTemplateArgs().flat_size(),
2584 Policy);
2585 return createCXString(OS.str());
2586 }
2587
2588 return clang_getCursorSpelling(C);
2589}
2590
Ted Kremeneke68fff62010-02-17 00:41:32 +00002591CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002592 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002593 case CXCursor_FunctionDecl:
2594 return createCXString("FunctionDecl");
2595 case CXCursor_TypedefDecl:
2596 return createCXString("TypedefDecl");
2597 case CXCursor_EnumDecl:
2598 return createCXString("EnumDecl");
2599 case CXCursor_EnumConstantDecl:
2600 return createCXString("EnumConstantDecl");
2601 case CXCursor_StructDecl:
2602 return createCXString("StructDecl");
2603 case CXCursor_UnionDecl:
2604 return createCXString("UnionDecl");
2605 case CXCursor_ClassDecl:
2606 return createCXString("ClassDecl");
2607 case CXCursor_FieldDecl:
2608 return createCXString("FieldDecl");
2609 case CXCursor_VarDecl:
2610 return createCXString("VarDecl");
2611 case CXCursor_ParmDecl:
2612 return createCXString("ParmDecl");
2613 case CXCursor_ObjCInterfaceDecl:
2614 return createCXString("ObjCInterfaceDecl");
2615 case CXCursor_ObjCCategoryDecl:
2616 return createCXString("ObjCCategoryDecl");
2617 case CXCursor_ObjCProtocolDecl:
2618 return createCXString("ObjCProtocolDecl");
2619 case CXCursor_ObjCPropertyDecl:
2620 return createCXString("ObjCPropertyDecl");
2621 case CXCursor_ObjCIvarDecl:
2622 return createCXString("ObjCIvarDecl");
2623 case CXCursor_ObjCInstanceMethodDecl:
2624 return createCXString("ObjCInstanceMethodDecl");
2625 case CXCursor_ObjCClassMethodDecl:
2626 return createCXString("ObjCClassMethodDecl");
2627 case CXCursor_ObjCImplementationDecl:
2628 return createCXString("ObjCImplementationDecl");
2629 case CXCursor_ObjCCategoryImplDecl:
2630 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002631 case CXCursor_CXXMethod:
2632 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002633 case CXCursor_UnexposedDecl:
2634 return createCXString("UnexposedDecl");
2635 case CXCursor_ObjCSuperClassRef:
2636 return createCXString("ObjCSuperClassRef");
2637 case CXCursor_ObjCProtocolRef:
2638 return createCXString("ObjCProtocolRef");
2639 case CXCursor_ObjCClassRef:
2640 return createCXString("ObjCClassRef");
2641 case CXCursor_TypeRef:
2642 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002643 case CXCursor_TemplateRef:
2644 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002645 case CXCursor_NamespaceRef:
2646 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002647 case CXCursor_MemberRef:
2648 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002649 case CXCursor_LabelRef:
2650 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002651 case CXCursor_OverloadedDeclRef:
2652 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002653 case CXCursor_UnexposedExpr:
2654 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002655 case CXCursor_BlockExpr:
2656 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002657 case CXCursor_DeclRefExpr:
2658 return createCXString("DeclRefExpr");
2659 case CXCursor_MemberRefExpr:
2660 return createCXString("MemberRefExpr");
2661 case CXCursor_CallExpr:
2662 return createCXString("CallExpr");
2663 case CXCursor_ObjCMessageExpr:
2664 return createCXString("ObjCMessageExpr");
2665 case CXCursor_UnexposedStmt:
2666 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002667 case CXCursor_LabelStmt:
2668 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002669 case CXCursor_InvalidFile:
2670 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002671 case CXCursor_InvalidCode:
2672 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002673 case CXCursor_NoDeclFound:
2674 return createCXString("NoDeclFound");
2675 case CXCursor_NotImplemented:
2676 return createCXString("NotImplemented");
2677 case CXCursor_TranslationUnit:
2678 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002679 case CXCursor_UnexposedAttr:
2680 return createCXString("UnexposedAttr");
2681 case CXCursor_IBActionAttr:
2682 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002683 case CXCursor_IBOutletAttr:
2684 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002685 case CXCursor_IBOutletCollectionAttr:
2686 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002687 case CXCursor_PreprocessingDirective:
2688 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002689 case CXCursor_MacroDefinition:
2690 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002691 case CXCursor_MacroInstantiation:
2692 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002693 case CXCursor_InclusionDirective:
2694 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002695 case CXCursor_Namespace:
2696 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002697 case CXCursor_LinkageSpec:
2698 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002699 case CXCursor_CXXBaseSpecifier:
2700 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002701 case CXCursor_Constructor:
2702 return createCXString("CXXConstructor");
2703 case CXCursor_Destructor:
2704 return createCXString("CXXDestructor");
2705 case CXCursor_ConversionFunction:
2706 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002707 case CXCursor_TemplateTypeParameter:
2708 return createCXString("TemplateTypeParameter");
2709 case CXCursor_NonTypeTemplateParameter:
2710 return createCXString("NonTypeTemplateParameter");
2711 case CXCursor_TemplateTemplateParameter:
2712 return createCXString("TemplateTemplateParameter");
2713 case CXCursor_FunctionTemplate:
2714 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002715 case CXCursor_ClassTemplate:
2716 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002717 case CXCursor_ClassTemplatePartialSpecialization:
2718 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002719 case CXCursor_NamespaceAlias:
2720 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002721 case CXCursor_UsingDirective:
2722 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002723 case CXCursor_UsingDeclaration:
2724 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002725 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002726
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002727 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002728 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002729}
Steve Naroff89922f82009-08-31 00:59:03 +00002730
Ted Kremeneke68fff62010-02-17 00:41:32 +00002731enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2732 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002733 CXClientData client_data) {
2734 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2735 *BestCursor = cursor;
2736 return CXChildVisit_Recurse;
2737}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002738
Douglas Gregorb9790342010-01-22 21:44:22 +00002739CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2740 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002741 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002742
Douglas Gregorb9790342010-01-22 21:44:22 +00002743 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002744 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2745
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002746 // Translate the given source location to make it point at the beginning of
2747 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002748 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002749
2750 // Guard against an invalid SourceLocation, or we may assert in one
2751 // of the following calls.
2752 if (SLoc.isInvalid())
2753 return clang_getNullCursor();
2754
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002755 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2756 CXXUnit->getASTContext().getLangOptions());
2757
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002758 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2759 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002760 // FIXME: Would be great to have a "hint" cursor, then walk from that
2761 // hint cursor upward until we find a cursor whose source range encloses
2762 // the region of interest, rather than starting from the translation unit.
2763 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002764 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002765 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002766 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002767 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002768 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002769}
2770
Ted Kremenek73885552009-11-17 19:28:59 +00002771CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002772 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002773}
2774
2775unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002776 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002777}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002778
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002779unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002780 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2781}
2782
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002783unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002784 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2785}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002786
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002787unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002788 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2789}
2790
Douglas Gregor97b98722010-01-19 23:20:36 +00002791unsigned clang_isExpression(enum CXCursorKind K) {
2792 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2793}
2794
2795unsigned clang_isStatement(enum CXCursorKind K) {
2796 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2797}
2798
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002799unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2800 return K == CXCursor_TranslationUnit;
2801}
2802
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002803unsigned clang_isPreprocessing(enum CXCursorKind K) {
2804 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2805}
2806
Ted Kremenekad6eff62010-03-08 21:17:29 +00002807unsigned clang_isUnexposed(enum CXCursorKind K) {
2808 switch (K) {
2809 case CXCursor_UnexposedDecl:
2810 case CXCursor_UnexposedExpr:
2811 case CXCursor_UnexposedStmt:
2812 case CXCursor_UnexposedAttr:
2813 return true;
2814 default:
2815 return false;
2816 }
2817}
2818
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002819CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002820 return C.kind;
2821}
2822
Douglas Gregor98258af2010-01-18 22:46:11 +00002823CXSourceLocation clang_getCursorLocation(CXCursor C) {
2824 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002825 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002826 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002827 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2828 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002829 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002830 }
2831
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002832 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002833 std::pair<ObjCProtocolDecl *, SourceLocation> P
2834 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002835 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002836 }
2837
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002838 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002839 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2840 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002841 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002842 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002843
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002844 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002845 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002846 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002847 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002848
2849 case CXCursor_TemplateRef: {
2850 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2851 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2852 }
2853
Douglas Gregor69319002010-08-31 23:48:11 +00002854 case CXCursor_NamespaceRef: {
2855 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2856 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2857 }
2858
Douglas Gregora67e03f2010-09-09 21:42:20 +00002859 case CXCursor_MemberRef: {
2860 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2861 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2862 }
2863
Ted Kremenek3064ef92010-08-27 21:34:58 +00002864 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00002865 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
2866 if (!BaseSpec)
2867 return clang_getNullLocation();
2868
2869 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
2870 return cxloc::translateSourceLocation(getCursorContext(C),
2871 TSInfo->getTypeLoc().getBeginLoc());
2872
2873 return cxloc::translateSourceLocation(getCursorContext(C),
2874 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00002875 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002876
Douglas Gregor36897b02010-09-10 00:22:18 +00002877 case CXCursor_LabelRef: {
2878 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
2879 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
2880 }
2881
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002882 case CXCursor_OverloadedDeclRef:
2883 return cxloc::translateSourceLocation(getCursorContext(C),
2884 getCursorOverloadedDeclRef(C).second);
2885
Douglas Gregorf46034a2010-01-18 23:41:10 +00002886 default:
2887 // FIXME: Need a way to enumerate all non-reference cases.
2888 llvm_unreachable("Missed a reference kind");
2889 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002890 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002891
2892 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002893 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002894 getLocationFromExpr(getCursorExpr(C)));
2895
Douglas Gregor36897b02010-09-10 00:22:18 +00002896 if (clang_isStatement(C.kind))
2897 return cxloc::translateSourceLocation(getCursorContext(C),
2898 getCursorStmt(C)->getLocStart());
2899
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002900 if (C.kind == CXCursor_PreprocessingDirective) {
2901 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2902 return cxloc::translateSourceLocation(getCursorContext(C), L);
2903 }
Douglas Gregor48072312010-03-18 15:23:44 +00002904
2905 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002906 SourceLocation L
2907 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002908 return cxloc::translateSourceLocation(getCursorContext(C), L);
2909 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002910
2911 if (C.kind == CXCursor_MacroDefinition) {
2912 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2913 return cxloc::translateSourceLocation(getCursorContext(C), L);
2914 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00002915
2916 if (C.kind == CXCursor_InclusionDirective) {
2917 SourceLocation L
2918 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
2919 return cxloc::translateSourceLocation(getCursorContext(C), L);
2920 }
2921
Ted Kremenek9a700d22010-05-12 06:16:13 +00002922 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002923 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002924
Douglas Gregorf46034a2010-01-18 23:41:10 +00002925 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002926 SourceLocation Loc = D->getLocation();
2927 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2928 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002929 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002930}
Douglas Gregora7bde202010-01-19 00:34:46 +00002931
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002932} // end extern "C"
2933
2934static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002935 if (clang_isReference(C.kind)) {
2936 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002937 case CXCursor_ObjCSuperClassRef:
2938 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002939
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002940 case CXCursor_ObjCProtocolRef:
2941 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002942
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002943 case CXCursor_ObjCClassRef:
2944 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002945
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002946 case CXCursor_TypeRef:
2947 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002948
2949 case CXCursor_TemplateRef:
2950 return getCursorTemplateRef(C).second;
2951
Douglas Gregor69319002010-08-31 23:48:11 +00002952 case CXCursor_NamespaceRef:
2953 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00002954
2955 case CXCursor_MemberRef:
2956 return getCursorMemberRef(C).second;
2957
Ted Kremenek3064ef92010-08-27 21:34:58 +00002958 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00002959 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002960
Douglas Gregor36897b02010-09-10 00:22:18 +00002961 case CXCursor_LabelRef:
2962 return getCursorLabelRef(C).second;
2963
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002964 case CXCursor_OverloadedDeclRef:
2965 return getCursorOverloadedDeclRef(C).second;
2966
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002967 default:
2968 // FIXME: Need a way to enumerate all non-reference cases.
2969 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002970 }
2971 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002972
2973 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002974 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002975
2976 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002977 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002978
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002979 if (C.kind == CXCursor_PreprocessingDirective)
2980 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002981
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002982 if (C.kind == CXCursor_MacroInstantiation)
2983 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002984
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002985 if (C.kind == CXCursor_MacroDefinition)
2986 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00002987
2988 if (C.kind == CXCursor_InclusionDirective)
2989 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
2990
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002991 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2992 return getCursorDecl(C)->getSourceRange();
2993
Douglas Gregorecdcb882010-10-20 22:00:55 +00002994 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002995
2996extern "C" {
2997
2998CXSourceRange clang_getCursorExtent(CXCursor C) {
2999 SourceRange R = getRawCursorExtent(C);
3000 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003001 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003002
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003003 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003004}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003005
3006CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003007 if (clang_isInvalid(C.kind))
3008 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003009
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003010 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003011 if (clang_isDeclaration(C.kind)) {
3012 Decl *D = getCursorDecl(C);
3013 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3014 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3015 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3016 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3017 if (ObjCForwardProtocolDecl *Protocols
3018 = dyn_cast<ObjCForwardProtocolDecl>(D))
3019 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3020
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003021 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003022 }
3023
Douglas Gregor97b98722010-01-19 23:20:36 +00003024 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003025 Expr *E = getCursorExpr(C);
3026 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003027 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003028 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003029
3030 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3031 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3032
Douglas Gregor97b98722010-01-19 23:20:36 +00003033 return clang_getNullCursor();
3034 }
3035
Douglas Gregor36897b02010-09-10 00:22:18 +00003036 if (clang_isStatement(C.kind)) {
3037 Stmt *S = getCursorStmt(C);
3038 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3039 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3040 getCursorASTUnit(C));
3041
3042 return clang_getNullCursor();
3043 }
3044
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003045 if (C.kind == CXCursor_MacroInstantiation) {
3046 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3047 return MakeMacroDefinitionCursor(Def, CXXUnit);
3048 }
3049
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003050 if (!clang_isReference(C.kind))
3051 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003052
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003053 switch (C.kind) {
3054 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003055 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003056
3057 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003058 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003059
3060 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003061 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003062
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003063 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003064 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003065
3066 case CXCursor_TemplateRef:
3067 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3068
Douglas Gregor69319002010-08-31 23:48:11 +00003069 case CXCursor_NamespaceRef:
3070 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3071
Douglas Gregora67e03f2010-09-09 21:42:20 +00003072 case CXCursor_MemberRef:
3073 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3074
Ted Kremenek3064ef92010-08-27 21:34:58 +00003075 case CXCursor_CXXBaseSpecifier: {
3076 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3077 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3078 CXXUnit));
3079 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003080
Douglas Gregor36897b02010-09-10 00:22:18 +00003081 case CXCursor_LabelRef:
3082 // FIXME: We end up faking the "parent" declaration here because we
3083 // don't want to make CXCursor larger.
3084 return MakeCXCursor(getCursorLabelRef(C).first,
3085 CXXUnit->getASTContext().getTranslationUnitDecl(),
3086 CXXUnit);
3087
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003088 case CXCursor_OverloadedDeclRef:
3089 return C;
3090
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003091 default:
3092 // We would prefer to enumerate all non-reference cursor kinds here.
3093 llvm_unreachable("Unhandled reference cursor kind");
3094 break;
3095 }
3096 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003097
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003098 return clang_getNullCursor();
3099}
3100
Douglas Gregorb6998662010-01-19 19:34:47 +00003101CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003102 if (clang_isInvalid(C.kind))
3103 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003104
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003105 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003106
Douglas Gregorb6998662010-01-19 19:34:47 +00003107 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003108 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003109 C = clang_getCursorReferenced(C);
3110 WasReference = true;
3111 }
3112
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003113 if (C.kind == CXCursor_MacroInstantiation)
3114 return clang_getCursorReferenced(C);
3115
Douglas Gregorb6998662010-01-19 19:34:47 +00003116 if (!clang_isDeclaration(C.kind))
3117 return clang_getNullCursor();
3118
3119 Decl *D = getCursorDecl(C);
3120 if (!D)
3121 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003122
Douglas Gregorb6998662010-01-19 19:34:47 +00003123 switch (D->getKind()) {
3124 // Declaration kinds that don't really separate the notions of
3125 // declaration and definition.
3126 case Decl::Namespace:
3127 case Decl::Typedef:
3128 case Decl::TemplateTypeParm:
3129 case Decl::EnumConstant:
3130 case Decl::Field:
3131 case Decl::ObjCIvar:
3132 case Decl::ObjCAtDefsField:
3133 case Decl::ImplicitParam:
3134 case Decl::ParmVar:
3135 case Decl::NonTypeTemplateParm:
3136 case Decl::TemplateTemplateParm:
3137 case Decl::ObjCCategoryImpl:
3138 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003139 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003140 case Decl::LinkageSpec:
3141 case Decl::ObjCPropertyImpl:
3142 case Decl::FileScopeAsm:
3143 case Decl::StaticAssert:
3144 case Decl::Block:
3145 return C;
3146
3147 // Declaration kinds that don't make any sense here, but are
3148 // nonetheless harmless.
3149 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003150 break;
3151
3152 // Declaration kinds for which the definition is not resolvable.
3153 case Decl::UnresolvedUsingTypename:
3154 case Decl::UnresolvedUsingValue:
3155 break;
3156
3157 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003158 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3159 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003160
3161 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003162 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003163
3164 case Decl::Enum:
3165 case Decl::Record:
3166 case Decl::CXXRecord:
3167 case Decl::ClassTemplateSpecialization:
3168 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003169 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003170 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003171 return clang_getNullCursor();
3172
3173 case Decl::Function:
3174 case Decl::CXXMethod:
3175 case Decl::CXXConstructor:
3176 case Decl::CXXDestructor:
3177 case Decl::CXXConversion: {
3178 const FunctionDecl *Def = 0;
3179 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003180 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003181 return clang_getNullCursor();
3182 }
3183
3184 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003185 // Ask the variable if it has a definition.
3186 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3187 return MakeCXCursor(Def, CXXUnit);
3188 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003189 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003190
Douglas Gregorb6998662010-01-19 19:34:47 +00003191 case Decl::FunctionTemplate: {
3192 const FunctionDecl *Def = 0;
3193 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003194 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003195 return clang_getNullCursor();
3196 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003197
Douglas Gregorb6998662010-01-19 19:34:47 +00003198 case Decl::ClassTemplate: {
3199 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003200 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003201 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003202 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003203 return clang_getNullCursor();
3204 }
3205
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003206 case Decl::Using:
3207 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3208 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003209
3210 case Decl::UsingShadow:
3211 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003212 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003213 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003214
3215 case Decl::ObjCMethod: {
3216 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3217 if (Method->isThisDeclarationADefinition())
3218 return C;
3219
3220 // Dig out the method definition in the associated
3221 // @implementation, if we have it.
3222 // FIXME: The ASTs should make finding the definition easier.
3223 if (ObjCInterfaceDecl *Class
3224 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3225 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3226 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3227 Method->isInstanceMethod()))
3228 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003229 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003230
3231 return clang_getNullCursor();
3232 }
3233
3234 case Decl::ObjCCategory:
3235 if (ObjCCategoryImplDecl *Impl
3236 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003237 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003238 return clang_getNullCursor();
3239
3240 case Decl::ObjCProtocol:
3241 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3242 return C;
3243 return clang_getNullCursor();
3244
3245 case Decl::ObjCInterface:
3246 // There are two notions of a "definition" for an Objective-C
3247 // class: the interface and its implementation. When we resolved a
3248 // reference to an Objective-C class, produce the @interface as
3249 // the definition; when we were provided with the interface,
3250 // produce the @implementation as the definition.
3251 if (WasReference) {
3252 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3253 return C;
3254 } else if (ObjCImplementationDecl *Impl
3255 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003256 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003257 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003258
Douglas Gregorb6998662010-01-19 19:34:47 +00003259 case Decl::ObjCProperty:
3260 // FIXME: We don't really know where to find the
3261 // ObjCPropertyImplDecls that implement this property.
3262 return clang_getNullCursor();
3263
3264 case Decl::ObjCCompatibleAlias:
3265 if (ObjCInterfaceDecl *Class
3266 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3267 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003268 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003269
Douglas Gregorb6998662010-01-19 19:34:47 +00003270 return clang_getNullCursor();
3271
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003272 case Decl::ObjCForwardProtocol:
3273 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3274 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003275
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003276 case Decl::ObjCClass:
3277 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3278 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003279
3280 case Decl::Friend:
3281 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003282 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003283 return clang_getNullCursor();
3284
3285 case Decl::FriendTemplate:
3286 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003287 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003288 return clang_getNullCursor();
3289 }
3290
3291 return clang_getNullCursor();
3292}
3293
3294unsigned clang_isCursorDefinition(CXCursor C) {
3295 if (!clang_isDeclaration(C.kind))
3296 return 0;
3297
3298 return clang_getCursorDefinition(C) == C;
3299}
3300
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003301unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003302 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003303 return 0;
3304
3305 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3306 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3307 return E->getNumDecls();
3308
3309 if (OverloadedTemplateStorage *S
3310 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3311 return S->size();
3312
3313 Decl *D = Storage.get<Decl*>();
3314 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3315 return Using->getNumShadowDecls();
3316 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3317 return Classes->size();
3318 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3319 return Protocols->protocol_size();
3320
3321 return 0;
3322}
3323
3324CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003325 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003326 return clang_getNullCursor();
3327
3328 if (index >= clang_getNumOverloadedDecls(cursor))
3329 return clang_getNullCursor();
3330
3331 ASTUnit *Unit = getCursorASTUnit(cursor);
3332 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3333 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3334 return MakeCXCursor(E->decls_begin()[index], Unit);
3335
3336 if (OverloadedTemplateStorage *S
3337 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3338 return MakeCXCursor(S->begin()[index], Unit);
3339
3340 Decl *D = Storage.get<Decl*>();
3341 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3342 // FIXME: This is, unfortunately, linear time.
3343 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3344 std::advance(Pos, index);
3345 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3346 }
3347
3348 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3349 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3350
3351 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3352 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3353
3354 return clang_getNullCursor();
3355}
3356
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003357void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003358 const char **startBuf,
3359 const char **endBuf,
3360 unsigned *startLine,
3361 unsigned *startColumn,
3362 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003363 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003364 assert(getCursorDecl(C) && "CXCursor has null decl");
3365 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003366 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3367 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003368
Steve Naroff4ade6d62009-09-23 17:52:52 +00003369 SourceManager &SM = FD->getASTContext().getSourceManager();
3370 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3371 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3372 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3373 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3374 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3375 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3376}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003377
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003378void clang_enableStackTraces(void) {
3379 llvm::sys::PrintStackTraceOnErrorSignal();
3380}
3381
Ted Kremenekfb480492010-01-13 21:46:36 +00003382} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003383
Ted Kremenekfb480492010-01-13 21:46:36 +00003384//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003385// Token-based Operations.
3386//===----------------------------------------------------------------------===//
3387
3388/* CXToken layout:
3389 * int_data[0]: a CXTokenKind
3390 * int_data[1]: starting token location
3391 * int_data[2]: token length
3392 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003393 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003394 * otherwise unused.
3395 */
3396extern "C" {
3397
3398CXTokenKind clang_getTokenKind(CXToken CXTok) {
3399 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3400}
3401
3402CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3403 switch (clang_getTokenKind(CXTok)) {
3404 case CXToken_Identifier:
3405 case CXToken_Keyword:
3406 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003407 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3408 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003409
3410 case CXToken_Literal: {
3411 // We have stashed the starting pointer in the ptr_data field. Use it.
3412 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003413 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003414 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003415
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003416 case CXToken_Punctuation:
3417 case CXToken_Comment:
3418 break;
3419 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003420
3421 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003422 // deconstructing the source location.
3423 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3424 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003425 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003426
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003427 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3428 std::pair<FileID, unsigned> LocInfo
3429 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003430 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003431 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003432 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3433 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003434 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003435
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003436 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003437}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003439CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3440 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3441 if (!CXXUnit)
3442 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003443
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003444 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3445 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3446}
3447
3448CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3449 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003450 if (!CXXUnit)
3451 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003452
3453 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003454 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3455}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003457void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3458 CXToken **Tokens, unsigned *NumTokens) {
3459 if (Tokens)
3460 *Tokens = 0;
3461 if (NumTokens)
3462 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003463
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003464 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3465 if (!CXXUnit || !Tokens || !NumTokens)
3466 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003467
Douglas Gregorbdf60622010-03-05 21:16:25 +00003468 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3469
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003470 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003471 if (R.isInvalid())
3472 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003473
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003474 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3475 std::pair<FileID, unsigned> BeginLocInfo
3476 = SourceMgr.getDecomposedLoc(R.getBegin());
3477 std::pair<FileID, unsigned> EndLocInfo
3478 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003479
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003480 // Cannot tokenize across files.
3481 if (BeginLocInfo.first != EndLocInfo.first)
3482 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003483
3484 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003485 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003486 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003487 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003488 if (Invalid)
3489 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003490
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003491 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3492 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003493 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003494 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003495
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003496 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003497 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003498 llvm::SmallVector<CXToken, 32> CXTokens;
3499 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003500 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003501 do {
3502 // Lex the next token
3503 Lex.LexFromRawLexer(Tok);
3504 if (Tok.is(tok::eof))
3505 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003506
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003507 // Initialize the CXToken.
3508 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003509
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003510 // - Common fields
3511 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3512 CXTok.int_data[2] = Tok.getLength();
3513 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003514
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003515 // - Kind-specific fields
3516 if (Tok.isLiteral()) {
3517 CXTok.int_data[0] = CXToken_Literal;
3518 CXTok.ptr_data = (void *)Tok.getLiteralData();
3519 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003520 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003521 std::pair<FileID, unsigned> LocInfo
3522 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003523 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003524 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003525 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3526 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003527 return;
3528
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003529 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003530 IdentifierInfo *II
3531 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003532
David Chisnall096428b2010-10-13 21:44:48 +00003533 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003534 CXTok.int_data[0] = CXToken_Keyword;
3535 }
3536 else {
3537 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3538 CXToken_Identifier
3539 : CXToken_Keyword;
3540 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003541 CXTok.ptr_data = II;
3542 } else if (Tok.is(tok::comment)) {
3543 CXTok.int_data[0] = CXToken_Comment;
3544 CXTok.ptr_data = 0;
3545 } else {
3546 CXTok.int_data[0] = CXToken_Punctuation;
3547 CXTok.ptr_data = 0;
3548 }
3549 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003550 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003551 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003552
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003553 if (CXTokens.empty())
3554 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003555
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003556 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3557 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3558 *NumTokens = CXTokens.size();
3559}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003560
Ted Kremenek6db61092010-05-05 00:55:15 +00003561void clang_disposeTokens(CXTranslationUnit TU,
3562 CXToken *Tokens, unsigned NumTokens) {
3563 free(Tokens);
3564}
3565
3566} // end: extern "C"
3567
3568//===----------------------------------------------------------------------===//
3569// Token annotation APIs.
3570//===----------------------------------------------------------------------===//
3571
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003572typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003573static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3574 CXCursor parent,
3575 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003576namespace {
3577class AnnotateTokensWorker {
3578 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003579 CXToken *Tokens;
3580 CXCursor *Cursors;
3581 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003582 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003583 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003584 CursorVisitor AnnotateVis;
3585 SourceManager &SrcMgr;
3586
3587 bool MoreTokens() const { return TokIdx < NumTokens; }
3588 unsigned NextToken() const { return TokIdx; }
3589 void AdvanceToken() { ++TokIdx; }
3590 SourceLocation GetTokenLoc(unsigned tokI) {
3591 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3592 }
3593
Ted Kremenek6db61092010-05-05 00:55:15 +00003594public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003595 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003596 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3597 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003598 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003599 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003600 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3601 Decl::MaxPCHLevel, RegionOfInterest),
3602 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003603
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003604 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003605 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003606 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003607};
3608}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003609
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003610void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3611 // Walk the AST within the region of interest, annotating tokens
3612 // along the way.
3613 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003614
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003615 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3616 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003617 if (Pos != Annotated.end() &&
3618 (clang_isInvalid(Cursors[I].kind) ||
3619 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003620 Cursors[I] = Pos->second;
3621 }
3622
3623 // Finish up annotating any tokens left.
3624 if (!MoreTokens())
3625 return;
3626
3627 const CXCursor &C = clang_getNullCursor();
3628 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3629 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3630 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003631 }
3632}
3633
Ted Kremenek6db61092010-05-05 00:55:15 +00003634enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003635AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003636 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003637 SourceRange cursorRange = getRawCursorExtent(cursor);
3638
3639 if (clang_isPreprocessing(cursor.kind)) {
3640 // For macro instantiations, just note where the beginning of the macro
3641 // instantiation occurs.
3642 if (cursor.kind == CXCursor_MacroInstantiation) {
3643 Annotated[Loc.int_data] = cursor;
3644 return CXChildVisit_Recurse;
3645 }
3646
3647 if (cursorRange.isInvalid())
3648 return CXChildVisit_Continue;
3649
3650 // Items in the preprocessing record are kept separate from items in
3651 // declarations, so we keep a separate token index.
3652 unsigned SavedTokIdx = TokIdx;
3653 TokIdx = PreprocessingTokIdx;
3654
3655 // Skip tokens up until we catch up to the beginning of the preprocessing
3656 // entry.
3657 while (MoreTokens()) {
3658 const unsigned I = NextToken();
3659 SourceLocation TokLoc = GetTokenLoc(I);
3660 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3661 case RangeBefore:
3662 AdvanceToken();
3663 continue;
3664 case RangeAfter:
3665 case RangeOverlap:
3666 break;
3667 }
3668 break;
3669 }
3670
3671 // Look at all of the tokens within this range.
3672 while (MoreTokens()) {
3673 const unsigned I = NextToken();
3674 SourceLocation TokLoc = GetTokenLoc(I);
3675 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3676 case RangeBefore:
3677 assert(0 && "Infeasible");
3678 case RangeAfter:
3679 break;
3680 case RangeOverlap:
3681 Cursors[I] = cursor;
3682 AdvanceToken();
3683 continue;
3684 }
3685 break;
3686 }
3687
3688 // Save the preprocessing token index; restore the non-preprocessing
3689 // token index.
3690 PreprocessingTokIdx = TokIdx;
3691 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003692 return CXChildVisit_Recurse;
3693 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003694
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003695 if (cursorRange.isInvalid())
3696 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003697
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003698 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3699
Ted Kremeneka333c662010-05-12 05:29:33 +00003700 // Adjust the annotated range based specific declarations.
3701 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3702 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003703 Decl *D = cxcursor::getCursorDecl(cursor);
3704 // Don't visit synthesized ObjC methods, since they have no syntatic
3705 // representation in the source.
3706 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3707 if (MD->isSynthesized())
3708 return CXChildVisit_Continue;
3709 }
3710 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003711 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3712 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003713 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003714 if (TLoc.isValid() &&
3715 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003716 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003717 }
3718 }
3719 }
3720
Ted Kremenek3f404602010-08-14 01:14:06 +00003721 // If the location of the cursor occurs within a macro instantiation, record
3722 // the spelling location of the cursor in our annotation map. We can then
3723 // paper over the token labelings during a post-processing step to try and
3724 // get cursor mappings for tokens that are the *arguments* of a macro
3725 // instantiation.
3726 if (L.isMacroID()) {
3727 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3728 // Only invalidate the old annotation if it isn't part of a preprocessing
3729 // directive. Here we assume that the default construction of CXCursor
3730 // results in CXCursor.kind being an initialized value (i.e., 0). If
3731 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00003732
Ted Kremenek3f404602010-08-14 01:14:06 +00003733 CXCursor &oldC = Annotated[rawEncoding];
3734 if (!clang_isPreprocessing(oldC.kind))
3735 oldC = cursor;
3736 }
3737
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003738 const enum CXCursorKind K = clang_getCursorKind(parent);
3739 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003740 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3741 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003742
3743 while (MoreTokens()) {
3744 const unsigned I = NextToken();
3745 SourceLocation TokLoc = GetTokenLoc(I);
3746 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3747 case RangeBefore:
3748 Cursors[I] = updateC;
3749 AdvanceToken();
3750 continue;
3751 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003752 case RangeOverlap:
3753 break;
3754 }
3755 break;
3756 }
3757
3758 // Visit children to get their cursor information.
3759 const unsigned BeforeChildren = NextToken();
3760 VisitChildren(cursor);
3761 const unsigned AfterChildren = NextToken();
3762
3763 // Adjust 'Last' to the last token within the extent of the cursor.
3764 while (MoreTokens()) {
3765 const unsigned I = NextToken();
3766 SourceLocation TokLoc = GetTokenLoc(I);
3767 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3768 case RangeBefore:
3769 assert(0 && "Infeasible");
3770 case RangeAfter:
3771 break;
3772 case RangeOverlap:
3773 Cursors[I] = updateC;
3774 AdvanceToken();
3775 continue;
3776 }
3777 break;
3778 }
3779 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003780
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003781 // Scan the tokens that are at the beginning of the cursor, but are not
3782 // capture by the child cursors.
3783
3784 // For AST elements within macros, rely on a post-annotate pass to
3785 // to correctly annotate the tokens with cursors. Otherwise we can
3786 // get confusing results of having tokens that map to cursors that really
3787 // are expanded by an instantiation.
3788 if (L.isMacroID())
3789 cursor = clang_getNullCursor();
3790
3791 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3792 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3793 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00003794
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003795 Cursors[I] = cursor;
3796 }
3797 // Scan the tokens that are at the end of the cursor, but are not captured
3798 // but the child cursors.
3799 for (unsigned I = AfterChildren; I != Last; ++I)
3800 Cursors[I] = cursor;
3801
3802 TokIdx = Last;
3803 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003804}
3805
Ted Kremenek6db61092010-05-05 00:55:15 +00003806static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3807 CXCursor parent,
3808 CXClientData client_data) {
3809 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3810}
3811
3812extern "C" {
3813
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003814void clang_annotateTokens(CXTranslationUnit TU,
3815 CXToken *Tokens, unsigned NumTokens,
3816 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003817
3818 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003819 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003820
Douglas Gregor4419b672010-10-21 06:10:04 +00003821 // Any token we don't specifically annotate will have a NULL cursor.
3822 CXCursor C = clang_getNullCursor();
3823 for (unsigned I = 0; I != NumTokens; ++I)
3824 Cursors[I] = C;
3825
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003826 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00003827 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003828 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003829
Douglas Gregorbdf60622010-03-05 21:16:25 +00003830 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003831
Douglas Gregor0396f462010-03-19 05:22:59 +00003832 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003833 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003834 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3835 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003836 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3837 clang_getTokenLocation(TU,
3838 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003839
Douglas Gregor0396f462010-03-19 05:22:59 +00003840 // A mapping from the source locations found when re-lexing or traversing the
3841 // region of interest to the corresponding cursors.
3842 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003843
3844 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003845 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003846 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3847 std::pair<FileID, unsigned> BeginLocInfo
3848 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3849 std::pair<FileID, unsigned> EndLocInfo
3850 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003851
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003852 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003853 bool Invalid = false;
3854 if (BeginLocInfo.first == EndLocInfo.first &&
3855 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3856 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003857 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3858 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003859 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003860 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003861 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003862
3863 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003864 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003865 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003866 Token Tok;
3867 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003868
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003869 reprocess:
3870 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3871 // We have found a preprocessing directive. Gobble it up so that we
3872 // don't see it while preprocessing these tokens later, but keep track of
3873 // all of the token locations inside this preprocessing directive so that
3874 // we can annotate them appropriately.
3875 //
3876 // FIXME: Some simple tests here could identify macro definitions and
3877 // #undefs, to provide specific cursor kinds for those.
3878 std::vector<SourceLocation> Locations;
3879 do {
3880 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003881 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003882 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003883
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003884 using namespace cxcursor;
3885 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003886 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3887 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003888 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003889 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3890 Annotated[Locations[I].getRawEncoding()] = Cursor;
3891 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003892
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003893 if (Tok.isAtStartOfLine())
3894 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003895
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003896 continue;
3897 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003898
Douglas Gregor48072312010-03-18 15:23:44 +00003899 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003900 break;
3901 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003902 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003903
Douglas Gregor0396f462010-03-19 05:22:59 +00003904 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003905 // a specific cursor.
3906 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3907 CXXUnit, RegionOfInterest);
3908 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003909}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003910} // end: extern "C"
3911
3912//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003913// Operations for querying linkage of a cursor.
3914//===----------------------------------------------------------------------===//
3915
3916extern "C" {
3917CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003918 if (!clang_isDeclaration(cursor.kind))
3919 return CXLinkage_Invalid;
3920
Ted Kremenek16b42592010-03-03 06:36:57 +00003921 Decl *D = cxcursor::getCursorDecl(cursor);
3922 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3923 switch (ND->getLinkage()) {
3924 case NoLinkage: return CXLinkage_NoLinkage;
3925 case InternalLinkage: return CXLinkage_Internal;
3926 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3927 case ExternalLinkage: return CXLinkage_External;
3928 };
3929
3930 return CXLinkage_Invalid;
3931}
3932} // end: extern "C"
3933
3934//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003935// Operations for querying language of a cursor.
3936//===----------------------------------------------------------------------===//
3937
3938static CXLanguageKind getDeclLanguage(const Decl *D) {
3939 switch (D->getKind()) {
3940 default:
3941 break;
3942 case Decl::ImplicitParam:
3943 case Decl::ObjCAtDefsField:
3944 case Decl::ObjCCategory:
3945 case Decl::ObjCCategoryImpl:
3946 case Decl::ObjCClass:
3947 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003948 case Decl::ObjCForwardProtocol:
3949 case Decl::ObjCImplementation:
3950 case Decl::ObjCInterface:
3951 case Decl::ObjCIvar:
3952 case Decl::ObjCMethod:
3953 case Decl::ObjCProperty:
3954 case Decl::ObjCPropertyImpl:
3955 case Decl::ObjCProtocol:
3956 return CXLanguage_ObjC;
3957 case Decl::CXXConstructor:
3958 case Decl::CXXConversion:
3959 case Decl::CXXDestructor:
3960 case Decl::CXXMethod:
3961 case Decl::CXXRecord:
3962 case Decl::ClassTemplate:
3963 case Decl::ClassTemplatePartialSpecialization:
3964 case Decl::ClassTemplateSpecialization:
3965 case Decl::Friend:
3966 case Decl::FriendTemplate:
3967 case Decl::FunctionTemplate:
3968 case Decl::LinkageSpec:
3969 case Decl::Namespace:
3970 case Decl::NamespaceAlias:
3971 case Decl::NonTypeTemplateParm:
3972 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003973 case Decl::TemplateTemplateParm:
3974 case Decl::TemplateTypeParm:
3975 case Decl::UnresolvedUsingTypename:
3976 case Decl::UnresolvedUsingValue:
3977 case Decl::Using:
3978 case Decl::UsingDirective:
3979 case Decl::UsingShadow:
3980 return CXLanguage_CPlusPlus;
3981 }
3982
3983 return CXLanguage_C;
3984}
3985
3986extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003987
3988enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3989 if (clang_isDeclaration(cursor.kind))
3990 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3991 if (D->hasAttr<UnavailableAttr>() ||
3992 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3993 return CXAvailability_Available;
3994
3995 if (D->hasAttr<DeprecatedAttr>())
3996 return CXAvailability_Deprecated;
3997 }
3998
3999 return CXAvailability_Available;
4000}
4001
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004002CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4003 if (clang_isDeclaration(cursor.kind))
4004 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4005
4006 return CXLanguage_Invalid;
4007}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004008
4009CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4010 if (clang_isDeclaration(cursor.kind)) {
4011 if (Decl *D = getCursorDecl(cursor)) {
4012 DeclContext *DC = D->getDeclContext();
4013 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4014 }
4015 }
4016
4017 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4018 if (Decl *D = getCursorDecl(cursor))
4019 return MakeCXCursor(D, getCursorASTUnit(cursor));
4020 }
4021
4022 return clang_getNullCursor();
4023}
4024
4025CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4026 if (clang_isDeclaration(cursor.kind)) {
4027 if (Decl *D = getCursorDecl(cursor)) {
4028 DeclContext *DC = D->getLexicalDeclContext();
4029 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4030 }
4031 }
4032
4033 // FIXME: Note that we can't easily compute the lexical context of a
4034 // statement or expression, so we return nothing.
4035 return clang_getNullCursor();
4036}
4037
Douglas Gregor9f592342010-10-01 20:25:15 +00004038static void CollectOverriddenMethods(DeclContext *Ctx,
4039 ObjCMethodDecl *Method,
4040 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4041 if (!Ctx)
4042 return;
4043
4044 // If we have a class or category implementation, jump straight to the
4045 // interface.
4046 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4047 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4048
4049 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4050 if (!Container)
4051 return;
4052
4053 // Check whether we have a matching method at this level.
4054 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4055 Method->isInstanceMethod()))
4056 if (Method != Overridden) {
4057 // We found an override at this level; there is no need to look
4058 // into other protocols or categories.
4059 Methods.push_back(Overridden);
4060 return;
4061 }
4062
4063 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4064 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4065 PEnd = Protocol->protocol_end();
4066 P != PEnd; ++P)
4067 CollectOverriddenMethods(*P, Method, Methods);
4068 }
4069
4070 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4071 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4072 PEnd = Category->protocol_end();
4073 P != PEnd; ++P)
4074 CollectOverriddenMethods(*P, Method, Methods);
4075 }
4076
4077 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4078 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4079 PEnd = Interface->protocol_end();
4080 P != PEnd; ++P)
4081 CollectOverriddenMethods(*P, Method, Methods);
4082
4083 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4084 Category; Category = Category->getNextClassCategory())
4085 CollectOverriddenMethods(Category, Method, Methods);
4086
4087 // We only look into the superclass if we haven't found anything yet.
4088 if (Methods.empty())
4089 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4090 return CollectOverriddenMethods(Super, Method, Methods);
4091 }
4092}
4093
4094void clang_getOverriddenCursors(CXCursor cursor,
4095 CXCursor **overridden,
4096 unsigned *num_overridden) {
4097 if (overridden)
4098 *overridden = 0;
4099 if (num_overridden)
4100 *num_overridden = 0;
4101 if (!overridden || !num_overridden)
4102 return;
4103
4104 if (!clang_isDeclaration(cursor.kind))
4105 return;
4106
4107 Decl *D = getCursorDecl(cursor);
4108 if (!D)
4109 return;
4110
4111 // Handle C++ member functions.
4112 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4113 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4114 *num_overridden = CXXMethod->size_overridden_methods();
4115 if (!*num_overridden)
4116 return;
4117
4118 *overridden = new CXCursor [*num_overridden];
4119 unsigned I = 0;
4120 for (CXXMethodDecl::method_iterator
4121 M = CXXMethod->begin_overridden_methods(),
4122 MEnd = CXXMethod->end_overridden_methods();
4123 M != MEnd; (void)++M, ++I)
4124 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4125 return;
4126 }
4127
4128 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4129 if (!Method)
4130 return;
4131
4132 // Handle Objective-C methods.
4133 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4134 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4135
4136 if (Methods.empty())
4137 return;
4138
4139 *num_overridden = Methods.size();
4140 *overridden = new CXCursor [Methods.size()];
4141 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4142 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4143}
4144
4145void clang_disposeOverriddenCursors(CXCursor *overridden) {
4146 delete [] overridden;
4147}
4148
Douglas Gregorecdcb882010-10-20 22:00:55 +00004149CXFile clang_getIncludedFile(CXCursor cursor) {
4150 if (cursor.kind != CXCursor_InclusionDirective)
4151 return 0;
4152
4153 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4154 return (void *)ID->getFile();
4155}
4156
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004157} // end: extern "C"
4158
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004159
4160//===----------------------------------------------------------------------===//
4161// C++ AST instrospection.
4162//===----------------------------------------------------------------------===//
4163
4164extern "C" {
4165unsigned clang_CXXMethod_isStatic(CXCursor C) {
4166 if (!clang_isDeclaration(C.kind))
4167 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004168
4169 CXXMethodDecl *Method = 0;
4170 Decl *D = cxcursor::getCursorDecl(C);
4171 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4172 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4173 else
4174 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4175 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004176}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004177
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004178} // end: extern "C"
4179
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004180//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004181// Attribute introspection.
4182//===----------------------------------------------------------------------===//
4183
4184extern "C" {
4185CXType clang_getIBOutletCollectionType(CXCursor C) {
4186 if (C.kind != CXCursor_IBOutletCollectionAttr)
4187 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4188
4189 IBOutletCollectionAttr *A =
4190 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4191
4192 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4193}
4194} // end: extern "C"
4195
4196//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004197// CXString Operations.
4198//===----------------------------------------------------------------------===//
4199
4200extern "C" {
4201const char *clang_getCString(CXString string) {
4202 return string.Spelling;
4203}
4204
4205void clang_disposeString(CXString string) {
4206 if (string.MustFreeString && string.Spelling)
4207 free((void*)string.Spelling);
4208}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004209
Ted Kremenekfb480492010-01-13 21:46:36 +00004210} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004211
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004212namespace clang { namespace cxstring {
4213CXString createCXString(const char *String, bool DupString){
4214 CXString Str;
4215 if (DupString) {
4216 Str.Spelling = strdup(String);
4217 Str.MustFreeString = 1;
4218 } else {
4219 Str.Spelling = String;
4220 Str.MustFreeString = 0;
4221 }
4222 return Str;
4223}
4224
4225CXString createCXString(llvm::StringRef String, bool DupString) {
4226 CXString Result;
4227 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4228 char *Spelling = (char *)malloc(String.size() + 1);
4229 memmove(Spelling, String.data(), String.size());
4230 Spelling[String.size()] = 0;
4231 Result.Spelling = Spelling;
4232 Result.MustFreeString = 1;
4233 } else {
4234 Result.Spelling = String.data();
4235 Result.MustFreeString = 0;
4236 }
4237 return Result;
4238}
4239}}
4240
Ted Kremenek04bb7162010-01-22 22:44:15 +00004241//===----------------------------------------------------------------------===//
4242// Misc. utility functions.
4243//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004244
Ted Kremenek04bb7162010-01-22 22:44:15 +00004245extern "C" {
4246
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004247CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004248 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004249}
4250
4251} // end: extern "C"