blob: 4413766b028e6c54647ccb37e488a087da89a417 [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) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001360 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001361 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1362 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001363 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001364 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001365 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001366 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001367
Douglas Gregora59e3902010-01-21 23:27:09 +00001368 return false;
1369}
1370
Douglas Gregor36897b02010-09-10 00:22:18 +00001371bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1372 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1373}
1374
Douglas Gregorf5bab412010-01-22 01:00:11 +00001375bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1376 if (VarDecl *Var = S->getConditionVariable()) {
1377 if (Visit(MakeCXCursor(Var, TU)))
1378 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001379 }
1380
Douglas Gregor263b47b2010-01-25 16:12:32 +00001381 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1382 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001383 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1384 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001385 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1386 return true;
1387
1388 return false;
1389}
1390
1391bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1392 if (VarDecl *Var = S->getConditionVariable()) {
1393 if (Visit(MakeCXCursor(Var, TU)))
1394 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001395 }
1396
Douglas Gregor263b47b2010-01-25 16:12:32 +00001397 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1398 return true;
1399 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1400 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001401
Douglas Gregor263b47b2010-01-25 16:12:32 +00001402 return false;
1403}
1404
1405bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1406 if (VarDecl *Var = S->getConditionVariable()) {
1407 if (Visit(MakeCXCursor(Var, TU)))
1408 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001409 }
1410
Douglas Gregor263b47b2010-01-25 16:12:32 +00001411 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1412 return true;
1413 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001414 return true;
1415
Douglas Gregor263b47b2010-01-25 16:12:32 +00001416 return false;
1417}
1418
1419bool CursorVisitor::VisitForStmt(ForStmt *S) {
1420 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1421 return true;
1422 if (VarDecl *Var = S->getConditionVariable()) {
1423 if (Visit(MakeCXCursor(Var, TU)))
1424 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001425 }
1426
Douglas Gregor263b47b2010-01-25 16:12:32 +00001427 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1428 return true;
1429 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1430 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001431 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1432 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001433
Douglas Gregorf5bab412010-01-22 01:00:11 +00001434 return false;
1435}
1436
Douglas Gregor8947a752010-09-02 20:35:02 +00001437bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1438 // Visit nested-name-specifier, if present.
1439 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1440 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1441 return true;
1442
1443 // Visit declaration name.
1444 if (VisitDeclarationNameInfo(E->getNameInfo()))
1445 return true;
1446
1447 // Visit explicitly-specified template arguments.
1448 if (E->hasExplicitTemplateArgs()) {
1449 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1450 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1451 *ArgEnd = Arg + Args.NumTemplateArgs;
1452 Arg != ArgEnd; ++Arg)
1453 if (VisitTemplateArgumentLoc(*Arg))
1454 return true;
1455 }
1456
1457 return false;
1458}
1459
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001460bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1461 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1462 return true;
1463
1464 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1465 return true;
1466
1467 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1468 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1469 return true;
1470
1471 return false;
1472}
1473
Ted Kremenek3064ef92010-08-27 21:34:58 +00001474bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1475 if (D->isDefinition()) {
1476 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1477 E = D->bases_end(); I != E; ++I) {
1478 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1479 return true;
1480 }
1481 }
1482
1483 return VisitTagDecl(D);
1484}
1485
1486
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001487bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1488 return Visit(B->getBlockDecl());
1489}
1490
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001491bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001492 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001493 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1494 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001495
1496 // Visit the components of the offsetof expression.
1497 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1498 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1499 const OffsetOfNode &Node = E->getComponent(I);
1500 switch (Node.getKind()) {
1501 case OffsetOfNode::Array:
1502 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1503 StmtParent, TU)))
1504 return true;
1505 break;
1506
1507 case OffsetOfNode::Field:
1508 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1509 TU)))
1510 return true;
1511 break;
1512
1513 case OffsetOfNode::Identifier:
1514 case OffsetOfNode::Base:
1515 continue;
1516 }
1517 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001518
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001519 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001520}
1521
Douglas Gregor336fd812010-01-23 00:40:08 +00001522bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1523 if (E->isArgumentType()) {
1524 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1525 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001526
Douglas Gregor336fd812010-01-23 00:40:08 +00001527 return false;
1528 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001529
Douglas Gregor336fd812010-01-23 00:40:08 +00001530 return VisitExpr(E);
1531}
1532
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001533bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1534 // Visit the base expression.
1535 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1536 return true;
1537
1538 // Visit the nested-name-specifier
1539 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1540 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1541 return true;
1542
1543 // Visit the declaration name.
1544 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1545 return true;
1546
1547 // Visit the explicitly-specified template arguments, if any.
1548 if (E->hasExplicitTemplateArgs()) {
1549 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1550 *ArgEnd = Arg + E->getNumTemplateArgs();
1551 Arg != ArgEnd;
1552 ++Arg) {
1553 if (VisitTemplateArgumentLoc(*Arg))
1554 return true;
1555 }
1556 }
1557
1558 return false;
1559}
1560
Douglas Gregor336fd812010-01-23 00:40:08 +00001561bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1562 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1563 if (Visit(TSInfo->getTypeLoc()))
1564 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001565
Douglas Gregor336fd812010-01-23 00:40:08 +00001566 return VisitCastExpr(E);
1567}
1568
1569bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1570 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1571 if (Visit(TSInfo->getTypeLoc()))
1572 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001573
Douglas Gregor336fd812010-01-23 00:40:08 +00001574 return VisitExpr(E);
1575}
1576
Douglas Gregor36897b02010-09-10 00:22:18 +00001577bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1578 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1579}
1580
Douglas Gregor648220e2010-08-10 15:02:34 +00001581bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1582 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1583 Visit(E->getArgTInfo2()->getTypeLoc());
1584}
1585
1586bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1587 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1588 return true;
1589
1590 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1591}
1592
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001593bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1594 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001595 if (InitListExpr *Syntactic = E->getSyntacticForm())
1596 return VisitExpr(Syntactic);
1597
1598 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001599}
1600
1601bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1602 // Visit the designators.
1603 typedef DesignatedInitExpr::Designator Designator;
1604 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1605 DEnd = E->designators_end();
1606 D != DEnd; ++D) {
1607 if (D->isFieldDesignator()) {
1608 if (FieldDecl *Field = D->getField())
1609 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1610 return true;
1611
1612 continue;
1613 }
1614
1615 if (D->isArrayDesignator()) {
1616 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1617 return true;
1618
1619 continue;
1620 }
1621
1622 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1623 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1624 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1625 return true;
1626 }
1627
1628 // Visit the initializer value itself.
1629 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1630}
1631
Douglas Gregor94802292010-09-02 21:20:16 +00001632bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1633 if (E->isTypeOperand()) {
1634 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1635 return Visit(TSInfo->getTypeLoc());
1636
1637 return false;
1638 }
1639
1640 return VisitExpr(E);
1641}
1642
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001643bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1644 if (E->isTypeOperand()) {
1645 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1646 return Visit(TSInfo->getTypeLoc());
1647
1648 return false;
1649 }
1650
1651 return VisitExpr(E);
1652}
1653
Douglas Gregorab6677e2010-09-08 00:15:04 +00001654bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1655 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1656 return Visit(TSInfo->getTypeLoc());
1657
1658 return VisitExpr(E);
1659}
1660
1661bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1662 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1663 return Visit(TSInfo->getTypeLoc());
1664
1665 return false;
1666}
1667
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001668bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1669 // Visit placement arguments.
1670 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1671 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1672 return true;
1673
1674 // Visit the allocated type.
1675 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1676 if (Visit(TSInfo->getTypeLoc()))
1677 return true;
1678
1679 // Visit the array size, if any.
1680 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1681 return true;
1682
1683 // Visit the initializer or constructor arguments.
1684 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1685 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1686 return true;
1687
1688 return false;
1689}
1690
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001691bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1692 // Visit base expression.
1693 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1694 return true;
1695
1696 // Visit the nested-name-specifier.
1697 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1698 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1699 return true;
1700
1701 // Visit the scope type that looks disturbingly like the nested-name-specifier
1702 // but isn't.
1703 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1704 if (Visit(TSInfo->getTypeLoc()))
1705 return true;
1706
1707 // Visit the name of the type being destroyed.
1708 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1709 if (Visit(TSInfo->getTypeLoc()))
1710 return true;
1711
1712 return false;
1713}
1714
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001715bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1716 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1717}
1718
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001719bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001720 // Visit the nested-name-specifier.
1721 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1722 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1723 return true;
1724
1725 // Visit the declaration name.
1726 if (VisitDeclarationNameInfo(E->getNameInfo()))
1727 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001728
1729 // Visit the overloaded declaration reference.
1730 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1731 return true;
1732
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001733 // Visit the explicitly-specified template arguments.
1734 if (const ExplicitTemplateArgumentList *ArgList
1735 = E->getOptionalExplicitTemplateArgs()) {
1736 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1737 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1738 Arg != ArgEnd; ++Arg) {
1739 if (VisitTemplateArgumentLoc(*Arg))
1740 return true;
1741 }
1742 }
1743
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001744 return false;
1745}
1746
Douglas Gregorbfebed22010-09-03 17:24:10 +00001747bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1748 DependentScopeDeclRefExpr *E) {
1749 // Visit the nested-name-specifier.
1750 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1751 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1752 return true;
1753
1754 // Visit the declaration name.
1755 if (VisitDeclarationNameInfo(E->getNameInfo()))
1756 return true;
1757
1758 // Visit the explicitly-specified template arguments.
1759 if (const ExplicitTemplateArgumentList *ArgList
1760 = E->getOptionalExplicitTemplateArgs()) {
1761 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1762 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1763 Arg != ArgEnd; ++Arg) {
1764 if (VisitTemplateArgumentLoc(*Arg))
1765 return true;
1766 }
1767 }
1768
1769 return false;
1770}
1771
Douglas Gregorab6677e2010-09-08 00:15:04 +00001772bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1773 CXXUnresolvedConstructExpr *E) {
1774 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1775 if (Visit(TSInfo->getTypeLoc()))
1776 return true;
1777
1778 return VisitExpr(E);
1779}
1780
Douglas Gregor25d63622010-09-03 17:35:34 +00001781bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1782 CXXDependentScopeMemberExpr *E) {
1783 // Visit the base expression, if there is one.
1784 if (!E->isImplicitAccess() &&
1785 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1786 return true;
1787
1788 // Visit the nested-name-specifier.
1789 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1790 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1791 return true;
1792
1793 // Visit the declaration name.
1794 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1795 return true;
1796
1797 // Visit the explicitly-specified template arguments.
1798 if (const ExplicitTemplateArgumentList *ArgList
1799 = E->getOptionalExplicitTemplateArgs()) {
1800 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1801 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1802 Arg != ArgEnd; ++Arg) {
1803 if (VisitTemplateArgumentLoc(*Arg))
1804 return true;
1805 }
1806 }
1807
1808 return false;
1809}
1810
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001811bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1812 // Visit the base expression, if there is one.
1813 if (!E->isImplicitAccess() &&
1814 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1815 return true;
1816
1817 return VisitOverloadExpr(E);
1818}
Douglas Gregor25d63622010-09-03 17:35:34 +00001819
Douglas Gregorc2350e52010-03-08 16:40:19 +00001820bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001821 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1822 if (Visit(TSInfo->getTypeLoc()))
1823 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001824
1825 return VisitExpr(E);
1826}
1827
Douglas Gregor81d34662010-04-20 15:39:42 +00001828bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1829 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1830}
1831
1832
Ted Kremenek09dfa372010-02-18 05:46:33 +00001833bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001834 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1835 i != e; ++i)
1836 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001837 return true;
1838
1839 return false;
1840}
1841
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001842static llvm::sys::Mutex EnableMultithreadingMutex;
1843static bool EnabledMultithreading;
1844
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001845extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001846CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1847 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00001848 // Disable pretty stack trace functionality, which will otherwise be a very
1849 // poor citizen of the world and set up all sorts of signal handlers.
1850 llvm::DisablePrettyStackTrace = true;
1851
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001852 // We use crash recovery to make some of our APIs more reliable, implicitly
1853 // enable it.
1854 llvm::CrashRecoveryContext::Enable();
1855
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001856 // Enable support for multithreading in LLVM.
1857 {
1858 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
1859 if (!EnabledMultithreading) {
1860 llvm::llvm_start_multithreaded();
1861 EnabledMultithreading = true;
1862 }
1863 }
1864
Douglas Gregora030b7c2010-01-22 20:35:53 +00001865 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001866 if (excludeDeclarationsFromPCH)
1867 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001868 if (displayDiagnostics)
1869 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001870 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001871}
1872
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001873void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001874 if (CIdx)
1875 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001876}
1877
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001878CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001879 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001880 if (!CIdx)
1881 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001882
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001883 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001884
Douglas Gregor28019772010-04-05 23:52:57 +00001885 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001886 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001887 CXXIdx->getOnlyLocalDecls(),
1888 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001889}
1890
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001891unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00001892 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00001893 CXTranslationUnit_CacheCompletionResults |
1894 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001895}
1896
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001897CXTranslationUnit
1898clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1899 const char *source_filename,
1900 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001901 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001902 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001903 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001904 return clang_parseTranslationUnit(CIdx, source_filename,
1905 command_line_args, num_command_line_args,
1906 unsaved_files, num_unsaved_files,
1907 CXTranslationUnit_DetailedPreprocessingRecord);
1908}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001909
1910struct ParseTranslationUnitInfo {
1911 CXIndex CIdx;
1912 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001913 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001914 int num_command_line_args;
1915 struct CXUnsavedFile *unsaved_files;
1916 unsigned num_unsaved_files;
1917 unsigned options;
1918 CXTranslationUnit result;
1919};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001920static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001921 ParseTranslationUnitInfo *PTUI =
1922 static_cast<ParseTranslationUnitInfo*>(UserData);
1923 CXIndex CIdx = PTUI->CIdx;
1924 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001925 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001926 int num_command_line_args = PTUI->num_command_line_args;
1927 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1928 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1929 unsigned options = PTUI->options;
1930 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001931
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001932 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001933 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001934
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001935 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1936
Douglas Gregor44c181a2010-07-23 00:33:23 +00001937 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001938 bool CompleteTranslationUnit
1939 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001940 bool CacheCodeCompetionResults
1941 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001942 bool CXXPrecompilePreamble
1943 = options & CXTranslationUnit_CXXPrecompiledPreamble;
1944 bool CXXChainedPCH
1945 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001946
Douglas Gregor5352ac02010-01-28 00:27:43 +00001947 // Configure the diagnostics.
1948 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001949 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1950 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001951
Douglas Gregor4db64a42010-01-23 00:14:00 +00001952 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1953 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001954 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001955 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001956 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001957 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1958 Buffer));
1959 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001960
Douglas Gregorb10daed2010-10-11 16:52:23 +00001961 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001962
Ted Kremenek139ba862009-10-22 00:03:57 +00001963 // The 'source_filename' argument is optional. If the caller does not
1964 // specify it then it is assumed that the source file is specified
1965 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001966 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00001967 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001968
1969 // Since the Clang C library is primarily used by batch tools dealing with
1970 // (often very broken) source code, where spell-checking can have a
1971 // significant negative impact on performance (particularly when
1972 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00001973 // Only do this if we haven't found a spell-checking-related argument.
1974 bool FoundSpellCheckingArgument = false;
1975 for (int I = 0; I != num_command_line_args; ++I) {
1976 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
1977 strcmp(command_line_args[I], "-fspell-checking") == 0) {
1978 FoundSpellCheckingArgument = true;
1979 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001980 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00001981 }
1982 if (!FoundSpellCheckingArgument)
1983 Args.push_back("-fno-spell-checking");
1984
1985 Args.insert(Args.end(), command_line_args,
1986 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00001987
Douglas Gregor44c181a2010-07-23 00:33:23 +00001988 // Do we need the detailed preprocessing record?
1989 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00001990 Args.push_back("-Xclang");
1991 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001992 }
1993
Douglas Gregorb10daed2010-10-11 16:52:23 +00001994 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00001995 llvm::OwningPtr<ASTUnit> Unit(
1996 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
1997 Diags,
1998 CXXIdx->getClangResourcesPath(),
1999 CXXIdx->getOnlyLocalDecls(),
2000 RemappedFiles.data(),
2001 RemappedFiles.size(),
2002 /*CaptureDiagnostics=*/true,
2003 PrecompilePreamble,
2004 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002005 CacheCodeCompetionResults,
2006 CXXPrecompilePreamble,
2007 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002008
Douglas Gregorb10daed2010-10-11 16:52:23 +00002009 if (NumErrors != Diags->getNumErrors()) {
2010 // Make sure to check that 'Unit' is non-NULL.
2011 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2012 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2013 DEnd = Unit->stored_diag_end();
2014 D != DEnd; ++D) {
2015 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2016 CXString Msg = clang_formatDiagnostic(&Diag,
2017 clang_defaultDiagnosticDisplayOptions());
2018 fprintf(stderr, "%s\n", clang_getCString(Msg));
2019 clang_disposeString(Msg);
2020 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002021#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002022 // On Windows, force a flush, since there may be multiple copies of
2023 // stderr and stdout in the file system, all with different buffers
2024 // but writing to the same device.
2025 fflush(stderr);
2026#endif
2027 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002028 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002029
Douglas Gregorb10daed2010-10-11 16:52:23 +00002030 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002031}
2032CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2033 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002034 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002035 int num_command_line_args,
2036 struct CXUnsavedFile *unsaved_files,
2037 unsigned num_unsaved_files,
2038 unsigned options) {
2039 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2040 num_command_line_args, unsaved_files, num_unsaved_files,
2041 options, 0 };
2042 llvm::CrashRecoveryContext CRC;
2043
2044 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002045 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2046 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2047 fprintf(stderr, " 'command_line_args' : [");
2048 for (int i = 0; i != num_command_line_args; ++i) {
2049 if (i)
2050 fprintf(stderr, ", ");
2051 fprintf(stderr, "'%s'", command_line_args[i]);
2052 }
2053 fprintf(stderr, "],\n");
2054 fprintf(stderr, " 'unsaved_files' : [");
2055 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2056 if (i)
2057 fprintf(stderr, ", ");
2058 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2059 unsaved_files[i].Length);
2060 }
2061 fprintf(stderr, "],\n");
2062 fprintf(stderr, " 'options' : %d,\n", options);
2063 fprintf(stderr, "}\n");
2064
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002065 return 0;
2066 }
2067
2068 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002069}
2070
Douglas Gregor19998442010-08-13 15:35:05 +00002071unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2072 return CXSaveTranslationUnit_None;
2073}
2074
2075int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2076 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002077 if (!TU)
2078 return 1;
2079
2080 return static_cast<ASTUnit *>(TU)->Save(FileName);
2081}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002082
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002083void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002084 if (CTUnit) {
2085 // If the translation unit has been marked as unsafe to free, just discard
2086 // it.
2087 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2088 return;
2089
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002090 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002091 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002092}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002093
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002094unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2095 return CXReparse_None;
2096}
2097
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002098struct ReparseTranslationUnitInfo {
2099 CXTranslationUnit TU;
2100 unsigned num_unsaved_files;
2101 struct CXUnsavedFile *unsaved_files;
2102 unsigned options;
2103 int result;
2104};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002105
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002106static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002107 ReparseTranslationUnitInfo *RTUI =
2108 static_cast<ReparseTranslationUnitInfo*>(UserData);
2109 CXTranslationUnit TU = RTUI->TU;
2110 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2111 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2112 unsigned options = RTUI->options;
2113 (void) options;
2114 RTUI->result = 1;
2115
Douglas Gregorabc563f2010-07-19 21:46:24 +00002116 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002117 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002118
2119 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2120 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002121
2122 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2123 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2124 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2125 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002126 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002127 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2128 Buffer));
2129 }
2130
Douglas Gregor593b0c12010-09-23 18:47:53 +00002131 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2132 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002133}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002134
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002135int clang_reparseTranslationUnit(CXTranslationUnit TU,
2136 unsigned num_unsaved_files,
2137 struct CXUnsavedFile *unsaved_files,
2138 unsigned options) {
2139 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2140 options, 0 };
2141 llvm::CrashRecoveryContext CRC;
2142
2143 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002144 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002145 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2146 return 1;
2147 }
2148
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002149
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002150 return RTUI.result;
2151}
2152
Douglas Gregordf95a132010-08-09 20:45:32 +00002153
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002154CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002155 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002156 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002157
Steve Naroff77accc12009-09-03 18:19:54 +00002158 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002159 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002160}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002161
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002162CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002163 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002164 return Result;
2165}
2166
Ted Kremenekfb480492010-01-13 21:46:36 +00002167} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002168
Ted Kremenekfb480492010-01-13 21:46:36 +00002169//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002170// CXSourceLocation and CXSourceRange Operations.
2171//===----------------------------------------------------------------------===//
2172
Douglas Gregorb9790342010-01-22 21:44:22 +00002173extern "C" {
2174CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002175 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002176 return Result;
2177}
2178
2179unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002180 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2181 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2182 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002183}
2184
2185CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2186 CXFile file,
2187 unsigned line,
2188 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002189 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002190 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002191
Douglas Gregorb9790342010-01-22 21:44:22 +00002192 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2193 SourceLocation SLoc
2194 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002196 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002197 if (SLoc.isInvalid()) return clang_getNullLocation();
2198
2199 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2200}
2201
2202CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2203 CXFile file,
2204 unsigned offset) {
2205 if (!tu || !file)
2206 return clang_getNullLocation();
2207
2208 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2209 SourceLocation Start
2210 = CXXUnit->getSourceManager().getLocation(
2211 static_cast<const FileEntry *>(file),
2212 1, 1);
2213 if (Start.isInvalid()) return clang_getNullLocation();
2214
2215 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2216
2217 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002218
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002219 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002220}
2221
Douglas Gregor5352ac02010-01-28 00:27:43 +00002222CXSourceRange clang_getNullRange() {
2223 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2224 return Result;
2225}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002226
Douglas Gregor5352ac02010-01-28 00:27:43 +00002227CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2228 if (begin.ptr_data[0] != end.ptr_data[0] ||
2229 begin.ptr_data[1] != end.ptr_data[1])
2230 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002231
2232 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002233 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002234 return Result;
2235}
2236
Douglas Gregor46766dc2010-01-26 19:19:08 +00002237void clang_getInstantiationLocation(CXSourceLocation location,
2238 CXFile *file,
2239 unsigned *line,
2240 unsigned *column,
2241 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002242 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2243
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002244 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002245 if (file)
2246 *file = 0;
2247 if (line)
2248 *line = 0;
2249 if (column)
2250 *column = 0;
2251 if (offset)
2252 *offset = 0;
2253 return;
2254 }
2255
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002256 const SourceManager &SM =
2257 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002258 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002259
2260 if (file)
2261 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2262 if (line)
2263 *line = SM.getInstantiationLineNumber(InstLoc);
2264 if (column)
2265 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002266 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002267 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002268}
2269
Douglas Gregor1db19de2010-01-19 21:36:55 +00002270CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002271 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002272 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002273 return Result;
2274}
2275
2276CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002277 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002278 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002279 return Result;
2280}
2281
Douglas Gregorb9790342010-01-22 21:44:22 +00002282} // end: extern "C"
2283
Douglas Gregor1db19de2010-01-19 21:36:55 +00002284//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002285// CXFile Operations.
2286//===----------------------------------------------------------------------===//
2287
2288extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002289CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002290 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002291 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002292
Steve Naroff88145032009-10-27 14:35:18 +00002293 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002294 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002295}
2296
2297time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002298 if (!SFile)
2299 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002300
Steve Naroff88145032009-10-27 14:35:18 +00002301 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2302 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002303}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002304
Douglas Gregorb9790342010-01-22 21:44:22 +00002305CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2306 if (!tu)
2307 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002308
Douglas Gregorb9790342010-01-22 21:44:22 +00002309 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002310
Douglas Gregorb9790342010-01-22 21:44:22 +00002311 FileManager &FMgr = CXXUnit->getFileManager();
2312 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2313 return const_cast<FileEntry *>(File);
2314}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002315
Ted Kremenekfb480492010-01-13 21:46:36 +00002316} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002317
Ted Kremenekfb480492010-01-13 21:46:36 +00002318//===----------------------------------------------------------------------===//
2319// CXCursor Operations.
2320//===----------------------------------------------------------------------===//
2321
Ted Kremenekfb480492010-01-13 21:46:36 +00002322static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002323 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2324 return getDeclFromExpr(CE->getSubExpr());
2325
Ted Kremenekfb480492010-01-13 21:46:36 +00002326 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2327 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002328 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2329 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002330 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2331 return ME->getMemberDecl();
2332 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2333 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002334 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2335 return PRE->getProperty();
2336
Ted Kremenekfb480492010-01-13 21:46:36 +00002337 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2338 return getDeclFromExpr(CE->getCallee());
Ted Kremenekfb480492010-01-13 21:46:36 +00002339 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2340 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002341
Douglas Gregordb1314e2010-10-01 21:11:22 +00002342 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2343 return PE->getProtocol();
2344
Ted Kremenekfb480492010-01-13 21:46:36 +00002345 return 0;
2346}
2347
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002348static SourceLocation getLocationFromExpr(Expr *E) {
2349 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2350 return /*FIXME:*/Msg->getLeftLoc();
2351 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2352 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002353 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2354 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002355 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2356 return Member->getMemberLoc();
2357 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2358 return Ivar->getLocation();
2359 return E->getLocStart();
2360}
2361
Ted Kremenekfb480492010-01-13 21:46:36 +00002362extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002363
2364unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002365 CXCursorVisitor visitor,
2366 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002367 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002368
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002369 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2370 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002371 return CursorVis.VisitChildren(parent);
2372}
2373
Douglas Gregor78205d42010-01-20 21:45:58 +00002374static CXString getDeclSpelling(Decl *D) {
2375 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2376 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002377 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002378
Douglas Gregor78205d42010-01-20 21:45:58 +00002379 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002380 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002381
Douglas Gregor78205d42010-01-20 21:45:58 +00002382 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2383 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2384 // and returns different names. NamedDecl returns the class name and
2385 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002386 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002387
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002388 if (isa<UsingDirectiveDecl>(D))
2389 return createCXString("");
2390
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002391 llvm::SmallString<1024> S;
2392 llvm::raw_svector_ostream os(S);
2393 ND->printName(os);
2394
2395 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002396}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002397
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002398CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002399 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002400 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002401
Steve Narofff334b4e2009-09-02 18:26:48 +00002402 if (clang_isReference(C.kind)) {
2403 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002404 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002405 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002406 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002407 }
2408 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002409 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002410 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002411 }
2412 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002413 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002414 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002415 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002416 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002417 case CXCursor_CXXBaseSpecifier: {
2418 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2419 return createCXString(B->getType().getAsString());
2420 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002421 case CXCursor_TypeRef: {
2422 TypeDecl *Type = getCursorTypeRef(C).first;
2423 assert(Type && "Missing type decl");
2424
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002425 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2426 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002427 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002428 case CXCursor_TemplateRef: {
2429 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002430 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002431
2432 return createCXString(Template->getNameAsString());
2433 }
Douglas Gregor69319002010-08-31 23:48:11 +00002434
2435 case CXCursor_NamespaceRef: {
2436 NamedDecl *NS = getCursorNamespaceRef(C).first;
2437 assert(NS && "Missing namespace decl");
2438
2439 return createCXString(NS->getNameAsString());
2440 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002441
Douglas Gregora67e03f2010-09-09 21:42:20 +00002442 case CXCursor_MemberRef: {
2443 FieldDecl *Field = getCursorMemberRef(C).first;
2444 assert(Field && "Missing member decl");
2445
2446 return createCXString(Field->getNameAsString());
2447 }
2448
Douglas Gregor36897b02010-09-10 00:22:18 +00002449 case CXCursor_LabelRef: {
2450 LabelStmt *Label = getCursorLabelRef(C).first;
2451 assert(Label && "Missing label");
2452
2453 return createCXString(Label->getID()->getName());
2454 }
2455
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002456 case CXCursor_OverloadedDeclRef: {
2457 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2458 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2459 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2460 return createCXString(ND->getNameAsString());
2461 return createCXString("");
2462 }
2463 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2464 return createCXString(E->getName().getAsString());
2465 OverloadedTemplateStorage *Ovl
2466 = Storage.get<OverloadedTemplateStorage*>();
2467 if (Ovl->size() == 0)
2468 return createCXString("");
2469 return createCXString((*Ovl->begin())->getNameAsString());
2470 }
2471
Daniel Dunbaracca7252009-11-30 20:42:49 +00002472 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002473 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002474 }
2475 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002476
2477 if (clang_isExpression(C.kind)) {
2478 Decl *D = getDeclFromExpr(getCursorExpr(C));
2479 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002480 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002481 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002482 }
2483
Douglas Gregor36897b02010-09-10 00:22:18 +00002484 if (clang_isStatement(C.kind)) {
2485 Stmt *S = getCursorStmt(C);
2486 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2487 return createCXString(Label->getID()->getName());
2488
2489 return createCXString("");
2490 }
2491
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002492 if (C.kind == CXCursor_MacroInstantiation)
2493 return createCXString(getCursorMacroInstantiation(C)->getName()
2494 ->getNameStart());
2495
Douglas Gregor572feb22010-03-18 18:04:21 +00002496 if (C.kind == CXCursor_MacroDefinition)
2497 return createCXString(getCursorMacroDefinition(C)->getName()
2498 ->getNameStart());
2499
Douglas Gregorecdcb882010-10-20 22:00:55 +00002500 if (C.kind == CXCursor_InclusionDirective)
2501 return createCXString(getCursorInclusionDirective(C)->getFileName());
2502
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002503 if (clang_isDeclaration(C.kind))
2504 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002505
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002506 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002507}
2508
Douglas Gregor358559d2010-10-02 22:49:11 +00002509CXString clang_getCursorDisplayName(CXCursor C) {
2510 if (!clang_isDeclaration(C.kind))
2511 return clang_getCursorSpelling(C);
2512
2513 Decl *D = getCursorDecl(C);
2514 if (!D)
2515 return createCXString("");
2516
2517 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2518 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2519 D = FunTmpl->getTemplatedDecl();
2520
2521 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2522 llvm::SmallString<64> Str;
2523 llvm::raw_svector_ostream OS(Str);
2524 OS << Function->getNameAsString();
2525 if (Function->getPrimaryTemplate())
2526 OS << "<>";
2527 OS << "(";
2528 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2529 if (I)
2530 OS << ", ";
2531 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2532 }
2533
2534 if (Function->isVariadic()) {
2535 if (Function->getNumParams())
2536 OS << ", ";
2537 OS << "...";
2538 }
2539 OS << ")";
2540 return createCXString(OS.str());
2541 }
2542
2543 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2544 llvm::SmallString<64> Str;
2545 llvm::raw_svector_ostream OS(Str);
2546 OS << ClassTemplate->getNameAsString();
2547 OS << "<";
2548 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2549 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2550 if (I)
2551 OS << ", ";
2552
2553 NamedDecl *Param = Params->getParam(I);
2554 if (Param->getIdentifier()) {
2555 OS << Param->getIdentifier()->getName();
2556 continue;
2557 }
2558
2559 // There is no parameter name, which makes this tricky. Try to come up
2560 // with something useful that isn't too long.
2561 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2562 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2563 else if (NonTypeTemplateParmDecl *NTTP
2564 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2565 OS << NTTP->getType().getAsString(Policy);
2566 else
2567 OS << "template<...> class";
2568 }
2569
2570 OS << ">";
2571 return createCXString(OS.str());
2572 }
2573
2574 if (ClassTemplateSpecializationDecl *ClassSpec
2575 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2576 // If the type was explicitly written, use that.
2577 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2578 return createCXString(TSInfo->getType().getAsString(Policy));
2579
2580 llvm::SmallString<64> Str;
2581 llvm::raw_svector_ostream OS(Str);
2582 OS << ClassSpec->getNameAsString();
2583 OS << TemplateSpecializationType::PrintTemplateArgumentList(
2584 ClassSpec->getTemplateArgs().getFlatArgumentList(),
2585 ClassSpec->getTemplateArgs().flat_size(),
2586 Policy);
2587 return createCXString(OS.str());
2588 }
2589
2590 return clang_getCursorSpelling(C);
2591}
2592
Ted Kremeneke68fff62010-02-17 00:41:32 +00002593CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002594 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002595 case CXCursor_FunctionDecl:
2596 return createCXString("FunctionDecl");
2597 case CXCursor_TypedefDecl:
2598 return createCXString("TypedefDecl");
2599 case CXCursor_EnumDecl:
2600 return createCXString("EnumDecl");
2601 case CXCursor_EnumConstantDecl:
2602 return createCXString("EnumConstantDecl");
2603 case CXCursor_StructDecl:
2604 return createCXString("StructDecl");
2605 case CXCursor_UnionDecl:
2606 return createCXString("UnionDecl");
2607 case CXCursor_ClassDecl:
2608 return createCXString("ClassDecl");
2609 case CXCursor_FieldDecl:
2610 return createCXString("FieldDecl");
2611 case CXCursor_VarDecl:
2612 return createCXString("VarDecl");
2613 case CXCursor_ParmDecl:
2614 return createCXString("ParmDecl");
2615 case CXCursor_ObjCInterfaceDecl:
2616 return createCXString("ObjCInterfaceDecl");
2617 case CXCursor_ObjCCategoryDecl:
2618 return createCXString("ObjCCategoryDecl");
2619 case CXCursor_ObjCProtocolDecl:
2620 return createCXString("ObjCProtocolDecl");
2621 case CXCursor_ObjCPropertyDecl:
2622 return createCXString("ObjCPropertyDecl");
2623 case CXCursor_ObjCIvarDecl:
2624 return createCXString("ObjCIvarDecl");
2625 case CXCursor_ObjCInstanceMethodDecl:
2626 return createCXString("ObjCInstanceMethodDecl");
2627 case CXCursor_ObjCClassMethodDecl:
2628 return createCXString("ObjCClassMethodDecl");
2629 case CXCursor_ObjCImplementationDecl:
2630 return createCXString("ObjCImplementationDecl");
2631 case CXCursor_ObjCCategoryImplDecl:
2632 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002633 case CXCursor_CXXMethod:
2634 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002635 case CXCursor_UnexposedDecl:
2636 return createCXString("UnexposedDecl");
2637 case CXCursor_ObjCSuperClassRef:
2638 return createCXString("ObjCSuperClassRef");
2639 case CXCursor_ObjCProtocolRef:
2640 return createCXString("ObjCProtocolRef");
2641 case CXCursor_ObjCClassRef:
2642 return createCXString("ObjCClassRef");
2643 case CXCursor_TypeRef:
2644 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002645 case CXCursor_TemplateRef:
2646 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002647 case CXCursor_NamespaceRef:
2648 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002649 case CXCursor_MemberRef:
2650 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002651 case CXCursor_LabelRef:
2652 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002653 case CXCursor_OverloadedDeclRef:
2654 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002655 case CXCursor_UnexposedExpr:
2656 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002657 case CXCursor_BlockExpr:
2658 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002659 case CXCursor_DeclRefExpr:
2660 return createCXString("DeclRefExpr");
2661 case CXCursor_MemberRefExpr:
2662 return createCXString("MemberRefExpr");
2663 case CXCursor_CallExpr:
2664 return createCXString("CallExpr");
2665 case CXCursor_ObjCMessageExpr:
2666 return createCXString("ObjCMessageExpr");
2667 case CXCursor_UnexposedStmt:
2668 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002669 case CXCursor_LabelStmt:
2670 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002671 case CXCursor_InvalidFile:
2672 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002673 case CXCursor_InvalidCode:
2674 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002675 case CXCursor_NoDeclFound:
2676 return createCXString("NoDeclFound");
2677 case CXCursor_NotImplemented:
2678 return createCXString("NotImplemented");
2679 case CXCursor_TranslationUnit:
2680 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002681 case CXCursor_UnexposedAttr:
2682 return createCXString("UnexposedAttr");
2683 case CXCursor_IBActionAttr:
2684 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002685 case CXCursor_IBOutletAttr:
2686 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002687 case CXCursor_IBOutletCollectionAttr:
2688 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002689 case CXCursor_PreprocessingDirective:
2690 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002691 case CXCursor_MacroDefinition:
2692 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002693 case CXCursor_MacroInstantiation:
2694 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002695 case CXCursor_InclusionDirective:
2696 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002697 case CXCursor_Namespace:
2698 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002699 case CXCursor_LinkageSpec:
2700 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002701 case CXCursor_CXXBaseSpecifier:
2702 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002703 case CXCursor_Constructor:
2704 return createCXString("CXXConstructor");
2705 case CXCursor_Destructor:
2706 return createCXString("CXXDestructor");
2707 case CXCursor_ConversionFunction:
2708 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002709 case CXCursor_TemplateTypeParameter:
2710 return createCXString("TemplateTypeParameter");
2711 case CXCursor_NonTypeTemplateParameter:
2712 return createCXString("NonTypeTemplateParameter");
2713 case CXCursor_TemplateTemplateParameter:
2714 return createCXString("TemplateTemplateParameter");
2715 case CXCursor_FunctionTemplate:
2716 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002717 case CXCursor_ClassTemplate:
2718 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002719 case CXCursor_ClassTemplatePartialSpecialization:
2720 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002721 case CXCursor_NamespaceAlias:
2722 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002723 case CXCursor_UsingDirective:
2724 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002725 case CXCursor_UsingDeclaration:
2726 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002727 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002728
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002729 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002730 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002731}
Steve Naroff89922f82009-08-31 00:59:03 +00002732
Ted Kremeneke68fff62010-02-17 00:41:32 +00002733enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2734 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002735 CXClientData client_data) {
2736 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2737 *BestCursor = cursor;
2738 return CXChildVisit_Recurse;
2739}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002740
Douglas Gregorb9790342010-01-22 21:44:22 +00002741CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2742 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002743 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002744
Douglas Gregorb9790342010-01-22 21:44:22 +00002745 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002746 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2747
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002748 // Translate the given source location to make it point at the beginning of
2749 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002750 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002751
2752 // Guard against an invalid SourceLocation, or we may assert in one
2753 // of the following calls.
2754 if (SLoc.isInvalid())
2755 return clang_getNullCursor();
2756
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002757 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2758 CXXUnit->getASTContext().getLangOptions());
2759
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002760 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2761 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002762 // FIXME: Would be great to have a "hint" cursor, then walk from that
2763 // hint cursor upward until we find a cursor whose source range encloses
2764 // the region of interest, rather than starting from the translation unit.
2765 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002766 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002767 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002768 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002769 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002770 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002771}
2772
Ted Kremenek73885552009-11-17 19:28:59 +00002773CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002774 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002775}
2776
2777unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002778 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002779}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002780
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002781unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002782 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2783}
2784
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002785unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002786 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2787}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002788
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002789unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002790 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2791}
2792
Douglas Gregor97b98722010-01-19 23:20:36 +00002793unsigned clang_isExpression(enum CXCursorKind K) {
2794 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2795}
2796
2797unsigned clang_isStatement(enum CXCursorKind K) {
2798 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2799}
2800
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002801unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2802 return K == CXCursor_TranslationUnit;
2803}
2804
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002805unsigned clang_isPreprocessing(enum CXCursorKind K) {
2806 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2807}
2808
Ted Kremenekad6eff62010-03-08 21:17:29 +00002809unsigned clang_isUnexposed(enum CXCursorKind K) {
2810 switch (K) {
2811 case CXCursor_UnexposedDecl:
2812 case CXCursor_UnexposedExpr:
2813 case CXCursor_UnexposedStmt:
2814 case CXCursor_UnexposedAttr:
2815 return true;
2816 default:
2817 return false;
2818 }
2819}
2820
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002821CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002822 return C.kind;
2823}
2824
Douglas Gregor98258af2010-01-18 22:46:11 +00002825CXSourceLocation clang_getCursorLocation(CXCursor C) {
2826 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002827 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002828 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002829 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2830 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002831 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002832 }
2833
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002834 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002835 std::pair<ObjCProtocolDecl *, SourceLocation> P
2836 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002837 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002838 }
2839
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002840 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002841 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2842 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002843 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002844 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002845
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002846 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002847 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002848 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002849 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002850
2851 case CXCursor_TemplateRef: {
2852 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2853 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2854 }
2855
Douglas Gregor69319002010-08-31 23:48:11 +00002856 case CXCursor_NamespaceRef: {
2857 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2858 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2859 }
2860
Douglas Gregora67e03f2010-09-09 21:42:20 +00002861 case CXCursor_MemberRef: {
2862 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2863 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2864 }
2865
Ted Kremenek3064ef92010-08-27 21:34:58 +00002866 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00002867 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
2868 if (!BaseSpec)
2869 return clang_getNullLocation();
2870
2871 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
2872 return cxloc::translateSourceLocation(getCursorContext(C),
2873 TSInfo->getTypeLoc().getBeginLoc());
2874
2875 return cxloc::translateSourceLocation(getCursorContext(C),
2876 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00002877 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002878
Douglas Gregor36897b02010-09-10 00:22:18 +00002879 case CXCursor_LabelRef: {
2880 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
2881 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
2882 }
2883
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002884 case CXCursor_OverloadedDeclRef:
2885 return cxloc::translateSourceLocation(getCursorContext(C),
2886 getCursorOverloadedDeclRef(C).second);
2887
Douglas Gregorf46034a2010-01-18 23:41:10 +00002888 default:
2889 // FIXME: Need a way to enumerate all non-reference cases.
2890 llvm_unreachable("Missed a reference kind");
2891 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002892 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002893
2894 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002895 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002896 getLocationFromExpr(getCursorExpr(C)));
2897
Douglas Gregor36897b02010-09-10 00:22:18 +00002898 if (clang_isStatement(C.kind))
2899 return cxloc::translateSourceLocation(getCursorContext(C),
2900 getCursorStmt(C)->getLocStart());
2901
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002902 if (C.kind == CXCursor_PreprocessingDirective) {
2903 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2904 return cxloc::translateSourceLocation(getCursorContext(C), L);
2905 }
Douglas Gregor48072312010-03-18 15:23:44 +00002906
2907 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002908 SourceLocation L
2909 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002910 return cxloc::translateSourceLocation(getCursorContext(C), L);
2911 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002912
2913 if (C.kind == CXCursor_MacroDefinition) {
2914 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2915 return cxloc::translateSourceLocation(getCursorContext(C), L);
2916 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00002917
2918 if (C.kind == CXCursor_InclusionDirective) {
2919 SourceLocation L
2920 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
2921 return cxloc::translateSourceLocation(getCursorContext(C), L);
2922 }
2923
Ted Kremenek9a700d22010-05-12 06:16:13 +00002924 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002925 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002926
Douglas Gregorf46034a2010-01-18 23:41:10 +00002927 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002928 SourceLocation Loc = D->getLocation();
2929 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2930 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00002931 // FIXME: Multiple variables declared in a single declaration
2932 // currently lack the information needed to correctly determine their
2933 // ranges when accounting for the type-specifier. We use context
2934 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
2935 // and if so, whether it is the first decl.
2936 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2937 if (!cxcursor::isFirstInDeclGroup(C))
2938 Loc = VD->getLocation();
2939 }
2940
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002941 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002942}
Douglas Gregora7bde202010-01-19 00:34:46 +00002943
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002944} // end extern "C"
2945
2946static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002947 if (clang_isReference(C.kind)) {
2948 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002949 case CXCursor_ObjCSuperClassRef:
2950 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002951
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002952 case CXCursor_ObjCProtocolRef:
2953 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002954
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002955 case CXCursor_ObjCClassRef:
2956 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002957
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002958 case CXCursor_TypeRef:
2959 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002960
2961 case CXCursor_TemplateRef:
2962 return getCursorTemplateRef(C).second;
2963
Douglas Gregor69319002010-08-31 23:48:11 +00002964 case CXCursor_NamespaceRef:
2965 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00002966
2967 case CXCursor_MemberRef:
2968 return getCursorMemberRef(C).second;
2969
Ted Kremenek3064ef92010-08-27 21:34:58 +00002970 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00002971 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002972
Douglas Gregor36897b02010-09-10 00:22:18 +00002973 case CXCursor_LabelRef:
2974 return getCursorLabelRef(C).second;
2975
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002976 case CXCursor_OverloadedDeclRef:
2977 return getCursorOverloadedDeclRef(C).second;
2978
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002979 default:
2980 // FIXME: Need a way to enumerate all non-reference cases.
2981 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002982 }
2983 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002984
2985 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002986 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002987
2988 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002989 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002990
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002991 if (C.kind == CXCursor_PreprocessingDirective)
2992 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002993
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002994 if (C.kind == CXCursor_MacroInstantiation)
2995 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002996
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002997 if (C.kind == CXCursor_MacroDefinition)
2998 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00002999
3000 if (C.kind == CXCursor_InclusionDirective)
3001 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3002
Ted Kremenek007a7c92010-11-01 23:26:51 +00003003 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3004 Decl *D = cxcursor::getCursorDecl(C);
3005 SourceRange R = D->getSourceRange();
3006 // FIXME: Multiple variables declared in a single declaration
3007 // currently lack the information needed to correctly determine their
3008 // ranges when accounting for the type-specifier. We use context
3009 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3010 // and if so, whether it is the first decl.
3011 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3012 if (!cxcursor::isFirstInDeclGroup(C))
3013 R.setBegin(VD->getLocation());
3014 }
3015 return R;
3016 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003017 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003018
3019extern "C" {
3020
3021CXSourceRange clang_getCursorExtent(CXCursor C) {
3022 SourceRange R = getRawCursorExtent(C);
3023 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003024 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003025
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003026 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003027}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003028
3029CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003030 if (clang_isInvalid(C.kind))
3031 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003032
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003033 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003034 if (clang_isDeclaration(C.kind)) {
3035 Decl *D = getCursorDecl(C);
3036 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3037 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3038 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3039 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3040 if (ObjCForwardProtocolDecl *Protocols
3041 = dyn_cast<ObjCForwardProtocolDecl>(D))
3042 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3043
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003044 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003045 }
3046
Douglas Gregor97b98722010-01-19 23:20:36 +00003047 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003048 Expr *E = getCursorExpr(C);
3049 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003050 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003051 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003052
3053 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3054 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3055
Douglas Gregor97b98722010-01-19 23:20:36 +00003056 return clang_getNullCursor();
3057 }
3058
Douglas Gregor36897b02010-09-10 00:22:18 +00003059 if (clang_isStatement(C.kind)) {
3060 Stmt *S = getCursorStmt(C);
3061 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3062 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3063 getCursorASTUnit(C));
3064
3065 return clang_getNullCursor();
3066 }
3067
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003068 if (C.kind == CXCursor_MacroInstantiation) {
3069 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3070 return MakeMacroDefinitionCursor(Def, CXXUnit);
3071 }
3072
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003073 if (!clang_isReference(C.kind))
3074 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003075
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003076 switch (C.kind) {
3077 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003078 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003079
3080 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003081 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003082
3083 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003084 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003085
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003086 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003087 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003088
3089 case CXCursor_TemplateRef:
3090 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3091
Douglas Gregor69319002010-08-31 23:48:11 +00003092 case CXCursor_NamespaceRef:
3093 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3094
Douglas Gregora67e03f2010-09-09 21:42:20 +00003095 case CXCursor_MemberRef:
3096 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3097
Ted Kremenek3064ef92010-08-27 21:34:58 +00003098 case CXCursor_CXXBaseSpecifier: {
3099 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3100 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3101 CXXUnit));
3102 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003103
Douglas Gregor36897b02010-09-10 00:22:18 +00003104 case CXCursor_LabelRef:
3105 // FIXME: We end up faking the "parent" declaration here because we
3106 // don't want to make CXCursor larger.
3107 return MakeCXCursor(getCursorLabelRef(C).first,
3108 CXXUnit->getASTContext().getTranslationUnitDecl(),
3109 CXXUnit);
3110
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003111 case CXCursor_OverloadedDeclRef:
3112 return C;
3113
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003114 default:
3115 // We would prefer to enumerate all non-reference cursor kinds here.
3116 llvm_unreachable("Unhandled reference cursor kind");
3117 break;
3118 }
3119 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003120
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003121 return clang_getNullCursor();
3122}
3123
Douglas Gregorb6998662010-01-19 19:34:47 +00003124CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003125 if (clang_isInvalid(C.kind))
3126 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003127
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003128 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003129
Douglas Gregorb6998662010-01-19 19:34:47 +00003130 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003131 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003132 C = clang_getCursorReferenced(C);
3133 WasReference = true;
3134 }
3135
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003136 if (C.kind == CXCursor_MacroInstantiation)
3137 return clang_getCursorReferenced(C);
3138
Douglas Gregorb6998662010-01-19 19:34:47 +00003139 if (!clang_isDeclaration(C.kind))
3140 return clang_getNullCursor();
3141
3142 Decl *D = getCursorDecl(C);
3143 if (!D)
3144 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003145
Douglas Gregorb6998662010-01-19 19:34:47 +00003146 switch (D->getKind()) {
3147 // Declaration kinds that don't really separate the notions of
3148 // declaration and definition.
3149 case Decl::Namespace:
3150 case Decl::Typedef:
3151 case Decl::TemplateTypeParm:
3152 case Decl::EnumConstant:
3153 case Decl::Field:
3154 case Decl::ObjCIvar:
3155 case Decl::ObjCAtDefsField:
3156 case Decl::ImplicitParam:
3157 case Decl::ParmVar:
3158 case Decl::NonTypeTemplateParm:
3159 case Decl::TemplateTemplateParm:
3160 case Decl::ObjCCategoryImpl:
3161 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003162 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003163 case Decl::LinkageSpec:
3164 case Decl::ObjCPropertyImpl:
3165 case Decl::FileScopeAsm:
3166 case Decl::StaticAssert:
3167 case Decl::Block:
3168 return C;
3169
3170 // Declaration kinds that don't make any sense here, but are
3171 // nonetheless harmless.
3172 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003173 break;
3174
3175 // Declaration kinds for which the definition is not resolvable.
3176 case Decl::UnresolvedUsingTypename:
3177 case Decl::UnresolvedUsingValue:
3178 break;
3179
3180 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003181 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3182 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003183
3184 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003185 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003186
3187 case Decl::Enum:
3188 case Decl::Record:
3189 case Decl::CXXRecord:
3190 case Decl::ClassTemplateSpecialization:
3191 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003192 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003193 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003194 return clang_getNullCursor();
3195
3196 case Decl::Function:
3197 case Decl::CXXMethod:
3198 case Decl::CXXConstructor:
3199 case Decl::CXXDestructor:
3200 case Decl::CXXConversion: {
3201 const FunctionDecl *Def = 0;
3202 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003203 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003204 return clang_getNullCursor();
3205 }
3206
3207 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003208 // Ask the variable if it has a definition.
3209 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3210 return MakeCXCursor(Def, CXXUnit);
3211 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003212 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003213
Douglas Gregorb6998662010-01-19 19:34:47 +00003214 case Decl::FunctionTemplate: {
3215 const FunctionDecl *Def = 0;
3216 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003217 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003218 return clang_getNullCursor();
3219 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003220
Douglas Gregorb6998662010-01-19 19:34:47 +00003221 case Decl::ClassTemplate: {
3222 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003223 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003224 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003225 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003226 return clang_getNullCursor();
3227 }
3228
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003229 case Decl::Using:
3230 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3231 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003232
3233 case Decl::UsingShadow:
3234 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003235 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003236 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003237
3238 case Decl::ObjCMethod: {
3239 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3240 if (Method->isThisDeclarationADefinition())
3241 return C;
3242
3243 // Dig out the method definition in the associated
3244 // @implementation, if we have it.
3245 // FIXME: The ASTs should make finding the definition easier.
3246 if (ObjCInterfaceDecl *Class
3247 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3248 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3249 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3250 Method->isInstanceMethod()))
3251 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003252 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003253
3254 return clang_getNullCursor();
3255 }
3256
3257 case Decl::ObjCCategory:
3258 if (ObjCCategoryImplDecl *Impl
3259 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003260 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003261 return clang_getNullCursor();
3262
3263 case Decl::ObjCProtocol:
3264 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3265 return C;
3266 return clang_getNullCursor();
3267
3268 case Decl::ObjCInterface:
3269 // There are two notions of a "definition" for an Objective-C
3270 // class: the interface and its implementation. When we resolved a
3271 // reference to an Objective-C class, produce the @interface as
3272 // the definition; when we were provided with the interface,
3273 // produce the @implementation as the definition.
3274 if (WasReference) {
3275 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3276 return C;
3277 } else if (ObjCImplementationDecl *Impl
3278 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003279 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003280 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003281
Douglas Gregorb6998662010-01-19 19:34:47 +00003282 case Decl::ObjCProperty:
3283 // FIXME: We don't really know where to find the
3284 // ObjCPropertyImplDecls that implement this property.
3285 return clang_getNullCursor();
3286
3287 case Decl::ObjCCompatibleAlias:
3288 if (ObjCInterfaceDecl *Class
3289 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3290 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003291 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003292
Douglas Gregorb6998662010-01-19 19:34:47 +00003293 return clang_getNullCursor();
3294
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003295 case Decl::ObjCForwardProtocol:
3296 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3297 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003298
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003299 case Decl::ObjCClass:
3300 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3301 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003302
3303 case Decl::Friend:
3304 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003305 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003306 return clang_getNullCursor();
3307
3308 case Decl::FriendTemplate:
3309 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003310 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003311 return clang_getNullCursor();
3312 }
3313
3314 return clang_getNullCursor();
3315}
3316
3317unsigned clang_isCursorDefinition(CXCursor C) {
3318 if (!clang_isDeclaration(C.kind))
3319 return 0;
3320
3321 return clang_getCursorDefinition(C) == C;
3322}
3323
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003324unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003325 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003326 return 0;
3327
3328 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3329 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3330 return E->getNumDecls();
3331
3332 if (OverloadedTemplateStorage *S
3333 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3334 return S->size();
3335
3336 Decl *D = Storage.get<Decl*>();
3337 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3338 return Using->getNumShadowDecls();
3339 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3340 return Classes->size();
3341 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3342 return Protocols->protocol_size();
3343
3344 return 0;
3345}
3346
3347CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003348 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003349 return clang_getNullCursor();
3350
3351 if (index >= clang_getNumOverloadedDecls(cursor))
3352 return clang_getNullCursor();
3353
3354 ASTUnit *Unit = getCursorASTUnit(cursor);
3355 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3356 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3357 return MakeCXCursor(E->decls_begin()[index], Unit);
3358
3359 if (OverloadedTemplateStorage *S
3360 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3361 return MakeCXCursor(S->begin()[index], Unit);
3362
3363 Decl *D = Storage.get<Decl*>();
3364 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3365 // FIXME: This is, unfortunately, linear time.
3366 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3367 std::advance(Pos, index);
3368 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3369 }
3370
3371 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3372 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3373
3374 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3375 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3376
3377 return clang_getNullCursor();
3378}
3379
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003380void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003381 const char **startBuf,
3382 const char **endBuf,
3383 unsigned *startLine,
3384 unsigned *startColumn,
3385 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003386 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003387 assert(getCursorDecl(C) && "CXCursor has null decl");
3388 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003389 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3390 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003391
Steve Naroff4ade6d62009-09-23 17:52:52 +00003392 SourceManager &SM = FD->getASTContext().getSourceManager();
3393 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3394 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3395 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3396 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3397 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3398 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3399}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003400
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003401void clang_enableStackTraces(void) {
3402 llvm::sys::PrintStackTraceOnErrorSignal();
3403}
3404
Ted Kremenekfb480492010-01-13 21:46:36 +00003405} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003406
Ted Kremenekfb480492010-01-13 21:46:36 +00003407//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003408// Token-based Operations.
3409//===----------------------------------------------------------------------===//
3410
3411/* CXToken layout:
3412 * int_data[0]: a CXTokenKind
3413 * int_data[1]: starting token location
3414 * int_data[2]: token length
3415 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003416 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003417 * otherwise unused.
3418 */
3419extern "C" {
3420
3421CXTokenKind clang_getTokenKind(CXToken CXTok) {
3422 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3423}
3424
3425CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3426 switch (clang_getTokenKind(CXTok)) {
3427 case CXToken_Identifier:
3428 case CXToken_Keyword:
3429 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003430 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3431 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003432
3433 case CXToken_Literal: {
3434 // We have stashed the starting pointer in the ptr_data field. Use it.
3435 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003436 return createCXString(llvm::StringRef(Text, 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 +00003439 case CXToken_Punctuation:
3440 case CXToken_Comment:
3441 break;
3442 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003443
3444 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003445 // deconstructing the source location.
3446 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3447 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003448 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003449
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003450 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3451 std::pair<FileID, unsigned> LocInfo
3452 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003453 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003454 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003455 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3456 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003457 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003458
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003459 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003460}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003461
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003462CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3463 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3464 if (!CXXUnit)
3465 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003466
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003467 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3468 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3469}
3470
3471CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3472 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003473 if (!CXXUnit)
3474 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003475
3476 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003477 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3478}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003479
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003480void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3481 CXToken **Tokens, unsigned *NumTokens) {
3482 if (Tokens)
3483 *Tokens = 0;
3484 if (NumTokens)
3485 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003486
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003487 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3488 if (!CXXUnit || !Tokens || !NumTokens)
3489 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003490
Douglas Gregorbdf60622010-03-05 21:16:25 +00003491 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3492
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003493 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003494 if (R.isInvalid())
3495 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003496
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003497 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3498 std::pair<FileID, unsigned> BeginLocInfo
3499 = SourceMgr.getDecomposedLoc(R.getBegin());
3500 std::pair<FileID, unsigned> EndLocInfo
3501 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003502
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003503 // Cannot tokenize across files.
3504 if (BeginLocInfo.first != EndLocInfo.first)
3505 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003506
3507 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003508 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003509 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003510 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003511 if (Invalid)
3512 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003513
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003514 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3515 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003516 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003517 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003518
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003519 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003520 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003521 llvm::SmallVector<CXToken, 32> CXTokens;
3522 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003523 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003524 do {
3525 // Lex the next token
3526 Lex.LexFromRawLexer(Tok);
3527 if (Tok.is(tok::eof))
3528 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003529
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003530 // Initialize the CXToken.
3531 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003532
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003533 // - Common fields
3534 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3535 CXTok.int_data[2] = Tok.getLength();
3536 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003537
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003538 // - Kind-specific fields
3539 if (Tok.isLiteral()) {
3540 CXTok.int_data[0] = CXToken_Literal;
3541 CXTok.ptr_data = (void *)Tok.getLiteralData();
3542 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003543 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003544 std::pair<FileID, unsigned> LocInfo
3545 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003546 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003547 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003548 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3549 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003550 return;
3551
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003552 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003553 IdentifierInfo *II
3554 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003555
David Chisnall096428b2010-10-13 21:44:48 +00003556 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003557 CXTok.int_data[0] = CXToken_Keyword;
3558 }
3559 else {
3560 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3561 CXToken_Identifier
3562 : CXToken_Keyword;
3563 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003564 CXTok.ptr_data = II;
3565 } else if (Tok.is(tok::comment)) {
3566 CXTok.int_data[0] = CXToken_Comment;
3567 CXTok.ptr_data = 0;
3568 } else {
3569 CXTok.int_data[0] = CXToken_Punctuation;
3570 CXTok.ptr_data = 0;
3571 }
3572 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003573 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003574 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003575
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003576 if (CXTokens.empty())
3577 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003578
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003579 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3580 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3581 *NumTokens = CXTokens.size();
3582}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003583
Ted Kremenek6db61092010-05-05 00:55:15 +00003584void clang_disposeTokens(CXTranslationUnit TU,
3585 CXToken *Tokens, unsigned NumTokens) {
3586 free(Tokens);
3587}
3588
3589} // end: extern "C"
3590
3591//===----------------------------------------------------------------------===//
3592// Token annotation APIs.
3593//===----------------------------------------------------------------------===//
3594
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003595typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003596static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3597 CXCursor parent,
3598 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003599namespace {
3600class AnnotateTokensWorker {
3601 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003602 CXToken *Tokens;
3603 CXCursor *Cursors;
3604 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003605 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003606 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003607 CursorVisitor AnnotateVis;
3608 SourceManager &SrcMgr;
3609
3610 bool MoreTokens() const { return TokIdx < NumTokens; }
3611 unsigned NextToken() const { return TokIdx; }
3612 void AdvanceToken() { ++TokIdx; }
3613 SourceLocation GetTokenLoc(unsigned tokI) {
3614 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3615 }
3616
Ted Kremenek6db61092010-05-05 00:55:15 +00003617public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003618 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003619 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3620 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003621 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003622 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003623 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3624 Decl::MaxPCHLevel, RegionOfInterest),
3625 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003626
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003627 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003628 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003629 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003630};
3631}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003632
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003633void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3634 // Walk the AST within the region of interest, annotating tokens
3635 // along the way.
3636 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003637
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003638 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3639 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003640 if (Pos != Annotated.end() &&
3641 (clang_isInvalid(Cursors[I].kind) ||
3642 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003643 Cursors[I] = Pos->second;
3644 }
3645
3646 // Finish up annotating any tokens left.
3647 if (!MoreTokens())
3648 return;
3649
3650 const CXCursor &C = clang_getNullCursor();
3651 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3652 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3653 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003654 }
3655}
3656
Ted Kremenek6db61092010-05-05 00:55:15 +00003657enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003658AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003659 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003660 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003661 if (cursorRange.isInvalid())
3662 return CXChildVisit_Recurse;
3663
Douglas Gregor4419b672010-10-21 06:10:04 +00003664 if (clang_isPreprocessing(cursor.kind)) {
3665 // For macro instantiations, just note where the beginning of the macro
3666 // instantiation occurs.
3667 if (cursor.kind == CXCursor_MacroInstantiation) {
3668 Annotated[Loc.int_data] = cursor;
3669 return CXChildVisit_Recurse;
3670 }
3671
Douglas Gregor4419b672010-10-21 06:10:04 +00003672 // Items in the preprocessing record are kept separate from items in
3673 // declarations, so we keep a separate token index.
3674 unsigned SavedTokIdx = TokIdx;
3675 TokIdx = PreprocessingTokIdx;
3676
3677 // Skip tokens up until we catch up to the beginning of the preprocessing
3678 // entry.
3679 while (MoreTokens()) {
3680 const unsigned I = NextToken();
3681 SourceLocation TokLoc = GetTokenLoc(I);
3682 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3683 case RangeBefore:
3684 AdvanceToken();
3685 continue;
3686 case RangeAfter:
3687 case RangeOverlap:
3688 break;
3689 }
3690 break;
3691 }
3692
3693 // Look at all of the tokens within this range.
3694 while (MoreTokens()) {
3695 const unsigned I = NextToken();
3696 SourceLocation TokLoc = GetTokenLoc(I);
3697 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3698 case RangeBefore:
3699 assert(0 && "Infeasible");
3700 case RangeAfter:
3701 break;
3702 case RangeOverlap:
3703 Cursors[I] = cursor;
3704 AdvanceToken();
3705 continue;
3706 }
3707 break;
3708 }
3709
3710 // Save the preprocessing token index; restore the non-preprocessing
3711 // token index.
3712 PreprocessingTokIdx = TokIdx;
3713 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003714 return CXChildVisit_Recurse;
3715 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003716
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003717 if (cursorRange.isInvalid())
3718 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003719
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003720 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3721
Ted Kremeneka333c662010-05-12 05:29:33 +00003722 // Adjust the annotated range based specific declarations.
3723 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3724 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003725 Decl *D = cxcursor::getCursorDecl(cursor);
3726 // Don't visit synthesized ObjC methods, since they have no syntatic
3727 // representation in the source.
3728 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3729 if (MD->isSynthesized())
3730 return CXChildVisit_Continue;
3731 }
3732 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003733 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3734 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003735 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00003736 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003737 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003738 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003739 }
3740 }
3741 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00003742
Ted Kremenek3f404602010-08-14 01:14:06 +00003743 // If the location of the cursor occurs within a macro instantiation, record
3744 // the spelling location of the cursor in our annotation map. We can then
3745 // paper over the token labelings during a post-processing step to try and
3746 // get cursor mappings for tokens that are the *arguments* of a macro
3747 // instantiation.
3748 if (L.isMacroID()) {
3749 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3750 // Only invalidate the old annotation if it isn't part of a preprocessing
3751 // directive. Here we assume that the default construction of CXCursor
3752 // results in CXCursor.kind being an initialized value (i.e., 0). If
3753 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00003754
Ted Kremenek3f404602010-08-14 01:14:06 +00003755 CXCursor &oldC = Annotated[rawEncoding];
3756 if (!clang_isPreprocessing(oldC.kind))
3757 oldC = cursor;
3758 }
3759
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003760 const enum CXCursorKind K = clang_getCursorKind(parent);
3761 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003762 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3763 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003764
3765 while (MoreTokens()) {
3766 const unsigned I = NextToken();
3767 SourceLocation TokLoc = GetTokenLoc(I);
3768 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3769 case RangeBefore:
3770 Cursors[I] = updateC;
3771 AdvanceToken();
3772 continue;
3773 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003774 case RangeOverlap:
3775 break;
3776 }
3777 break;
3778 }
3779
3780 // Visit children to get their cursor information.
3781 const unsigned BeforeChildren = NextToken();
3782 VisitChildren(cursor);
3783 const unsigned AfterChildren = NextToken();
3784
3785 // Adjust 'Last' to the last token within the extent of the cursor.
3786 while (MoreTokens()) {
3787 const unsigned I = NextToken();
3788 SourceLocation TokLoc = GetTokenLoc(I);
3789 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3790 case RangeBefore:
3791 assert(0 && "Infeasible");
3792 case RangeAfter:
3793 break;
3794 case RangeOverlap:
3795 Cursors[I] = updateC;
3796 AdvanceToken();
3797 continue;
3798 }
3799 break;
3800 }
3801 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003802
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003803 // Scan the tokens that are at the beginning of the cursor, but are not
3804 // capture by the child cursors.
3805
3806 // For AST elements within macros, rely on a post-annotate pass to
3807 // to correctly annotate the tokens with cursors. Otherwise we can
3808 // get confusing results of having tokens that map to cursors that really
3809 // are expanded by an instantiation.
3810 if (L.isMacroID())
3811 cursor = clang_getNullCursor();
3812
3813 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3814 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3815 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00003816
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003817 Cursors[I] = cursor;
3818 }
3819 // Scan the tokens that are at the end of the cursor, but are not captured
3820 // but the child cursors.
3821 for (unsigned I = AfterChildren; I != Last; ++I)
3822 Cursors[I] = cursor;
3823
3824 TokIdx = Last;
3825 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003826}
3827
Ted Kremenek6db61092010-05-05 00:55:15 +00003828static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3829 CXCursor parent,
3830 CXClientData client_data) {
3831 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3832}
3833
3834extern "C" {
3835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003836void clang_annotateTokens(CXTranslationUnit TU,
3837 CXToken *Tokens, unsigned NumTokens,
3838 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003839
3840 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003841 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003842
Douglas Gregor4419b672010-10-21 06:10:04 +00003843 // Any token we don't specifically annotate will have a NULL cursor.
3844 CXCursor C = clang_getNullCursor();
3845 for (unsigned I = 0; I != NumTokens; ++I)
3846 Cursors[I] = C;
3847
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003848 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00003849 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003850 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003851
Douglas Gregorbdf60622010-03-05 21:16:25 +00003852 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003853
Douglas Gregor0396f462010-03-19 05:22:59 +00003854 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003855 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003856 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3857 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003858 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3859 clang_getTokenLocation(TU,
3860 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003861
Douglas Gregor0396f462010-03-19 05:22:59 +00003862 // A mapping from the source locations found when re-lexing or traversing the
3863 // region of interest to the corresponding cursors.
3864 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003865
3866 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003867 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003868 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3869 std::pair<FileID, unsigned> BeginLocInfo
3870 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3871 std::pair<FileID, unsigned> EndLocInfo
3872 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003873
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003874 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003875 bool Invalid = false;
3876 if (BeginLocInfo.first == EndLocInfo.first &&
3877 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3878 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003879 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3880 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003881 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003882 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003883 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003884
3885 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003886 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003887 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003888 Token Tok;
3889 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003890
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003891 reprocess:
3892 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3893 // We have found a preprocessing directive. Gobble it up so that we
3894 // don't see it while preprocessing these tokens later, but keep track of
3895 // all of the token locations inside this preprocessing directive so that
3896 // we can annotate them appropriately.
3897 //
3898 // FIXME: Some simple tests here could identify macro definitions and
3899 // #undefs, to provide specific cursor kinds for those.
3900 std::vector<SourceLocation> Locations;
3901 do {
3902 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003903 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003904 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003905
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003906 using namespace cxcursor;
3907 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003908 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3909 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003910 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003911 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3912 Annotated[Locations[I].getRawEncoding()] = Cursor;
3913 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003914
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003915 if (Tok.isAtStartOfLine())
3916 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003917
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003918 continue;
3919 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003920
Douglas Gregor48072312010-03-18 15:23:44 +00003921 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003922 break;
3923 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003924 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003925
Douglas Gregor0396f462010-03-19 05:22:59 +00003926 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003927 // a specific cursor.
3928 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3929 CXXUnit, RegionOfInterest);
3930 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003931}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003932} // end: extern "C"
3933
3934//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003935// Operations for querying linkage of a cursor.
3936//===----------------------------------------------------------------------===//
3937
3938extern "C" {
3939CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003940 if (!clang_isDeclaration(cursor.kind))
3941 return CXLinkage_Invalid;
3942
Ted Kremenek16b42592010-03-03 06:36:57 +00003943 Decl *D = cxcursor::getCursorDecl(cursor);
3944 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3945 switch (ND->getLinkage()) {
3946 case NoLinkage: return CXLinkage_NoLinkage;
3947 case InternalLinkage: return CXLinkage_Internal;
3948 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3949 case ExternalLinkage: return CXLinkage_External;
3950 };
3951
3952 return CXLinkage_Invalid;
3953}
3954} // end: extern "C"
3955
3956//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003957// Operations for querying language of a cursor.
3958//===----------------------------------------------------------------------===//
3959
3960static CXLanguageKind getDeclLanguage(const Decl *D) {
3961 switch (D->getKind()) {
3962 default:
3963 break;
3964 case Decl::ImplicitParam:
3965 case Decl::ObjCAtDefsField:
3966 case Decl::ObjCCategory:
3967 case Decl::ObjCCategoryImpl:
3968 case Decl::ObjCClass:
3969 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003970 case Decl::ObjCForwardProtocol:
3971 case Decl::ObjCImplementation:
3972 case Decl::ObjCInterface:
3973 case Decl::ObjCIvar:
3974 case Decl::ObjCMethod:
3975 case Decl::ObjCProperty:
3976 case Decl::ObjCPropertyImpl:
3977 case Decl::ObjCProtocol:
3978 return CXLanguage_ObjC;
3979 case Decl::CXXConstructor:
3980 case Decl::CXXConversion:
3981 case Decl::CXXDestructor:
3982 case Decl::CXXMethod:
3983 case Decl::CXXRecord:
3984 case Decl::ClassTemplate:
3985 case Decl::ClassTemplatePartialSpecialization:
3986 case Decl::ClassTemplateSpecialization:
3987 case Decl::Friend:
3988 case Decl::FriendTemplate:
3989 case Decl::FunctionTemplate:
3990 case Decl::LinkageSpec:
3991 case Decl::Namespace:
3992 case Decl::NamespaceAlias:
3993 case Decl::NonTypeTemplateParm:
3994 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003995 case Decl::TemplateTemplateParm:
3996 case Decl::TemplateTypeParm:
3997 case Decl::UnresolvedUsingTypename:
3998 case Decl::UnresolvedUsingValue:
3999 case Decl::Using:
4000 case Decl::UsingDirective:
4001 case Decl::UsingShadow:
4002 return CXLanguage_CPlusPlus;
4003 }
4004
4005 return CXLanguage_C;
4006}
4007
4008extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004009
4010enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4011 if (clang_isDeclaration(cursor.kind))
4012 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4013 if (D->hasAttr<UnavailableAttr>() ||
4014 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4015 return CXAvailability_Available;
4016
4017 if (D->hasAttr<DeprecatedAttr>())
4018 return CXAvailability_Deprecated;
4019 }
4020
4021 return CXAvailability_Available;
4022}
4023
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004024CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4025 if (clang_isDeclaration(cursor.kind))
4026 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4027
4028 return CXLanguage_Invalid;
4029}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004030
4031CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4032 if (clang_isDeclaration(cursor.kind)) {
4033 if (Decl *D = getCursorDecl(cursor)) {
4034 DeclContext *DC = D->getDeclContext();
4035 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4036 }
4037 }
4038
4039 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4040 if (Decl *D = getCursorDecl(cursor))
4041 return MakeCXCursor(D, getCursorASTUnit(cursor));
4042 }
4043
4044 return clang_getNullCursor();
4045}
4046
4047CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4048 if (clang_isDeclaration(cursor.kind)) {
4049 if (Decl *D = getCursorDecl(cursor)) {
4050 DeclContext *DC = D->getLexicalDeclContext();
4051 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4052 }
4053 }
4054
4055 // FIXME: Note that we can't easily compute the lexical context of a
4056 // statement or expression, so we return nothing.
4057 return clang_getNullCursor();
4058}
4059
Douglas Gregor9f592342010-10-01 20:25:15 +00004060static void CollectOverriddenMethods(DeclContext *Ctx,
4061 ObjCMethodDecl *Method,
4062 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4063 if (!Ctx)
4064 return;
4065
4066 // If we have a class or category implementation, jump straight to the
4067 // interface.
4068 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4069 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4070
4071 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4072 if (!Container)
4073 return;
4074
4075 // Check whether we have a matching method at this level.
4076 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4077 Method->isInstanceMethod()))
4078 if (Method != Overridden) {
4079 // We found an override at this level; there is no need to look
4080 // into other protocols or categories.
4081 Methods.push_back(Overridden);
4082 return;
4083 }
4084
4085 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4086 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4087 PEnd = Protocol->protocol_end();
4088 P != PEnd; ++P)
4089 CollectOverriddenMethods(*P, Method, Methods);
4090 }
4091
4092 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4093 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4094 PEnd = Category->protocol_end();
4095 P != PEnd; ++P)
4096 CollectOverriddenMethods(*P, Method, Methods);
4097 }
4098
4099 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4100 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4101 PEnd = Interface->protocol_end();
4102 P != PEnd; ++P)
4103 CollectOverriddenMethods(*P, Method, Methods);
4104
4105 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4106 Category; Category = Category->getNextClassCategory())
4107 CollectOverriddenMethods(Category, Method, Methods);
4108
4109 // We only look into the superclass if we haven't found anything yet.
4110 if (Methods.empty())
4111 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4112 return CollectOverriddenMethods(Super, Method, Methods);
4113 }
4114}
4115
4116void clang_getOverriddenCursors(CXCursor cursor,
4117 CXCursor **overridden,
4118 unsigned *num_overridden) {
4119 if (overridden)
4120 *overridden = 0;
4121 if (num_overridden)
4122 *num_overridden = 0;
4123 if (!overridden || !num_overridden)
4124 return;
4125
4126 if (!clang_isDeclaration(cursor.kind))
4127 return;
4128
4129 Decl *D = getCursorDecl(cursor);
4130 if (!D)
4131 return;
4132
4133 // Handle C++ member functions.
4134 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4135 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4136 *num_overridden = CXXMethod->size_overridden_methods();
4137 if (!*num_overridden)
4138 return;
4139
4140 *overridden = new CXCursor [*num_overridden];
4141 unsigned I = 0;
4142 for (CXXMethodDecl::method_iterator
4143 M = CXXMethod->begin_overridden_methods(),
4144 MEnd = CXXMethod->end_overridden_methods();
4145 M != MEnd; (void)++M, ++I)
4146 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4147 return;
4148 }
4149
4150 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4151 if (!Method)
4152 return;
4153
4154 // Handle Objective-C methods.
4155 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4156 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4157
4158 if (Methods.empty())
4159 return;
4160
4161 *num_overridden = Methods.size();
4162 *overridden = new CXCursor [Methods.size()];
4163 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4164 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4165}
4166
4167void clang_disposeOverriddenCursors(CXCursor *overridden) {
4168 delete [] overridden;
4169}
4170
Douglas Gregorecdcb882010-10-20 22:00:55 +00004171CXFile clang_getIncludedFile(CXCursor cursor) {
4172 if (cursor.kind != CXCursor_InclusionDirective)
4173 return 0;
4174
4175 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4176 return (void *)ID->getFile();
4177}
4178
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004179} // end: extern "C"
4180
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004181
4182//===----------------------------------------------------------------------===//
4183// C++ AST instrospection.
4184//===----------------------------------------------------------------------===//
4185
4186extern "C" {
4187unsigned clang_CXXMethod_isStatic(CXCursor C) {
4188 if (!clang_isDeclaration(C.kind))
4189 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004190
4191 CXXMethodDecl *Method = 0;
4192 Decl *D = cxcursor::getCursorDecl(C);
4193 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4194 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4195 else
4196 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4197 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004198}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004199
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004200} // end: extern "C"
4201
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004202//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004203// Attribute introspection.
4204//===----------------------------------------------------------------------===//
4205
4206extern "C" {
4207CXType clang_getIBOutletCollectionType(CXCursor C) {
4208 if (C.kind != CXCursor_IBOutletCollectionAttr)
4209 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4210
4211 IBOutletCollectionAttr *A =
4212 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4213
4214 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4215}
4216} // end: extern "C"
4217
4218//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004219// CXString Operations.
4220//===----------------------------------------------------------------------===//
4221
4222extern "C" {
4223const char *clang_getCString(CXString string) {
4224 return string.Spelling;
4225}
4226
4227void clang_disposeString(CXString string) {
4228 if (string.MustFreeString && string.Spelling)
4229 free((void*)string.Spelling);
4230}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004231
Ted Kremenekfb480492010-01-13 21:46:36 +00004232} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004233
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004234namespace clang { namespace cxstring {
4235CXString createCXString(const char *String, bool DupString){
4236 CXString Str;
4237 if (DupString) {
4238 Str.Spelling = strdup(String);
4239 Str.MustFreeString = 1;
4240 } else {
4241 Str.Spelling = String;
4242 Str.MustFreeString = 0;
4243 }
4244 return Str;
4245}
4246
4247CXString createCXString(llvm::StringRef String, bool DupString) {
4248 CXString Result;
4249 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4250 char *Spelling = (char *)malloc(String.size() + 1);
4251 memmove(Spelling, String.data(), String.size());
4252 Spelling[String.size()] = 0;
4253 Result.Spelling = Spelling;
4254 Result.MustFreeString = 1;
4255 } else {
4256 Result.Spelling = String.data();
4257 Result.MustFreeString = 0;
4258 }
4259 return Result;
4260}
4261}}
4262
Ted Kremenek04bb7162010-01-22 22:44:15 +00004263//===----------------------------------------------------------------------===//
4264// Misc. utility functions.
4265//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004266
Ted Kremenek04bb7162010-01-22 22:44:15 +00004267extern "C" {
4268
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004269CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004270 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004271}
4272
4273} // end: extern "C"