blob: 9962bd21517752ae1cbc82485c2de8b3f1a3670b [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000045#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000046
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.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000106 if (EndLoc.isValid() && EndLoc.isMacroID())
107 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000108 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000109 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 EndLoc = EndLoc.getFileLocWithOffset(Length);
111 }
112
113 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
114 R.getBegin().getRawEncoding(),
115 EndLoc.getRawEncoding() };
116 return Result;
117}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000118
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000119//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000120// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
122
Steve Naroff89922f82009-08-31 00:59:03 +0000123namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000124
125class VisitorJob {
126public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000127 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000128 TypeLocVisitKind, OverloadExprPartsKind,
129 DeclRefExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000130protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000131 void *dataA;
132 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000133 CXCursor parent;
134 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000135 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
136 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000137public:
138 Kind getKind() const { return K; }
139 const CXCursor &getParent() const { return parent; }
140 static bool classof(VisitorJob *VJ) { return true; }
141};
142
143typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
144
Douglas Gregorb1373d02010-01-20 20:59:29 +0000145// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000146class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000147 public TypeLocVisitor<CursorVisitor, bool>,
148 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000149{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000150 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000151 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000152
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000153 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000154 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000155
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000156 /// \brief The declaration that serves at the parent of any statement or
157 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000158 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000159
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000160 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000161 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000162
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000163 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000164 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000165
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000166 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
167 // to the visitor. Declarations with a PCH level greater than this value will
168 // be suppressed.
169 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170
171 /// \brief When valid, a source range to which the cursor should restrict
172 /// its search.
173 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000175 // FIXME: Eventually remove. This part of a hack to support proper
176 // iteration over all Decls contained lexically within an ObjC container.
177 DeclContext::decl_iterator *DI_current;
178 DeclContext::decl_iterator DE_current;
179
Douglas Gregorb1373d02010-01-20 20:59:29 +0000180 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000181 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000182 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
184 /// \brief Determine whether this particular source range comes before, comes
185 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000186 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000187 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000188 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
189
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000190 class SetParentRAII {
191 CXCursor &Parent;
192 Decl *&StmtParent;
193 CXCursor OldParent;
194
195 public:
196 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
197 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
198 {
199 Parent = NewParent;
200 if (clang_isDeclaration(Parent.kind))
201 StmtParent = getCursorDecl(Parent);
202 }
203
204 ~SetParentRAII() {
205 Parent = OldParent;
206 if (clang_isDeclaration(Parent.kind))
207 StmtParent = getCursorDecl(Parent);
208 }
209 };
210
Steve Naroff89922f82009-08-31 00:59:03 +0000211public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000212 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
213 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000216 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
217 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000218 {
219 Parent.kind = CXCursor_NoDeclFound;
220 Parent.data[0] = 0;
221 Parent.data[1] = 0;
222 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000223 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000224 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000225
Ted Kremenekab979612010-11-11 08:05:23 +0000226 ASTUnit *getASTUnit() const { return TU; }
227
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000228 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000229
230 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
231 getPreprocessedEntities();
232
Douglas Gregorb1373d02010-01-20 20:59:29 +0000233 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000234
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000235 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000236 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000237 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000238 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000239 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000240 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000241 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
242 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000243 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000244 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000245 bool VisitClassTemplatePartialSpecializationDecl(
246 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000247 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000248 bool VisitEnumConstantDecl(EnumConstantDecl *D);
249 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
250 bool VisitFunctionDecl(FunctionDecl *ND);
251 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000252 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000253 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000254 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000255 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000256 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000257 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
258 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
259 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
260 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000261 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000262 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
263 bool VisitObjCImplDecl(ObjCImplDecl *D);
264 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
265 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000266 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
267 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
268 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000269 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000270 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000271 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000272 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000273 bool VisitUsingDecl(UsingDecl *D);
274 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
275 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000276
Douglas Gregor01829d32010-08-31 14:41:23 +0000277 // Name visitor
278 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000279 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000280
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000281 // Template visitors
282 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000283 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000284 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
285
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000286 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000287 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000288 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000289 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000290 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
291 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000292 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000293 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000294 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000295 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
296 bool VisitPointerTypeLoc(PointerTypeLoc TL);
297 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
298 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
299 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
300 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000301 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000302 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000303 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000304 // FIXME: Implement visitors here when the unimplemented TypeLocs get
305 // implemented
306 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
307 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000308
Douglas Gregora59e3902010-01-21 23:27:09 +0000309 // Statement visitors
310 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000311
Douglas Gregor336fd812010-01-23 00:40:08 +0000312 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000313 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000314 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000315 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000316 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
317 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000318 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000319 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000320 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000321 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000322 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000323 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000324 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000325 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000326 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000327
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000328 // Data-recursive visitor functions.
329 bool IsInRegionOfInterest(CXCursor C);
330 bool RunVisitorWorkList(VisitorWorkList &WL);
331 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenek37f1ea02010-11-15 23:11:54 +0000332 bool VisitDataRecursive(Stmt *S) LLVM_ATTRIBUTE_NOINLINE;
Steve Naroff89922f82009-08-31 00:59:03 +0000333};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000334
Ted Kremenekab188932010-01-05 19:32:54 +0000335} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000336
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000337static SourceRange getRawCursorExtent(CXCursor C);
338
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000339RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000340 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
341}
342
Douglas Gregorb1373d02010-01-20 20:59:29 +0000343/// \brief Visit the given cursor and, if requested by the visitor,
344/// its children.
345///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000346/// \param Cursor the cursor to visit.
347///
348/// \param CheckRegionOfInterest if true, then the caller already checked that
349/// this cursor is within the region of interest.
350///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000351/// \returns true if the visitation should be aborted, false if it
352/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000353bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000354 if (clang_isInvalid(Cursor.kind))
355 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000356
Douglas Gregorb1373d02010-01-20 20:59:29 +0000357 if (clang_isDeclaration(Cursor.kind)) {
358 Decl *D = getCursorDecl(Cursor);
359 assert(D && "Invalid declaration cursor");
360 if (D->getPCHLevel() > MaxPCHLevel)
361 return false;
362
363 if (D->isImplicit())
364 return false;
365 }
366
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367 // If we have a range of interest, and this cursor doesn't intersect with it,
368 // we're done.
369 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000370 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000371 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372 return false;
373 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000374
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 switch (Visitor(Cursor, Parent, ClientData)) {
376 case CXChildVisit_Break:
377 return true;
378
379 case CXChildVisit_Continue:
380 return false;
381
382 case CXChildVisit_Recurse:
383 return VisitChildren(Cursor);
384 }
385
Douglas Gregorfd643772010-01-25 16:45:46 +0000386 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000387}
388
Douglas Gregor788f5a12010-03-20 00:41:21 +0000389std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
390CursorVisitor::getPreprocessedEntities() {
391 PreprocessingRecord &PPRec
392 = *TU->getPreprocessor().getPreprocessingRecord();
393
394 bool OnlyLocalDecls
395 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
396
397 // There is no region of interest; we have to walk everything.
398 if (RegionOfInterest.isInvalid())
399 return std::make_pair(PPRec.begin(OnlyLocalDecls),
400 PPRec.end(OnlyLocalDecls));
401
402 // Find the file in which the region of interest lands.
403 SourceManager &SM = TU->getSourceManager();
404 std::pair<FileID, unsigned> Begin
405 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
406 std::pair<FileID, unsigned> End
407 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
408
409 // The region of interest spans files; we have to walk everything.
410 if (Begin.first != End.first)
411 return std::make_pair(PPRec.begin(OnlyLocalDecls),
412 PPRec.end(OnlyLocalDecls));
413
414 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
415 = TU->getPreprocessedEntitiesByFile();
416 if (ByFileMap.empty()) {
417 // Build the mapping from files to sets of preprocessed entities.
418 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
419 EEnd = PPRec.end(OnlyLocalDecls);
420 E != EEnd; ++E) {
421 std::pair<FileID, unsigned> P
422 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
423 ByFileMap[P.first].push_back(*E);
424 }
425 }
426
427 return std::make_pair(ByFileMap[Begin.first].begin(),
428 ByFileMap[Begin.first].end());
429}
430
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431/// \brief Visit the children of the given cursor.
432///
433/// \returns true if the visitation should be aborted, false if it
434/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000435bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000436 if (clang_isReference(Cursor.kind)) {
437 // By definition, references have no children.
438 return false;
439 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000440
441 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000443 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 if (clang_isDeclaration(Cursor.kind)) {
446 Decl *D = getCursorDecl(Cursor);
447 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000448 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000449 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000450
Douglas Gregora59e3902010-01-21 23:27:09 +0000451 if (clang_isStatement(Cursor.kind))
452 return Visit(getCursorStmt(Cursor));
453 if (clang_isExpression(Cursor.kind))
454 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000457 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000458 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
459 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000460 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
461 TLEnd = CXXUnit->top_level_end();
462 TL != TLEnd; ++TL) {
463 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000464 return true;
465 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000466 } else if (VisitDeclContext(
467 CXXUnit->getASTContext().getTranslationUnitDecl()))
468 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000469
Douglas Gregor0396f462010-03-19 05:22:59 +0000470 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000471 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000472 // FIXME: Once we have the ability to deserialize a preprocessing record,
473 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000474 PreprocessingRecord::iterator E, EEnd;
475 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000476 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
477 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
478 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000479
Douglas Gregor0396f462010-03-19 05:22:59 +0000480 continue;
481 }
482
483 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
484 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
485 return true;
486
487 continue;
488 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000489
490 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
491 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
492 return true;
493
494 continue;
495 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 }
497 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000498 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000499 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 return false;
503}
504
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000505bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000506 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
507 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000508
Ted Kremenek664cffd2010-07-22 11:30:19 +0000509 if (Stmt *Body = B->getBody())
510 return Visit(MakeCXCursor(Body, StmtParent, TU));
511
512 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000513}
514
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000515llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
516 if (RegionOfInterest.isValid()) {
517 SourceRange Range = getRawCursorExtent(Cursor);
518 if (Range.isInvalid())
519 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000520
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000521 switch (CompareRegionOfInterest(Range)) {
522 case RangeBefore:
523 // This declaration comes before the region of interest; skip it.
524 return llvm::Optional<bool>();
525
526 case RangeAfter:
527 // This declaration comes after the region of interest; we're done.
528 return false;
529
530 case RangeOverlap:
531 // This declaration overlaps the region of interest; visit it.
532 break;
533 }
534 }
535 return true;
536}
537
538bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
539 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
540
541 // FIXME: Eventually remove. This part of a hack to support proper
542 // iteration over all Decls contained lexically within an ObjC container.
543 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
544 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
545
546 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000547 Decl *D = *I;
548 if (D->getLexicalDeclContext() != DC)
549 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000550 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000551 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
552 if (!V.hasValue())
553 continue;
554 if (!V.getValue())
555 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000556 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 return true;
558 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000560}
561
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000562bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
563 llvm_unreachable("Translation units are visited directly by Visit()");
564 return false;
565}
566
567bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
568 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
569 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000570
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000571 return false;
572}
573
574bool CursorVisitor::VisitTagDecl(TagDecl *D) {
575 return VisitDeclContext(D);
576}
577
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000578bool CursorVisitor::VisitClassTemplateSpecializationDecl(
579 ClassTemplateSpecializationDecl *D) {
580 bool ShouldVisitBody = false;
581 switch (D->getSpecializationKind()) {
582 case TSK_Undeclared:
583 case TSK_ImplicitInstantiation:
584 // Nothing to visit
585 return false;
586
587 case TSK_ExplicitInstantiationDeclaration:
588 case TSK_ExplicitInstantiationDefinition:
589 break;
590
591 case TSK_ExplicitSpecialization:
592 ShouldVisitBody = true;
593 break;
594 }
595
596 // Visit the template arguments used in the specialization.
597 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
598 TypeLoc TL = SpecType->getTypeLoc();
599 if (TemplateSpecializationTypeLoc *TSTLoc
600 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
601 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
602 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
603 return true;
604 }
605 }
606
607 if (ShouldVisitBody && VisitCXXRecordDecl(D))
608 return true;
609
610 return false;
611}
612
Douglas Gregor74dbe642010-08-31 19:31:58 +0000613bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
614 ClassTemplatePartialSpecializationDecl *D) {
615 // FIXME: Visit the "outer" template parameter lists on the TagDecl
616 // before visiting these template parameters.
617 if (VisitTemplateParameters(D->getTemplateParameters()))
618 return true;
619
620 // Visit the partial specialization arguments.
621 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
622 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
623 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
624 return true;
625
626 return VisitCXXRecordDecl(D);
627}
628
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000629bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000630 // Visit the default argument.
631 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
632 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
633 if (Visit(DefArg->getTypeLoc()))
634 return true;
635
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000636 return false;
637}
638
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000639bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
640 if (Expr *Init = D->getInitExpr())
641 return Visit(MakeCXCursor(Init, StmtParent, TU));
642 return false;
643}
644
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000645bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
646 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
647 if (Visit(TSInfo->getTypeLoc()))
648 return true;
649
650 return false;
651}
652
Douglas Gregora67e03f2010-09-09 21:42:20 +0000653/// \brief Compare two base or member initializers based on their source order.
654static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
655 CXXBaseOrMemberInitializer const * const *X
656 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
657 CXXBaseOrMemberInitializer const * const *Y
658 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
659
660 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
661 return -1;
662 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
663 return 1;
664 else
665 return 0;
666}
667
Douglas Gregorb1373d02010-01-20 20:59:29 +0000668bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000669 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
670 // Visit the function declaration's syntactic components in the order
671 // written. This requires a bit of work.
672 TypeLoc TL = TSInfo->getTypeLoc();
673 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
674
675 // If we have a function declared directly (without the use of a typedef),
676 // visit just the return type. Otherwise, just visit the function's type
677 // now.
678 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
679 (!FTL && Visit(TL)))
680 return true;
681
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000682 // Visit the nested-name-specifier, if present.
683 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
684 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
685 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000686
687 // Visit the declaration name.
688 if (VisitDeclarationNameInfo(ND->getNameInfo()))
689 return true;
690
691 // FIXME: Visit explicitly-specified template arguments!
692
693 // Visit the function parameters, if we have a function type.
694 if (FTL && VisitFunctionTypeLoc(*FTL, true))
695 return true;
696
697 // FIXME: Attributes?
698 }
699
Douglas Gregora67e03f2010-09-09 21:42:20 +0000700 if (ND->isThisDeclarationADefinition()) {
701 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
702 // Find the initializers that were written in the source.
703 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
704 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
705 IEnd = Constructor->init_end();
706 I != IEnd; ++I) {
707 if (!(*I)->isWritten())
708 continue;
709
710 WrittenInits.push_back(*I);
711 }
712
713 // Sort the initializers in source order
714 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
715 &CompareCXXBaseOrMemberInitializers);
716
717 // Visit the initializers in source order
718 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
719 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
720 if (Init->isMemberInitializer()) {
721 if (Visit(MakeCursorMemberRef(Init->getMember(),
722 Init->getMemberLocation(), TU)))
723 return true;
724 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
725 if (Visit(BaseInfo->getTypeLoc()))
726 return true;
727 }
728
729 // Visit the initializer value.
730 if (Expr *Initializer = Init->getInit())
731 if (Visit(MakeCXCursor(Initializer, ND, TU)))
732 return true;
733 }
734 }
735
736 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
737 return true;
738 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000739
Douglas Gregorb1373d02010-01-20 20:59:29 +0000740 return false;
741}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000742
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000743bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
744 if (VisitDeclaratorDecl(D))
745 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000746
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000747 if (Expr *BitWidth = D->getBitWidth())
748 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000749
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000750 return false;
751}
752
753bool CursorVisitor::VisitVarDecl(VarDecl *D) {
754 if (VisitDeclaratorDecl(D))
755 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000756
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000757 if (Expr *Init = D->getInit())
758 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000759
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000760 return false;
761}
762
Douglas Gregor84b51d72010-09-01 20:16:53 +0000763bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
764 if (VisitDeclaratorDecl(D))
765 return true;
766
767 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
768 if (Expr *DefArg = D->getDefaultArgument())
769 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
770
771 return false;
772}
773
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000774bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
775 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
776 // before visiting these template parameters.
777 if (VisitTemplateParameters(D->getTemplateParameters()))
778 return true;
779
780 return VisitFunctionDecl(D->getTemplatedDecl());
781}
782
Douglas Gregor39d6f072010-08-31 19:02:00 +0000783bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
784 // FIXME: Visit the "outer" template parameter lists on the TagDecl
785 // before visiting these template parameters.
786 if (VisitTemplateParameters(D->getTemplateParameters()))
787 return true;
788
789 return VisitCXXRecordDecl(D->getTemplatedDecl());
790}
791
Douglas Gregor84b51d72010-09-01 20:16:53 +0000792bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
793 if (VisitTemplateParameters(D->getTemplateParameters()))
794 return true;
795
796 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
797 VisitTemplateArgumentLoc(D->getDefaultArgument()))
798 return true;
799
800 return false;
801}
802
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000803bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000804 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
805 if (Visit(TSInfo->getTypeLoc()))
806 return true;
807
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000808 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000809 PEnd = ND->param_end();
810 P != PEnd; ++P) {
811 if (Visit(MakeCXCursor(*P, TU)))
812 return true;
813 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815 if (ND->isThisDeclarationADefinition() &&
816 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
817 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000818
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000819 return false;
820}
821
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000822namespace {
823 struct ContainerDeclsSort {
824 SourceManager &SM;
825 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
826 bool operator()(Decl *A, Decl *B) {
827 SourceLocation L_A = A->getLocStart();
828 SourceLocation L_B = B->getLocStart();
829 assert(L_A.isValid() && L_B.isValid());
830 return SM.isBeforeInTranslationUnit(L_A, L_B);
831 }
832 };
833}
834
Douglas Gregora59e3902010-01-21 23:27:09 +0000835bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000836 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
837 // an @implementation can lexically contain Decls that are not properly
838 // nested in the AST. When we identify such cases, we need to retrofit
839 // this nesting here.
840 if (!DI_current)
841 return VisitDeclContext(D);
842
843 // Scan the Decls that immediately come after the container
844 // in the current DeclContext. If any fall within the
845 // container's lexical region, stash them into a vector
846 // for later processing.
847 llvm::SmallVector<Decl *, 24> DeclsInContainer;
848 SourceLocation EndLoc = D->getSourceRange().getEnd();
849 SourceManager &SM = TU->getSourceManager();
850 if (EndLoc.isValid()) {
851 DeclContext::decl_iterator next = *DI_current;
852 while (++next != DE_current) {
853 Decl *D_next = *next;
854 if (!D_next)
855 break;
856 SourceLocation L = D_next->getLocStart();
857 if (!L.isValid())
858 break;
859 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
860 *DI_current = next;
861 DeclsInContainer.push_back(D_next);
862 continue;
863 }
864 break;
865 }
866 }
867
868 // The common case.
869 if (DeclsInContainer.empty())
870 return VisitDeclContext(D);
871
872 // Get all the Decls in the DeclContext, and sort them with the
873 // additional ones we've collected. Then visit them.
874 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
875 I!=E; ++I) {
876 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000877 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
878 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000879 continue;
880 DeclsInContainer.push_back(subDecl);
881 }
882
883 // Now sort the Decls so that they appear in lexical order.
884 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
885 ContainerDeclsSort(SM));
886
887 // Now visit the decls.
888 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
889 E = DeclsInContainer.end(); I != E; ++I) {
890 CXCursor Cursor = MakeCXCursor(*I, TU);
891 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
892 if (!V.hasValue())
893 continue;
894 if (!V.getValue())
895 return false;
896 if (Visit(Cursor, true))
897 return true;
898 }
899 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000900}
901
Douglas Gregorb1373d02010-01-20 20:59:29 +0000902bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000903 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
904 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000905 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000906
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000907 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
908 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
909 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000910 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000911 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000912
Douglas Gregora59e3902010-01-21 23:27:09 +0000913 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000914}
915
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000916bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
917 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
918 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
919 E = PID->protocol_end(); I != E; ++I, ++PL)
920 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
921 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000922
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000923 return VisitObjCContainerDecl(PID);
924}
925
Ted Kremenek23173d72010-05-18 21:09:07 +0000926bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000927 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000928 return true;
929
Ted Kremenek23173d72010-05-18 21:09:07 +0000930 // FIXME: This implements a workaround with @property declarations also being
931 // installed in the DeclContext for the @interface. Eventually this code
932 // should be removed.
933 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
934 if (!CDecl || !CDecl->IsClassExtension())
935 return false;
936
937 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
938 if (!ID)
939 return false;
940
941 IdentifierInfo *PropertyId = PD->getIdentifier();
942 ObjCPropertyDecl *prevDecl =
943 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
944
945 if (!prevDecl)
946 return false;
947
948 // Visit synthesized methods since they will be skipped when visiting
949 // the @interface.
950 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000951 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000952 if (Visit(MakeCXCursor(MD, TU)))
953 return true;
954
955 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000956 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000957 if (Visit(MakeCXCursor(MD, TU)))
958 return true;
959
960 return false;
961}
962
Douglas Gregorb1373d02010-01-20 20:59:29 +0000963bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000964 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000965 if (D->getSuperClass() &&
966 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000967 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000968 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000969 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000970
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000971 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
972 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
973 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000974 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000975 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000976
Douglas Gregora59e3902010-01-21 23:27:09 +0000977 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000978}
979
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000980bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
981 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000982}
983
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000984bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000985 // 'ID' could be null when dealing with invalid code.
986 if (ObjCInterfaceDecl *ID = D->getClassInterface())
987 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
988 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000990 return VisitObjCImplDecl(D);
991}
992
993bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
994#if 0
995 // Issue callbacks for super class.
996 // FIXME: No source location information!
997 if (D->getSuperClass() &&
998 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001000 TU)))
1001 return true;
1002#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001003
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001004 return VisitObjCImplDecl(D);
1005}
1006
1007bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1008 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1009 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1010 E = D->protocol_end();
1011 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001012 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
1015 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001016}
1017
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1019 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1020 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1021 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001023 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001024}
1025
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001026bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1027 return VisitDeclContext(D);
1028}
1029
Douglas Gregor69319002010-08-31 23:48:11 +00001030bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001031 // Visit nested-name-specifier.
1032 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1033 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1034 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001035
1036 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1037 D->getTargetNameLoc(), TU));
1038}
1039
Douglas Gregor7e242562010-09-01 19:52:22 +00001040bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001041 // Visit nested-name-specifier.
1042 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1043 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1044 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001045
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001046 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1047 return true;
1048
Douglas Gregor7e242562010-09-01 19:52:22 +00001049 return VisitDeclarationNameInfo(D->getNameInfo());
1050}
1051
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001052bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001053 // Visit nested-name-specifier.
1054 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1055 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1056 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001057
1058 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1059 D->getIdentLocation(), TU));
1060}
1061
Douglas Gregor7e242562010-09-01 19:52:22 +00001062bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001063 // Visit nested-name-specifier.
1064 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1065 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1066 return true;
1067
Douglas Gregor7e242562010-09-01 19:52:22 +00001068 return VisitDeclarationNameInfo(D->getNameInfo());
1069}
1070
1071bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1072 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001073 // Visit nested-name-specifier.
1074 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1075 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1076 return true;
1077
Douglas Gregor7e242562010-09-01 19:52:22 +00001078 return false;
1079}
1080
Douglas Gregor01829d32010-08-31 14:41:23 +00001081bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1082 switch (Name.getName().getNameKind()) {
1083 case clang::DeclarationName::Identifier:
1084 case clang::DeclarationName::CXXLiteralOperatorName:
1085 case clang::DeclarationName::CXXOperatorName:
1086 case clang::DeclarationName::CXXUsingDirective:
1087 return false;
1088
1089 case clang::DeclarationName::CXXConstructorName:
1090 case clang::DeclarationName::CXXDestructorName:
1091 case clang::DeclarationName::CXXConversionFunctionName:
1092 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1093 return Visit(TSInfo->getTypeLoc());
1094 return false;
1095
1096 case clang::DeclarationName::ObjCZeroArgSelector:
1097 case clang::DeclarationName::ObjCOneArgSelector:
1098 case clang::DeclarationName::ObjCMultiArgSelector:
1099 // FIXME: Per-identifier location info?
1100 return false;
1101 }
1102
1103 return false;
1104}
1105
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1107 SourceRange Range) {
1108 // FIXME: This whole routine is a hack to work around the lack of proper
1109 // source information in nested-name-specifiers (PR5791). Since we do have
1110 // a beginning source location, we can visit the first component of the
1111 // nested-name-specifier, if it's a single-token component.
1112 if (!NNS)
1113 return false;
1114
1115 // Get the first component in the nested-name-specifier.
1116 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1117 NNS = Prefix;
1118
1119 switch (NNS->getKind()) {
1120 case NestedNameSpecifier::Namespace:
1121 // FIXME: The token at this source location might actually have been a
1122 // namespace alias, but we don't model that. Lame!
1123 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1124 TU));
1125
1126 case NestedNameSpecifier::TypeSpec: {
1127 // If the type has a form where we know that the beginning of the source
1128 // range matches up with a reference cursor. Visit the appropriate reference
1129 // cursor.
1130 Type *T = NNS->getAsType();
1131 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1132 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1133 if (const TagType *Tag = dyn_cast<TagType>(T))
1134 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1135 if (const TemplateSpecializationType *TST
1136 = dyn_cast<TemplateSpecializationType>(T))
1137 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1138 break;
1139 }
1140
1141 case NestedNameSpecifier::TypeSpecWithTemplate:
1142 case NestedNameSpecifier::Global:
1143 case NestedNameSpecifier::Identifier:
1144 break;
1145 }
1146
1147 return false;
1148}
1149
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001150bool CursorVisitor::VisitTemplateParameters(
1151 const TemplateParameterList *Params) {
1152 if (!Params)
1153 return false;
1154
1155 for (TemplateParameterList::const_iterator P = Params->begin(),
1156 PEnd = Params->end();
1157 P != PEnd; ++P) {
1158 if (Visit(MakeCXCursor(*P, TU)))
1159 return true;
1160 }
1161
1162 return false;
1163}
1164
Douglas Gregor0b36e612010-08-31 20:37:03 +00001165bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1166 switch (Name.getKind()) {
1167 case TemplateName::Template:
1168 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1169
1170 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001171 // Visit the overloaded template set.
1172 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1173 return true;
1174
Douglas Gregor0b36e612010-08-31 20:37:03 +00001175 return false;
1176
1177 case TemplateName::DependentTemplate:
1178 // FIXME: Visit nested-name-specifier.
1179 return false;
1180
1181 case TemplateName::QualifiedTemplate:
1182 // FIXME: Visit nested-name-specifier.
1183 return Visit(MakeCursorTemplateRef(
1184 Name.getAsQualifiedTemplateName()->getDecl(),
1185 Loc, TU));
1186 }
1187
1188 return false;
1189}
1190
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001191bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1192 switch (TAL.getArgument().getKind()) {
1193 case TemplateArgument::Null:
1194 case TemplateArgument::Integral:
1195 return false;
1196
1197 case TemplateArgument::Pack:
1198 // FIXME: Implement when variadic templates come along.
1199 return false;
1200
1201 case TemplateArgument::Type:
1202 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1203 return Visit(TSInfo->getTypeLoc());
1204 return false;
1205
1206 case TemplateArgument::Declaration:
1207 if (Expr *E = TAL.getSourceDeclExpression())
1208 return Visit(MakeCXCursor(E, StmtParent, TU));
1209 return false;
1210
1211 case TemplateArgument::Expression:
1212 if (Expr *E = TAL.getSourceExpression())
1213 return Visit(MakeCXCursor(E, StmtParent, TU));
1214 return false;
1215
1216 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001217 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1218 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001219 }
1220
1221 return false;
1222}
1223
Ted Kremeneka0536d82010-05-07 01:04:29 +00001224bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1225 return VisitDeclContext(D);
1226}
1227
Douglas Gregor01829d32010-08-31 14:41:23 +00001228bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1229 return Visit(TL.getUnqualifiedLoc());
1230}
1231
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001232bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1233 ASTContext &Context = TU->getASTContext();
1234
1235 // Some builtin types (such as Objective-C's "id", "sel", and
1236 // "Class") have associated declarations. Create cursors for those.
1237 QualType VisitType;
1238 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001239 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001240 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001241 case BuiltinType::Char_U:
1242 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001243 case BuiltinType::Char16:
1244 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001245 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001246 case BuiltinType::UInt:
1247 case BuiltinType::ULong:
1248 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001249 case BuiltinType::UInt128:
1250 case BuiltinType::Char_S:
1251 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001252 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001253 case BuiltinType::Short:
1254 case BuiltinType::Int:
1255 case BuiltinType::Long:
1256 case BuiltinType::LongLong:
1257 case BuiltinType::Int128:
1258 case BuiltinType::Float:
1259 case BuiltinType::Double:
1260 case BuiltinType::LongDouble:
1261 case BuiltinType::NullPtr:
1262 case BuiltinType::Overload:
1263 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001264 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001265
1266 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001268
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001269 case BuiltinType::ObjCId:
1270 VisitType = Context.getObjCIdType();
1271 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001272
1273 case BuiltinType::ObjCClass:
1274 VisitType = Context.getObjCClassType();
1275 break;
1276
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001277 case BuiltinType::ObjCSel:
1278 VisitType = Context.getObjCSelType();
1279 break;
1280 }
1281
1282 if (!VisitType.isNull()) {
1283 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001284 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001285 TU));
1286 }
1287
1288 return false;
1289}
1290
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001291bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1292 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1293}
1294
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001295bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1296 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1297}
1298
1299bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1300 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1301}
1302
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001303bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001304 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001305 // no context information with which we can match up the depth/index in the
1306 // type to the appropriate
1307 return false;
1308}
1309
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001310bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1311 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1312 return true;
1313
John McCallc12c5bb2010-05-15 11:32:37 +00001314 return false;
1315}
1316
1317bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1318 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1319 return true;
1320
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001321 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1322 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1323 TU)))
1324 return true;
1325 }
1326
1327 return false;
1328}
1329
1330bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001331 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001332}
1333
1334bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1335 return Visit(TL.getPointeeLoc());
1336}
1337
1338bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1339 return Visit(TL.getPointeeLoc());
1340}
1341
1342bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1343 return Visit(TL.getPointeeLoc());
1344}
1345
1346bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001347 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348}
1349
1350bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001351 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001352}
1353
Douglas Gregor01829d32010-08-31 14:41:23 +00001354bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1355 bool SkipResultType) {
1356 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001357 return true;
1358
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001360 if (Decl *D = TL.getArg(I))
1361 if (Visit(MakeCXCursor(D, TU)))
1362 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001363
1364 return false;
1365}
1366
1367bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1368 if (Visit(TL.getElementLoc()))
1369 return true;
1370
1371 if (Expr *Size = TL.getSizeExpr())
1372 return Visit(MakeCXCursor(Size, StmtParent, TU));
1373
1374 return false;
1375}
1376
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001377bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1378 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001379 // Visit the template name.
1380 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1381 TL.getTemplateNameLoc()))
1382 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001383
1384 // Visit the template arguments.
1385 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1386 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1387 return true;
1388
1389 return false;
1390}
1391
Douglas Gregor2332c112010-01-21 20:48:56 +00001392bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1393 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1394}
1395
1396bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1397 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1398 return Visit(TSInfo->getTypeLoc());
1399
1400 return false;
1401}
1402
Douglas Gregora59e3902010-01-21 23:27:09 +00001403bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001404 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001405}
1406
Ted Kremenek3064ef92010-08-27 21:34:58 +00001407bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1408 if (D->isDefinition()) {
1409 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1410 E = D->bases_end(); I != E; ++I) {
1411 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1412 return true;
1413 }
1414 }
1415
1416 return VisitTagDecl(D);
1417}
1418
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001419bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001420 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001421 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1422 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001423
1424 // Visit the components of the offsetof expression.
1425 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1426 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1427 const OffsetOfNode &Node = E->getComponent(I);
1428 switch (Node.getKind()) {
1429 case OffsetOfNode::Array:
1430 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1431 StmtParent, TU)))
1432 return true;
1433 break;
1434
1435 case OffsetOfNode::Field:
1436 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1437 TU)))
1438 return true;
1439 break;
1440
1441 case OffsetOfNode::Identifier:
1442 case OffsetOfNode::Base:
1443 continue;
1444 }
1445 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001446
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001447 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001448}
1449
Douglas Gregor336fd812010-01-23 00:40:08 +00001450bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1451 if (E->isArgumentType()) {
1452 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1453 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454
Douglas Gregor336fd812010-01-23 00:40:08 +00001455 return false;
1456 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001457
Douglas Gregor336fd812010-01-23 00:40:08 +00001458 return VisitExpr(E);
1459}
1460
Douglas Gregor36897b02010-09-10 00:22:18 +00001461bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1462 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1463}
1464
Douglas Gregor648220e2010-08-10 15:02:34 +00001465bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1466 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1467 Visit(E->getArgTInfo2()->getTypeLoc());
1468}
1469
1470bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1471 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1472 return true;
1473
1474 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1475}
1476
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001477bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1478 // Visit the designators.
1479 typedef DesignatedInitExpr::Designator Designator;
1480 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1481 DEnd = E->designators_end();
1482 D != DEnd; ++D) {
1483 if (D->isFieldDesignator()) {
1484 if (FieldDecl *Field = D->getField())
1485 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1486 return true;
1487
1488 continue;
1489 }
1490
1491 if (D->isArrayDesignator()) {
1492 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1493 return true;
1494
1495 continue;
1496 }
1497
1498 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1499 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1500 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1501 return true;
1502 }
1503
1504 // Visit the initializer value itself.
1505 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1506}
1507
Douglas Gregor94802292010-09-02 21:20:16 +00001508bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1509 if (E->isTypeOperand()) {
1510 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1511 return Visit(TSInfo->getTypeLoc());
1512
1513 return false;
1514 }
1515
1516 return VisitExpr(E);
1517}
1518
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001519bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1520 if (E->isTypeOperand()) {
1521 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1522 return Visit(TSInfo->getTypeLoc());
1523
1524 return false;
1525 }
1526
1527 return VisitExpr(E);
1528}
1529
Douglas Gregorab6677e2010-09-08 00:15:04 +00001530bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1531 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1532 return Visit(TSInfo->getTypeLoc());
1533
1534 return false;
1535}
1536
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001537bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1538 // Visit base expression.
1539 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1540 return true;
1541
1542 // Visit the nested-name-specifier.
1543 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1544 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1545 return true;
1546
1547 // Visit the scope type that looks disturbingly like the nested-name-specifier
1548 // but isn't.
1549 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1550 if (Visit(TSInfo->getTypeLoc()))
1551 return true;
1552
1553 // Visit the name of the type being destroyed.
1554 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1555 if (Visit(TSInfo->getTypeLoc()))
1556 return true;
1557
1558 return false;
1559}
1560
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001561bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1562 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1563}
1564
Douglas Gregorbfebed22010-09-03 17:24:10 +00001565bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1566 DependentScopeDeclRefExpr *E) {
1567 // Visit the nested-name-specifier.
1568 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1569 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1570 return true;
1571
1572 // Visit the declaration name.
1573 if (VisitDeclarationNameInfo(E->getNameInfo()))
1574 return true;
1575
1576 // Visit the explicitly-specified template arguments.
1577 if (const ExplicitTemplateArgumentList *ArgList
1578 = E->getOptionalExplicitTemplateArgs()) {
1579 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1580 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1581 Arg != ArgEnd; ++Arg) {
1582 if (VisitTemplateArgumentLoc(*Arg))
1583 return true;
1584 }
1585 }
1586
1587 return false;
1588}
1589
Douglas Gregorab6677e2010-09-08 00:15:04 +00001590bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1591 CXXUnresolvedConstructExpr *E) {
1592 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1593 if (Visit(TSInfo->getTypeLoc()))
1594 return true;
1595
1596 return VisitExpr(E);
1597}
1598
Douglas Gregor25d63622010-09-03 17:35:34 +00001599bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1600 CXXDependentScopeMemberExpr *E) {
1601 // Visit the base expression, if there is one.
1602 if (!E->isImplicitAccess() &&
1603 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1604 return true;
1605
1606 // Visit the nested-name-specifier.
1607 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1608 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1609 return true;
1610
1611 // Visit the declaration name.
1612 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1613 return true;
1614
1615 // Visit the explicitly-specified template arguments.
1616 if (const ExplicitTemplateArgumentList *ArgList
1617 = E->getOptionalExplicitTemplateArgs()) {
1618 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1619 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1620 Arg != ArgEnd; ++Arg) {
1621 if (VisitTemplateArgumentLoc(*Arg))
1622 return true;
1623 }
1624 }
1625
1626 return false;
1627}
1628
Ted Kremenek09dfa372010-02-18 05:46:33 +00001629bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001630 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1631 i != e; ++i)
1632 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001633 return true;
1634
1635 return false;
1636}
1637
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001638//===----------------------------------------------------------------------===//
1639// Data-recursive visitor methods.
1640//===----------------------------------------------------------------------===//
1641
Ted Kremenek28a71942010-11-13 00:36:47 +00001642namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001643#define DEF_JOB(NAME, DATA, KIND)\
1644class NAME : public VisitorJob {\
1645public:\
1646 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1647 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1648 DATA *get() const { return static_cast<DATA*>(dataA); }\
1649};
1650
1651DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1652DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001653DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001654DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1655#undef DEF_JOB
1656
1657class DeclVisit : public VisitorJob {
1658public:
1659 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1660 VisitorJob(parent, VisitorJob::DeclVisitKind,
1661 d, isFirst ? (void*) 1 : (void*) 0) {}
1662 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001663 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001664 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001665 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001666 bool isFirst() const { return dataB ? true : false; }
1667};
1668
1669class TypeLocVisit : public VisitorJob {
1670public:
1671 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1672 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1673 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1674
1675 static bool classof(const VisitorJob *VJ) {
1676 return VJ->getKind() == TypeLocVisitKind;
1677 }
1678
Ted Kremenek82f3c502010-11-15 22:23:26 +00001679 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001680 QualType T = QualType::getFromOpaquePtr(dataA);
1681 return TypeLoc(T, dataB);
1682 }
1683};
1684
Ted Kremenek28a71942010-11-13 00:36:47 +00001685class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1686 VisitorWorkList &WL;
1687 CXCursor Parent;
1688public:
1689 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1690 : WL(wl), Parent(parent) {}
1691
Ted Kremenek73d15c42010-11-13 01:09:29 +00001692 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001693 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001694 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001695 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1696 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001697 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001698 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001699 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001700 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001701 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1702 void VisitForStmt(ForStmt *FS);
1703 void VisitIfStmt(IfStmt *If);
1704 void VisitInitListExpr(InitListExpr *IE);
1705 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001706 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001707 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1708 void VisitOverloadExpr(OverloadExpr *E);
1709 void VisitStmt(Stmt *S);
1710 void VisitSwitchStmt(SwitchStmt *S);
1711 void VisitWhileStmt(WhileStmt *W);
1712 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1713
1714private:
1715 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001716 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001717 void AddTypeLoc(TypeSourceInfo *TI);
1718 void EnqueueChildren(Stmt *S);
1719};
1720} // end anonyous namespace
1721
1722void EnqueueVisitor::AddStmt(Stmt *S) {
1723 if (S)
1724 WL.push_back(StmtVisit(S, Parent));
1725}
Ted Kremenek035dc412010-11-13 00:36:50 +00001726void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001727 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001728 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001729}
1730void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1731 if (TI)
1732 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1733 }
1734void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001735 unsigned size = WL.size();
1736 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1737 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001738 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001739 }
1740 if (size == WL.size())
1741 return;
1742 // Now reverse the entries we just added. This will match the DFS
1743 // ordering performed by the worklist.
1744 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1745 std::reverse(I, E);
1746}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001747void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1748 AddDecl(B->getBlockDecl());
1749}
Ted Kremenek28a71942010-11-13 00:36:47 +00001750void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1751 EnqueueChildren(E);
1752 AddTypeLoc(E->getTypeSourceInfo());
1753}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001754void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1755 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1756 E = S->body_rend(); I != E; ++I) {
1757 AddStmt(*I);
1758 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001759}
1760void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1761 // Enqueue the initializer or constructor arguments.
1762 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1763 AddStmt(E->getConstructorArg(I-1));
1764 // Enqueue the array size, if any.
1765 AddStmt(E->getArraySize());
1766 // Enqueue the allocated type.
1767 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1768 // Enqueue the placement arguments.
1769 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1770 AddStmt(E->getPlacementArg(I-1));
1771}
Ted Kremenek28a71942010-11-13 00:36:47 +00001772void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001773 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1774 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001775 AddStmt(CE->getCallee());
1776 AddStmt(CE->getArg(0));
1777}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001778void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1779 EnqueueChildren(E);
1780 AddTypeLoc(E->getTypeSourceInfo());
1781}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001782void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1783 WL.push_back(DeclRefExprParts(DR, Parent));
1784}
Ted Kremenek035dc412010-11-13 00:36:50 +00001785void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1786 unsigned size = WL.size();
1787 bool isFirst = true;
1788 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1789 D != DEnd; ++D) {
1790 AddDecl(*D, isFirst);
1791 isFirst = false;
1792 }
1793 if (size == WL.size())
1794 return;
1795 // Now reverse the entries we just added. This will match the DFS
1796 // ordering performed by the worklist.
1797 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1798 std::reverse(I, E);
1799}
Ted Kremenek28a71942010-11-13 00:36:47 +00001800void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1801 EnqueueChildren(E);
1802 AddTypeLoc(E->getTypeInfoAsWritten());
1803}
1804void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1805 AddStmt(FS->getBody());
1806 AddStmt(FS->getInc());
1807 AddStmt(FS->getCond());
1808 AddDecl(FS->getConditionVariable());
1809 AddStmt(FS->getInit());
1810}
1811void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1812 AddStmt(If->getElse());
1813 AddStmt(If->getThen());
1814 AddStmt(If->getCond());
1815 AddDecl(If->getConditionVariable());
1816}
1817void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1818 // We care about the syntactic form of the initializer list, only.
1819 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1820 IE = Syntactic;
1821 EnqueueChildren(IE);
1822}
1823void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1824 WL.push_back(MemberExprParts(M, Parent));
1825 AddStmt(M->getBase());
1826}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001827void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1828 AddTypeLoc(E->getEncodedTypeSourceInfo());
1829}
Ted Kremenek28a71942010-11-13 00:36:47 +00001830void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1831 EnqueueChildren(M);
1832 AddTypeLoc(M->getClassReceiverTypeInfo());
1833}
1834void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001835 WL.push_back(OverloadExprParts(E, Parent));
1836}
Ted Kremenek28a71942010-11-13 00:36:47 +00001837void EnqueueVisitor::VisitStmt(Stmt *S) {
1838 EnqueueChildren(S);
1839}
1840void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1841 AddStmt(S->getBody());
1842 AddStmt(S->getCond());
1843 AddDecl(S->getConditionVariable());
1844}
1845void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1846 AddStmt(W->getBody());
1847 AddStmt(W->getCond());
1848 AddDecl(W->getConditionVariable());
1849}
1850void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1851 VisitOverloadExpr(U);
1852 if (!U->isImplicitAccess())
1853 AddStmt(U->getBase());
1854}
Ted Kremenek60458782010-11-12 21:34:16 +00001855
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001856void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001857 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001858}
1859
1860bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1861 if (RegionOfInterest.isValid()) {
1862 SourceRange Range = getRawCursorExtent(C);
1863 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1864 return false;
1865 }
1866 return true;
1867}
1868
1869bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1870 while (!WL.empty()) {
1871 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001872 VisitorJob LI = WL.back();
1873 WL.pop_back();
1874
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001875 // Set the Parent field, then back to its old value once we're done.
1876 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1877
1878 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001879 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001880 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001881 if (!D)
1882 continue;
1883
1884 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001885 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001886 return true;
1887
1888 continue;
1889 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001890 case VisitorJob::TypeLocVisitKind: {
1891 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001892 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001893 return true;
1894 continue;
1895 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001896 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001897 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001898 if (!S)
1899 continue;
1900
Ted Kremenekf1107452010-11-12 18:26:56 +00001901 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001902 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1903
1904 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001905 case Stmt::GotoStmtClass: {
1906 GotoStmt *GS = cast<GotoStmt>(S);
1907 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1908 GS->getLabelLoc(), TU))) {
1909 return true;
1910 }
1911 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001912 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001913 // Cases not yet handled by the data-recursion
1914 // algorithm.
1915 case Stmt::OffsetOfExprClass:
1916 case Stmt::SizeOfAlignOfExprClass:
1917 case Stmt::AddrLabelExprClass:
1918 case Stmt::TypesCompatibleExprClass:
1919 case Stmt::VAArgExprClass:
1920 case Stmt::DesignatedInitExprClass:
1921 case Stmt::CXXTypeidExprClass:
1922 case Stmt::CXXUuidofExprClass:
1923 case Stmt::CXXScalarValueInitExprClass:
1924 case Stmt::CXXPseudoDestructorExprClass:
1925 case Stmt::UnaryTypeTraitExprClass:
1926 case Stmt::DependentScopeDeclRefExprClass:
1927 case Stmt::CXXUnresolvedConstructExprClass:
1928 case Stmt::CXXDependentScopeMemberExprClass:
1929 if (Visit(Cursor))
1930 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001931 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001932 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001933 if (!IsInRegionOfInterest(Cursor))
1934 continue;
1935 switch (Visitor(Cursor, Parent, ClientData)) {
1936 case CXChildVisit_Break:
1937 return true;
1938 case CXChildVisit_Continue:
1939 break;
1940 case CXChildVisit_Recurse:
1941 EnqueueWorkList(WL, S);
1942 break;
1943 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001944 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001945 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001946 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001947 }
1948 case VisitorJob::MemberExprPartsKind: {
1949 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001950 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001951
1952 // Visit the nested-name-specifier
1953 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1954 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1955 return true;
1956
1957 // Visit the declaration name.
1958 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1959 return true;
1960
1961 // Visit the explicitly-specified template arguments, if any.
1962 if (M->hasExplicitTemplateArgs()) {
1963 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1964 *ArgEnd = Arg + M->getNumTemplateArgs();
1965 Arg != ArgEnd; ++Arg) {
1966 if (VisitTemplateArgumentLoc(*Arg))
1967 return true;
1968 }
1969 }
1970 continue;
1971 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001972 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001973 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001974 // Visit nested-name-specifier, if present.
1975 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
1976 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
1977 return true;
1978 // Visit declaration name.
1979 if (VisitDeclarationNameInfo(DR->getNameInfo()))
1980 return true;
1981 // Visit explicitly-specified template arguments.
1982 if (DR->hasExplicitTemplateArgs()) {
1983 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
1984 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1985 *ArgEnd = Arg + Args.NumTemplateArgs;
1986 Arg != ArgEnd; ++Arg)
1987 if (VisitTemplateArgumentLoc(*Arg))
1988 return true;
1989 }
1990 continue;
1991 }
Ted Kremenek60458782010-11-12 21:34:16 +00001992 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001993 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00001994 // Visit the nested-name-specifier.
1995 if (NestedNameSpecifier *Qualifier = O->getQualifier())
1996 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
1997 return true;
1998 // Visit the declaration name.
1999 if (VisitDeclarationNameInfo(O->getNameInfo()))
2000 return true;
2001 // Visit the overloaded declaration reference.
2002 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2003 return true;
2004 // Visit the explicitly-specified template arguments.
2005 if (const ExplicitTemplateArgumentList *ArgList
2006 = O->getOptionalExplicitTemplateArgs()) {
2007 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2008 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2009 Arg != ArgEnd; ++Arg) {
2010 if (VisitTemplateArgumentLoc(*Arg))
2011 return true;
2012 }
2013 }
2014 continue;
2015 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002016 }
2017 }
2018 return false;
2019}
2020
2021bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2022 VisitorWorkList WL;
2023 EnqueueWorkList(WL, S);
2024 return RunVisitorWorkList(WL);
2025}
2026
2027//===----------------------------------------------------------------------===//
2028// Misc. API hooks.
2029//===----------------------------------------------------------------------===//
2030
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002031static llvm::sys::Mutex EnableMultithreadingMutex;
2032static bool EnabledMultithreading;
2033
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002034extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002035CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2036 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002037 // Disable pretty stack trace functionality, which will otherwise be a very
2038 // poor citizen of the world and set up all sorts of signal handlers.
2039 llvm::DisablePrettyStackTrace = true;
2040
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002041 // We use crash recovery to make some of our APIs more reliable, implicitly
2042 // enable it.
2043 llvm::CrashRecoveryContext::Enable();
2044
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002045 // Enable support for multithreading in LLVM.
2046 {
2047 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2048 if (!EnabledMultithreading) {
2049 llvm::llvm_start_multithreaded();
2050 EnabledMultithreading = true;
2051 }
2052 }
2053
Douglas Gregora030b7c2010-01-22 20:35:53 +00002054 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002055 if (excludeDeclarationsFromPCH)
2056 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002057 if (displayDiagnostics)
2058 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002059 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002060}
2061
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002062void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002063 if (CIdx)
2064 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002065}
2066
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002067CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002068 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002069 if (!CIdx)
2070 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002071
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002072 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002073 FileSystemOptions FileSystemOpts;
2074 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002075
Douglas Gregor28019772010-04-05 23:52:57 +00002076 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002077 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002078 CXXIdx->getOnlyLocalDecls(),
2079 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002080}
2081
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002082unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002083 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002084 CXTranslationUnit_CacheCompletionResults |
2085 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002086}
2087
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002088CXTranslationUnit
2089clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2090 const char *source_filename,
2091 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002092 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002093 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002094 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002095 return clang_parseTranslationUnit(CIdx, source_filename,
2096 command_line_args, num_command_line_args,
2097 unsaved_files, num_unsaved_files,
2098 CXTranslationUnit_DetailedPreprocessingRecord);
2099}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002100
2101struct ParseTranslationUnitInfo {
2102 CXIndex CIdx;
2103 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002104 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002105 int num_command_line_args;
2106 struct CXUnsavedFile *unsaved_files;
2107 unsigned num_unsaved_files;
2108 unsigned options;
2109 CXTranslationUnit result;
2110};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002111static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002112 ParseTranslationUnitInfo *PTUI =
2113 static_cast<ParseTranslationUnitInfo*>(UserData);
2114 CXIndex CIdx = PTUI->CIdx;
2115 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002116 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002117 int num_command_line_args = PTUI->num_command_line_args;
2118 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2119 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2120 unsigned options = PTUI->options;
2121 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002122
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002123 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002124 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002125
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002126 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2127
Douglas Gregor44c181a2010-07-23 00:33:23 +00002128 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002129 bool CompleteTranslationUnit
2130 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002131 bool CacheCodeCompetionResults
2132 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002133 bool CXXPrecompilePreamble
2134 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2135 bool CXXChainedPCH
2136 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002137
Douglas Gregor5352ac02010-01-28 00:27:43 +00002138 // Configure the diagnostics.
2139 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002140 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2141 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002142
Douglas Gregor4db64a42010-01-23 00:14:00 +00002143 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2144 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002145 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002146 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002147 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002148 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2149 Buffer));
2150 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002151
Douglas Gregorb10daed2010-10-11 16:52:23 +00002152 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002153
Ted Kremenek139ba862009-10-22 00:03:57 +00002154 // The 'source_filename' argument is optional. If the caller does not
2155 // specify it then it is assumed that the source file is specified
2156 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002157 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002158 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002159
2160 // Since the Clang C library is primarily used by batch tools dealing with
2161 // (often very broken) source code, where spell-checking can have a
2162 // significant negative impact on performance (particularly when
2163 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002164 // Only do this if we haven't found a spell-checking-related argument.
2165 bool FoundSpellCheckingArgument = false;
2166 for (int I = 0; I != num_command_line_args; ++I) {
2167 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2168 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2169 FoundSpellCheckingArgument = true;
2170 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002171 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002172 }
2173 if (!FoundSpellCheckingArgument)
2174 Args.push_back("-fno-spell-checking");
2175
2176 Args.insert(Args.end(), command_line_args,
2177 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002178
Douglas Gregor44c181a2010-07-23 00:33:23 +00002179 // Do we need the detailed preprocessing record?
2180 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002181 Args.push_back("-Xclang");
2182 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002183 }
2184
Douglas Gregorb10daed2010-10-11 16:52:23 +00002185 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002186 llvm::OwningPtr<ASTUnit> Unit(
2187 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2188 Diags,
2189 CXXIdx->getClangResourcesPath(),
2190 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002191 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002192 RemappedFiles.data(),
2193 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002194 PrecompilePreamble,
2195 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002196 CacheCodeCompetionResults,
2197 CXXPrecompilePreamble,
2198 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002199
Douglas Gregorb10daed2010-10-11 16:52:23 +00002200 if (NumErrors != Diags->getNumErrors()) {
2201 // Make sure to check that 'Unit' is non-NULL.
2202 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2203 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2204 DEnd = Unit->stored_diag_end();
2205 D != DEnd; ++D) {
2206 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2207 CXString Msg = clang_formatDiagnostic(&Diag,
2208 clang_defaultDiagnosticDisplayOptions());
2209 fprintf(stderr, "%s\n", clang_getCString(Msg));
2210 clang_disposeString(Msg);
2211 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002212#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002213 // On Windows, force a flush, since there may be multiple copies of
2214 // stderr and stdout in the file system, all with different buffers
2215 // but writing to the same device.
2216 fflush(stderr);
2217#endif
2218 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002219 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002220
Douglas Gregorb10daed2010-10-11 16:52:23 +00002221 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002222}
2223CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2224 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002225 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002226 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002227 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002228 unsigned num_unsaved_files,
2229 unsigned options) {
2230 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002231 num_command_line_args, unsaved_files,
2232 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002233 llvm::CrashRecoveryContext CRC;
2234
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002235 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002236 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2237 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2238 fprintf(stderr, " 'command_line_args' : [");
2239 for (int i = 0; i != num_command_line_args; ++i) {
2240 if (i)
2241 fprintf(stderr, ", ");
2242 fprintf(stderr, "'%s'", command_line_args[i]);
2243 }
2244 fprintf(stderr, "],\n");
2245 fprintf(stderr, " 'unsaved_files' : [");
2246 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2247 if (i)
2248 fprintf(stderr, ", ");
2249 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2250 unsaved_files[i].Length);
2251 }
2252 fprintf(stderr, "],\n");
2253 fprintf(stderr, " 'options' : %d,\n", options);
2254 fprintf(stderr, "}\n");
2255
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002256 return 0;
2257 }
2258
2259 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002260}
2261
Douglas Gregor19998442010-08-13 15:35:05 +00002262unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2263 return CXSaveTranslationUnit_None;
2264}
2265
2266int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2267 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002268 if (!TU)
2269 return 1;
2270
2271 return static_cast<ASTUnit *>(TU)->Save(FileName);
2272}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002273
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002274void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002275 if (CTUnit) {
2276 // If the translation unit has been marked as unsafe to free, just discard
2277 // it.
2278 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2279 return;
2280
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002281 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002282 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002283}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002284
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002285unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2286 return CXReparse_None;
2287}
2288
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002289struct ReparseTranslationUnitInfo {
2290 CXTranslationUnit TU;
2291 unsigned num_unsaved_files;
2292 struct CXUnsavedFile *unsaved_files;
2293 unsigned options;
2294 int result;
2295};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002296
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002297static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002298 ReparseTranslationUnitInfo *RTUI =
2299 static_cast<ReparseTranslationUnitInfo*>(UserData);
2300 CXTranslationUnit TU = RTUI->TU;
2301 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2302 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2303 unsigned options = RTUI->options;
2304 (void) options;
2305 RTUI->result = 1;
2306
Douglas Gregorabc563f2010-07-19 21:46:24 +00002307 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002308 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002309
2310 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2311 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002312
2313 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2314 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2315 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2316 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002317 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002318 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2319 Buffer));
2320 }
2321
Douglas Gregor593b0c12010-09-23 18:47:53 +00002322 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2323 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002324}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002325
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002326int clang_reparseTranslationUnit(CXTranslationUnit TU,
2327 unsigned num_unsaved_files,
2328 struct CXUnsavedFile *unsaved_files,
2329 unsigned options) {
2330 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2331 options, 0 };
2332 llvm::CrashRecoveryContext CRC;
2333
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002334 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002335 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002336 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2337 return 1;
2338 }
2339
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002340
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002341 return RTUI.result;
2342}
2343
Douglas Gregordf95a132010-08-09 20:45:32 +00002344
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002345CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002346 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002347 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002348
Steve Naroff77accc12009-09-03 18:19:54 +00002349 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002350 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002351}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002352
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002353CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002354 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002355 return Result;
2356}
2357
Ted Kremenekfb480492010-01-13 21:46:36 +00002358} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002359
Ted Kremenekfb480492010-01-13 21:46:36 +00002360//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002361// CXSourceLocation and CXSourceRange Operations.
2362//===----------------------------------------------------------------------===//
2363
Douglas Gregorb9790342010-01-22 21:44:22 +00002364extern "C" {
2365CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002366 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002367 return Result;
2368}
2369
2370unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002371 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2372 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2373 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002374}
2375
2376CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2377 CXFile file,
2378 unsigned line,
2379 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002380 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002381 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002382
Douglas Gregorb9790342010-01-22 21:44:22 +00002383 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2384 SourceLocation SLoc
2385 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002386 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002387 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002388 if (SLoc.isInvalid()) return clang_getNullLocation();
2389
2390 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2391}
2392
2393CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2394 CXFile file,
2395 unsigned offset) {
2396 if (!tu || !file)
2397 return clang_getNullLocation();
2398
2399 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2400 SourceLocation Start
2401 = CXXUnit->getSourceManager().getLocation(
2402 static_cast<const FileEntry *>(file),
2403 1, 1);
2404 if (Start.isInvalid()) return clang_getNullLocation();
2405
2406 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2407
2408 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002409
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002410 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002411}
2412
Douglas Gregor5352ac02010-01-28 00:27:43 +00002413CXSourceRange clang_getNullRange() {
2414 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2415 return Result;
2416}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002417
Douglas Gregor5352ac02010-01-28 00:27:43 +00002418CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2419 if (begin.ptr_data[0] != end.ptr_data[0] ||
2420 begin.ptr_data[1] != end.ptr_data[1])
2421 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002422
2423 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002424 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002425 return Result;
2426}
2427
Douglas Gregor46766dc2010-01-26 19:19:08 +00002428void clang_getInstantiationLocation(CXSourceLocation location,
2429 CXFile *file,
2430 unsigned *line,
2431 unsigned *column,
2432 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002433 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2434
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002435 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002436 if (file)
2437 *file = 0;
2438 if (line)
2439 *line = 0;
2440 if (column)
2441 *column = 0;
2442 if (offset)
2443 *offset = 0;
2444 return;
2445 }
2446
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002447 const SourceManager &SM =
2448 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002449 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002450
2451 if (file)
2452 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2453 if (line)
2454 *line = SM.getInstantiationLineNumber(InstLoc);
2455 if (column)
2456 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002457 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002458 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002459}
2460
Douglas Gregora9b06d42010-11-09 06:24:54 +00002461void clang_getSpellingLocation(CXSourceLocation location,
2462 CXFile *file,
2463 unsigned *line,
2464 unsigned *column,
2465 unsigned *offset) {
2466 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2467
2468 if (!location.ptr_data[0] || Loc.isInvalid()) {
2469 if (file)
2470 *file = 0;
2471 if (line)
2472 *line = 0;
2473 if (column)
2474 *column = 0;
2475 if (offset)
2476 *offset = 0;
2477 return;
2478 }
2479
2480 const SourceManager &SM =
2481 *static_cast<const SourceManager*>(location.ptr_data[0]);
2482 SourceLocation SpellLoc = Loc;
2483 if (SpellLoc.isMacroID()) {
2484 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2485 if (SimpleSpellingLoc.isFileID() &&
2486 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2487 SpellLoc = SimpleSpellingLoc;
2488 else
2489 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2490 }
2491
2492 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2493 FileID FID = LocInfo.first;
2494 unsigned FileOffset = LocInfo.second;
2495
2496 if (file)
2497 *file = (void *)SM.getFileEntryForID(FID);
2498 if (line)
2499 *line = SM.getLineNumber(FID, FileOffset);
2500 if (column)
2501 *column = SM.getColumnNumber(FID, FileOffset);
2502 if (offset)
2503 *offset = FileOffset;
2504}
2505
Douglas Gregor1db19de2010-01-19 21:36:55 +00002506CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002507 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002508 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002509 return Result;
2510}
2511
2512CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002513 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002514 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002515 return Result;
2516}
2517
Douglas Gregorb9790342010-01-22 21:44:22 +00002518} // end: extern "C"
2519
Douglas Gregor1db19de2010-01-19 21:36:55 +00002520//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002521// CXFile Operations.
2522//===----------------------------------------------------------------------===//
2523
2524extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002525CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002526 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002527 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002528
Steve Naroff88145032009-10-27 14:35:18 +00002529 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002530 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002531}
2532
2533time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002534 if (!SFile)
2535 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002536
Steve Naroff88145032009-10-27 14:35:18 +00002537 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2538 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002539}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002540
Douglas Gregorb9790342010-01-22 21:44:22 +00002541CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2542 if (!tu)
2543 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002544
Douglas Gregorb9790342010-01-22 21:44:22 +00002545 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002546
Douglas Gregorb9790342010-01-22 21:44:22 +00002547 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002548 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2549 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002550 return const_cast<FileEntry *>(File);
2551}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002552
Ted Kremenekfb480492010-01-13 21:46:36 +00002553} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002554
Ted Kremenekfb480492010-01-13 21:46:36 +00002555//===----------------------------------------------------------------------===//
2556// CXCursor Operations.
2557//===----------------------------------------------------------------------===//
2558
Ted Kremenekfb480492010-01-13 21:46:36 +00002559static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002560 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2561 return getDeclFromExpr(CE->getSubExpr());
2562
Ted Kremenekfb480492010-01-13 21:46:36 +00002563 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2564 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002565 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2566 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002567 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2568 return ME->getMemberDecl();
2569 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2570 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002571 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2572 return PRE->getProperty();
2573
Ted Kremenekfb480492010-01-13 21:46:36 +00002574 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2575 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002576 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2577 if (!CE->isElidable())
2578 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002579 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2580 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Douglas Gregordb1314e2010-10-01 21:11:22 +00002582 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2583 return PE->getProtocol();
2584
Ted Kremenekfb480492010-01-13 21:46:36 +00002585 return 0;
2586}
2587
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002588static SourceLocation getLocationFromExpr(Expr *E) {
2589 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2590 return /*FIXME:*/Msg->getLeftLoc();
2591 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2592 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002593 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2594 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002595 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2596 return Member->getMemberLoc();
2597 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2598 return Ivar->getLocation();
2599 return E->getLocStart();
2600}
2601
Ted Kremenekfb480492010-01-13 21:46:36 +00002602extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002603
2604unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002605 CXCursorVisitor visitor,
2606 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002607 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002608
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002609 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2610 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002611 return CursorVis.VisitChildren(parent);
2612}
2613
David Chisnall3387c652010-11-03 14:12:26 +00002614#ifndef __has_feature
2615#define __has_feature(x) 0
2616#endif
2617#if __has_feature(blocks)
2618typedef enum CXChildVisitResult
2619 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2620
2621static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2622 CXClientData client_data) {
2623 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2624 return block(cursor, parent);
2625}
2626#else
2627// If we are compiled with a compiler that doesn't have native blocks support,
2628// define and call the block manually, so the
2629typedef struct _CXChildVisitResult
2630{
2631 void *isa;
2632 int flags;
2633 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002634 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2635 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002636} *CXCursorVisitorBlock;
2637
2638static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2639 CXClientData client_data) {
2640 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2641 return block->invoke(block, cursor, parent);
2642}
2643#endif
2644
2645
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002646unsigned clang_visitChildrenWithBlock(CXCursor parent,
2647 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002648 return clang_visitChildren(parent, visitWithBlock, block);
2649}
2650
Douglas Gregor78205d42010-01-20 21:45:58 +00002651static CXString getDeclSpelling(Decl *D) {
2652 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2653 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002654 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002655
Douglas Gregor78205d42010-01-20 21:45:58 +00002656 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002657 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002658
Douglas Gregor78205d42010-01-20 21:45:58 +00002659 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2660 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2661 // and returns different names. NamedDecl returns the class name and
2662 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002663 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002664
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002665 if (isa<UsingDirectiveDecl>(D))
2666 return createCXString("");
2667
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002668 llvm::SmallString<1024> S;
2669 llvm::raw_svector_ostream os(S);
2670 ND->printName(os);
2671
2672 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002673}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002674
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002675CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002676 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002677 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002678
Steve Narofff334b4e2009-09-02 18:26:48 +00002679 if (clang_isReference(C.kind)) {
2680 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002681 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002682 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002683 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002684 }
2685 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002686 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002687 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002688 }
2689 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002690 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002691 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002692 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002693 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002694 case CXCursor_CXXBaseSpecifier: {
2695 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2696 return createCXString(B->getType().getAsString());
2697 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002698 case CXCursor_TypeRef: {
2699 TypeDecl *Type = getCursorTypeRef(C).first;
2700 assert(Type && "Missing type decl");
2701
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002702 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2703 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002704 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002705 case CXCursor_TemplateRef: {
2706 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002707 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002708
2709 return createCXString(Template->getNameAsString());
2710 }
Douglas Gregor69319002010-08-31 23:48:11 +00002711
2712 case CXCursor_NamespaceRef: {
2713 NamedDecl *NS = getCursorNamespaceRef(C).first;
2714 assert(NS && "Missing namespace decl");
2715
2716 return createCXString(NS->getNameAsString());
2717 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002718
Douglas Gregora67e03f2010-09-09 21:42:20 +00002719 case CXCursor_MemberRef: {
2720 FieldDecl *Field = getCursorMemberRef(C).first;
2721 assert(Field && "Missing member decl");
2722
2723 return createCXString(Field->getNameAsString());
2724 }
2725
Douglas Gregor36897b02010-09-10 00:22:18 +00002726 case CXCursor_LabelRef: {
2727 LabelStmt *Label = getCursorLabelRef(C).first;
2728 assert(Label && "Missing label");
2729
2730 return createCXString(Label->getID()->getName());
2731 }
2732
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002733 case CXCursor_OverloadedDeclRef: {
2734 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2735 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2736 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2737 return createCXString(ND->getNameAsString());
2738 return createCXString("");
2739 }
2740 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2741 return createCXString(E->getName().getAsString());
2742 OverloadedTemplateStorage *Ovl
2743 = Storage.get<OverloadedTemplateStorage*>();
2744 if (Ovl->size() == 0)
2745 return createCXString("");
2746 return createCXString((*Ovl->begin())->getNameAsString());
2747 }
2748
Daniel Dunbaracca7252009-11-30 20:42:49 +00002749 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002750 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002751 }
2752 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002753
2754 if (clang_isExpression(C.kind)) {
2755 Decl *D = getDeclFromExpr(getCursorExpr(C));
2756 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002757 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002758 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002759 }
2760
Douglas Gregor36897b02010-09-10 00:22:18 +00002761 if (clang_isStatement(C.kind)) {
2762 Stmt *S = getCursorStmt(C);
2763 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2764 return createCXString(Label->getID()->getName());
2765
2766 return createCXString("");
2767 }
2768
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002769 if (C.kind == CXCursor_MacroInstantiation)
2770 return createCXString(getCursorMacroInstantiation(C)->getName()
2771 ->getNameStart());
2772
Douglas Gregor572feb22010-03-18 18:04:21 +00002773 if (C.kind == CXCursor_MacroDefinition)
2774 return createCXString(getCursorMacroDefinition(C)->getName()
2775 ->getNameStart());
2776
Douglas Gregorecdcb882010-10-20 22:00:55 +00002777 if (C.kind == CXCursor_InclusionDirective)
2778 return createCXString(getCursorInclusionDirective(C)->getFileName());
2779
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002780 if (clang_isDeclaration(C.kind))
2781 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002782
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002783 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002784}
2785
Douglas Gregor358559d2010-10-02 22:49:11 +00002786CXString clang_getCursorDisplayName(CXCursor C) {
2787 if (!clang_isDeclaration(C.kind))
2788 return clang_getCursorSpelling(C);
2789
2790 Decl *D = getCursorDecl(C);
2791 if (!D)
2792 return createCXString("");
2793
2794 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2795 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2796 D = FunTmpl->getTemplatedDecl();
2797
2798 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2799 llvm::SmallString<64> Str;
2800 llvm::raw_svector_ostream OS(Str);
2801 OS << Function->getNameAsString();
2802 if (Function->getPrimaryTemplate())
2803 OS << "<>";
2804 OS << "(";
2805 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2806 if (I)
2807 OS << ", ";
2808 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2809 }
2810
2811 if (Function->isVariadic()) {
2812 if (Function->getNumParams())
2813 OS << ", ";
2814 OS << "...";
2815 }
2816 OS << ")";
2817 return createCXString(OS.str());
2818 }
2819
2820 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2821 llvm::SmallString<64> Str;
2822 llvm::raw_svector_ostream OS(Str);
2823 OS << ClassTemplate->getNameAsString();
2824 OS << "<";
2825 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2826 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2827 if (I)
2828 OS << ", ";
2829
2830 NamedDecl *Param = Params->getParam(I);
2831 if (Param->getIdentifier()) {
2832 OS << Param->getIdentifier()->getName();
2833 continue;
2834 }
2835
2836 // There is no parameter name, which makes this tricky. Try to come up
2837 // with something useful that isn't too long.
2838 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2839 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2840 else if (NonTypeTemplateParmDecl *NTTP
2841 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2842 OS << NTTP->getType().getAsString(Policy);
2843 else
2844 OS << "template<...> class";
2845 }
2846
2847 OS << ">";
2848 return createCXString(OS.str());
2849 }
2850
2851 if (ClassTemplateSpecializationDecl *ClassSpec
2852 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2853 // If the type was explicitly written, use that.
2854 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2855 return createCXString(TSInfo->getType().getAsString(Policy));
2856
2857 llvm::SmallString<64> Str;
2858 llvm::raw_svector_ostream OS(Str);
2859 OS << ClassSpec->getNameAsString();
2860 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002861 ClassSpec->getTemplateArgs().data(),
2862 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002863 Policy);
2864 return createCXString(OS.str());
2865 }
2866
2867 return clang_getCursorSpelling(C);
2868}
2869
Ted Kremeneke68fff62010-02-17 00:41:32 +00002870CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002871 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002872 case CXCursor_FunctionDecl:
2873 return createCXString("FunctionDecl");
2874 case CXCursor_TypedefDecl:
2875 return createCXString("TypedefDecl");
2876 case CXCursor_EnumDecl:
2877 return createCXString("EnumDecl");
2878 case CXCursor_EnumConstantDecl:
2879 return createCXString("EnumConstantDecl");
2880 case CXCursor_StructDecl:
2881 return createCXString("StructDecl");
2882 case CXCursor_UnionDecl:
2883 return createCXString("UnionDecl");
2884 case CXCursor_ClassDecl:
2885 return createCXString("ClassDecl");
2886 case CXCursor_FieldDecl:
2887 return createCXString("FieldDecl");
2888 case CXCursor_VarDecl:
2889 return createCXString("VarDecl");
2890 case CXCursor_ParmDecl:
2891 return createCXString("ParmDecl");
2892 case CXCursor_ObjCInterfaceDecl:
2893 return createCXString("ObjCInterfaceDecl");
2894 case CXCursor_ObjCCategoryDecl:
2895 return createCXString("ObjCCategoryDecl");
2896 case CXCursor_ObjCProtocolDecl:
2897 return createCXString("ObjCProtocolDecl");
2898 case CXCursor_ObjCPropertyDecl:
2899 return createCXString("ObjCPropertyDecl");
2900 case CXCursor_ObjCIvarDecl:
2901 return createCXString("ObjCIvarDecl");
2902 case CXCursor_ObjCInstanceMethodDecl:
2903 return createCXString("ObjCInstanceMethodDecl");
2904 case CXCursor_ObjCClassMethodDecl:
2905 return createCXString("ObjCClassMethodDecl");
2906 case CXCursor_ObjCImplementationDecl:
2907 return createCXString("ObjCImplementationDecl");
2908 case CXCursor_ObjCCategoryImplDecl:
2909 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002910 case CXCursor_CXXMethod:
2911 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002912 case CXCursor_UnexposedDecl:
2913 return createCXString("UnexposedDecl");
2914 case CXCursor_ObjCSuperClassRef:
2915 return createCXString("ObjCSuperClassRef");
2916 case CXCursor_ObjCProtocolRef:
2917 return createCXString("ObjCProtocolRef");
2918 case CXCursor_ObjCClassRef:
2919 return createCXString("ObjCClassRef");
2920 case CXCursor_TypeRef:
2921 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002922 case CXCursor_TemplateRef:
2923 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002924 case CXCursor_NamespaceRef:
2925 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002926 case CXCursor_MemberRef:
2927 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002928 case CXCursor_LabelRef:
2929 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002930 case CXCursor_OverloadedDeclRef:
2931 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002932 case CXCursor_UnexposedExpr:
2933 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002934 case CXCursor_BlockExpr:
2935 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002936 case CXCursor_DeclRefExpr:
2937 return createCXString("DeclRefExpr");
2938 case CXCursor_MemberRefExpr:
2939 return createCXString("MemberRefExpr");
2940 case CXCursor_CallExpr:
2941 return createCXString("CallExpr");
2942 case CXCursor_ObjCMessageExpr:
2943 return createCXString("ObjCMessageExpr");
2944 case CXCursor_UnexposedStmt:
2945 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002946 case CXCursor_LabelStmt:
2947 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002948 case CXCursor_InvalidFile:
2949 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002950 case CXCursor_InvalidCode:
2951 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002952 case CXCursor_NoDeclFound:
2953 return createCXString("NoDeclFound");
2954 case CXCursor_NotImplemented:
2955 return createCXString("NotImplemented");
2956 case CXCursor_TranslationUnit:
2957 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002958 case CXCursor_UnexposedAttr:
2959 return createCXString("UnexposedAttr");
2960 case CXCursor_IBActionAttr:
2961 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002962 case CXCursor_IBOutletAttr:
2963 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002964 case CXCursor_IBOutletCollectionAttr:
2965 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002966 case CXCursor_PreprocessingDirective:
2967 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002968 case CXCursor_MacroDefinition:
2969 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002970 case CXCursor_MacroInstantiation:
2971 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002972 case CXCursor_InclusionDirective:
2973 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002974 case CXCursor_Namespace:
2975 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002976 case CXCursor_LinkageSpec:
2977 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002978 case CXCursor_CXXBaseSpecifier:
2979 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002980 case CXCursor_Constructor:
2981 return createCXString("CXXConstructor");
2982 case CXCursor_Destructor:
2983 return createCXString("CXXDestructor");
2984 case CXCursor_ConversionFunction:
2985 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002986 case CXCursor_TemplateTypeParameter:
2987 return createCXString("TemplateTypeParameter");
2988 case CXCursor_NonTypeTemplateParameter:
2989 return createCXString("NonTypeTemplateParameter");
2990 case CXCursor_TemplateTemplateParameter:
2991 return createCXString("TemplateTemplateParameter");
2992 case CXCursor_FunctionTemplate:
2993 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002994 case CXCursor_ClassTemplate:
2995 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002996 case CXCursor_ClassTemplatePartialSpecialization:
2997 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002998 case CXCursor_NamespaceAlias:
2999 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003000 case CXCursor_UsingDirective:
3001 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003002 case CXCursor_UsingDeclaration:
3003 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003004 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003005
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003006 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003007 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003008}
Steve Naroff89922f82009-08-31 00:59:03 +00003009
Ted Kremeneke68fff62010-02-17 00:41:32 +00003010enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3011 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003012 CXClientData client_data) {
3013 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003014
3015 // If our current best cursor is the construction of a temporary object,
3016 // don't replace that cursor with a type reference, because we want
3017 // clang_getCursor() to point at the constructor.
3018 if (clang_isExpression(BestCursor->kind) &&
3019 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3020 cursor.kind == CXCursor_TypeRef)
3021 return CXChildVisit_Recurse;
3022
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003023 *BestCursor = cursor;
3024 return CXChildVisit_Recurse;
3025}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003026
Douglas Gregorb9790342010-01-22 21:44:22 +00003027CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3028 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003029 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003030
Douglas Gregorb9790342010-01-22 21:44:22 +00003031 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003032 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3033
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003034 // Translate the given source location to make it point at the beginning of
3035 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003036 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003037
3038 // Guard against an invalid SourceLocation, or we may assert in one
3039 // of the following calls.
3040 if (SLoc.isInvalid())
3041 return clang_getNullCursor();
3042
Douglas Gregor40749ee2010-11-03 00:35:38 +00003043 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003044 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3045 CXXUnit->getASTContext().getLangOptions());
3046
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003047 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3048 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003049 // FIXME: Would be great to have a "hint" cursor, then walk from that
3050 // hint cursor upward until we find a cursor whose source range encloses
3051 // the region of interest, rather than starting from the translation unit.
3052 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003053 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003054 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003055 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003056 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003057
3058 if (Logging) {
3059 CXFile SearchFile;
3060 unsigned SearchLine, SearchColumn;
3061 CXFile ResultFile;
3062 unsigned ResultLine, ResultColumn;
3063 CXString SearchFileName, ResultFileName, KindSpelling;
3064 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3065
3066 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3067 0);
3068 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3069 &ResultColumn, 0);
3070 SearchFileName = clang_getFileName(SearchFile);
3071 ResultFileName = clang_getFileName(ResultFile);
3072 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3073 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3074 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3075 clang_getCString(KindSpelling),
3076 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3077 clang_disposeString(SearchFileName);
3078 clang_disposeString(ResultFileName);
3079 clang_disposeString(KindSpelling);
3080 }
3081
Ted Kremeneke68fff62010-02-17 00:41:32 +00003082 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003083}
3084
Ted Kremenek73885552009-11-17 19:28:59 +00003085CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003086 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003087}
3088
3089unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003090 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003091}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003092
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003093unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003094 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3095}
3096
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003097unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003098 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3099}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003100
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003101unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003102 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3103}
3104
Douglas Gregor97b98722010-01-19 23:20:36 +00003105unsigned clang_isExpression(enum CXCursorKind K) {
3106 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3107}
3108
3109unsigned clang_isStatement(enum CXCursorKind K) {
3110 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3111}
3112
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003113unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3114 return K == CXCursor_TranslationUnit;
3115}
3116
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003117unsigned clang_isPreprocessing(enum CXCursorKind K) {
3118 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3119}
3120
Ted Kremenekad6eff62010-03-08 21:17:29 +00003121unsigned clang_isUnexposed(enum CXCursorKind K) {
3122 switch (K) {
3123 case CXCursor_UnexposedDecl:
3124 case CXCursor_UnexposedExpr:
3125 case CXCursor_UnexposedStmt:
3126 case CXCursor_UnexposedAttr:
3127 return true;
3128 default:
3129 return false;
3130 }
3131}
3132
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003133CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003134 return C.kind;
3135}
3136
Douglas Gregor98258af2010-01-18 22:46:11 +00003137CXSourceLocation clang_getCursorLocation(CXCursor C) {
3138 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003139 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003140 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003141 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3142 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003143 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003144 }
3145
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003146 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003147 std::pair<ObjCProtocolDecl *, SourceLocation> P
3148 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003149 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003150 }
3151
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003152 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003153 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3154 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003155 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003156 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003157
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003158 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003159 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003160 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003161 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003162
3163 case CXCursor_TemplateRef: {
3164 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3165 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3166 }
3167
Douglas Gregor69319002010-08-31 23:48:11 +00003168 case CXCursor_NamespaceRef: {
3169 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3170 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3171 }
3172
Douglas Gregora67e03f2010-09-09 21:42:20 +00003173 case CXCursor_MemberRef: {
3174 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3175 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3176 }
3177
Ted Kremenek3064ef92010-08-27 21:34:58 +00003178 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003179 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3180 if (!BaseSpec)
3181 return clang_getNullLocation();
3182
3183 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3184 return cxloc::translateSourceLocation(getCursorContext(C),
3185 TSInfo->getTypeLoc().getBeginLoc());
3186
3187 return cxloc::translateSourceLocation(getCursorContext(C),
3188 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003189 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003190
Douglas Gregor36897b02010-09-10 00:22:18 +00003191 case CXCursor_LabelRef: {
3192 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3193 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3194 }
3195
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003196 case CXCursor_OverloadedDeclRef:
3197 return cxloc::translateSourceLocation(getCursorContext(C),
3198 getCursorOverloadedDeclRef(C).second);
3199
Douglas Gregorf46034a2010-01-18 23:41:10 +00003200 default:
3201 // FIXME: Need a way to enumerate all non-reference cases.
3202 llvm_unreachable("Missed a reference kind");
3203 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003204 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003205
3206 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003207 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003208 getLocationFromExpr(getCursorExpr(C)));
3209
Douglas Gregor36897b02010-09-10 00:22:18 +00003210 if (clang_isStatement(C.kind))
3211 return cxloc::translateSourceLocation(getCursorContext(C),
3212 getCursorStmt(C)->getLocStart());
3213
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003214 if (C.kind == CXCursor_PreprocessingDirective) {
3215 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3216 return cxloc::translateSourceLocation(getCursorContext(C), L);
3217 }
Douglas Gregor48072312010-03-18 15:23:44 +00003218
3219 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003220 SourceLocation L
3221 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003222 return cxloc::translateSourceLocation(getCursorContext(C), L);
3223 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003224
3225 if (C.kind == CXCursor_MacroDefinition) {
3226 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3227 return cxloc::translateSourceLocation(getCursorContext(C), L);
3228 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003229
3230 if (C.kind == CXCursor_InclusionDirective) {
3231 SourceLocation L
3232 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3233 return cxloc::translateSourceLocation(getCursorContext(C), L);
3234 }
3235
Ted Kremenek9a700d22010-05-12 06:16:13 +00003236 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003237 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003238
Douglas Gregorf46034a2010-01-18 23:41:10 +00003239 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003240 SourceLocation Loc = D->getLocation();
3241 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3242 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003243 // FIXME: Multiple variables declared in a single declaration
3244 // currently lack the information needed to correctly determine their
3245 // ranges when accounting for the type-specifier. We use context
3246 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3247 // and if so, whether it is the first decl.
3248 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3249 if (!cxcursor::isFirstInDeclGroup(C))
3250 Loc = VD->getLocation();
3251 }
3252
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003253 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003254}
Douglas Gregora7bde202010-01-19 00:34:46 +00003255
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003256} // end extern "C"
3257
3258static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003259 if (clang_isReference(C.kind)) {
3260 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003261 case CXCursor_ObjCSuperClassRef:
3262 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003263
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003264 case CXCursor_ObjCProtocolRef:
3265 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003266
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003267 case CXCursor_ObjCClassRef:
3268 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003269
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003270 case CXCursor_TypeRef:
3271 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003272
3273 case CXCursor_TemplateRef:
3274 return getCursorTemplateRef(C).second;
3275
Douglas Gregor69319002010-08-31 23:48:11 +00003276 case CXCursor_NamespaceRef:
3277 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003278
3279 case CXCursor_MemberRef:
3280 return getCursorMemberRef(C).second;
3281
Ted Kremenek3064ef92010-08-27 21:34:58 +00003282 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003283 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003284
Douglas Gregor36897b02010-09-10 00:22:18 +00003285 case CXCursor_LabelRef:
3286 return getCursorLabelRef(C).second;
3287
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003288 case CXCursor_OverloadedDeclRef:
3289 return getCursorOverloadedDeclRef(C).second;
3290
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003291 default:
3292 // FIXME: Need a way to enumerate all non-reference cases.
3293 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003294 }
3295 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003296
3297 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003298 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003299
3300 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003301 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003302
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003303 if (C.kind == CXCursor_PreprocessingDirective)
3304 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003305
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003306 if (C.kind == CXCursor_MacroInstantiation)
3307 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003308
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003309 if (C.kind == CXCursor_MacroDefinition)
3310 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003311
3312 if (C.kind == CXCursor_InclusionDirective)
3313 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3314
Ted Kremenek007a7c92010-11-01 23:26:51 +00003315 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3316 Decl *D = cxcursor::getCursorDecl(C);
3317 SourceRange R = D->getSourceRange();
3318 // FIXME: Multiple variables declared in a single declaration
3319 // currently lack the information needed to correctly determine their
3320 // ranges when accounting for the type-specifier. We use context
3321 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3322 // and if so, whether it is the first decl.
3323 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3324 if (!cxcursor::isFirstInDeclGroup(C))
3325 R.setBegin(VD->getLocation());
3326 }
3327 return R;
3328 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003329 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003330
3331extern "C" {
3332
3333CXSourceRange clang_getCursorExtent(CXCursor C) {
3334 SourceRange R = getRawCursorExtent(C);
3335 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003336 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003337
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003338 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003339}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003340
3341CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003342 if (clang_isInvalid(C.kind))
3343 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003344
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003345 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003346 if (clang_isDeclaration(C.kind)) {
3347 Decl *D = getCursorDecl(C);
3348 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3349 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3350 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3351 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3352 if (ObjCForwardProtocolDecl *Protocols
3353 = dyn_cast<ObjCForwardProtocolDecl>(D))
3354 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3355
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003356 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003357 }
3358
Douglas Gregor97b98722010-01-19 23:20:36 +00003359 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003360 Expr *E = getCursorExpr(C);
3361 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003362 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003363 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003364
3365 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3366 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3367
Douglas Gregor97b98722010-01-19 23:20:36 +00003368 return clang_getNullCursor();
3369 }
3370
Douglas Gregor36897b02010-09-10 00:22:18 +00003371 if (clang_isStatement(C.kind)) {
3372 Stmt *S = getCursorStmt(C);
3373 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3374 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3375 getCursorASTUnit(C));
3376
3377 return clang_getNullCursor();
3378 }
3379
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003380 if (C.kind == CXCursor_MacroInstantiation) {
3381 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3382 return MakeMacroDefinitionCursor(Def, CXXUnit);
3383 }
3384
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003385 if (!clang_isReference(C.kind))
3386 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003387
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003388 switch (C.kind) {
3389 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003390 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003391
3392 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003393 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003394
3395 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003396 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003397
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003398 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003399 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003400
3401 case CXCursor_TemplateRef:
3402 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3403
Douglas Gregor69319002010-08-31 23:48:11 +00003404 case CXCursor_NamespaceRef:
3405 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3406
Douglas Gregora67e03f2010-09-09 21:42:20 +00003407 case CXCursor_MemberRef:
3408 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3409
Ted Kremenek3064ef92010-08-27 21:34:58 +00003410 case CXCursor_CXXBaseSpecifier: {
3411 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3412 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3413 CXXUnit));
3414 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003415
Douglas Gregor36897b02010-09-10 00:22:18 +00003416 case CXCursor_LabelRef:
3417 // FIXME: We end up faking the "parent" declaration here because we
3418 // don't want to make CXCursor larger.
3419 return MakeCXCursor(getCursorLabelRef(C).first,
3420 CXXUnit->getASTContext().getTranslationUnitDecl(),
3421 CXXUnit);
3422
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003423 case CXCursor_OverloadedDeclRef:
3424 return C;
3425
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003426 default:
3427 // We would prefer to enumerate all non-reference cursor kinds here.
3428 llvm_unreachable("Unhandled reference cursor kind");
3429 break;
3430 }
3431 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003432
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003433 return clang_getNullCursor();
3434}
3435
Douglas Gregorb6998662010-01-19 19:34:47 +00003436CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003437 if (clang_isInvalid(C.kind))
3438 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003439
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003440 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003441
Douglas Gregorb6998662010-01-19 19:34:47 +00003442 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003443 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003444 C = clang_getCursorReferenced(C);
3445 WasReference = true;
3446 }
3447
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003448 if (C.kind == CXCursor_MacroInstantiation)
3449 return clang_getCursorReferenced(C);
3450
Douglas Gregorb6998662010-01-19 19:34:47 +00003451 if (!clang_isDeclaration(C.kind))
3452 return clang_getNullCursor();
3453
3454 Decl *D = getCursorDecl(C);
3455 if (!D)
3456 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003457
Douglas Gregorb6998662010-01-19 19:34:47 +00003458 switch (D->getKind()) {
3459 // Declaration kinds that don't really separate the notions of
3460 // declaration and definition.
3461 case Decl::Namespace:
3462 case Decl::Typedef:
3463 case Decl::TemplateTypeParm:
3464 case Decl::EnumConstant:
3465 case Decl::Field:
3466 case Decl::ObjCIvar:
3467 case Decl::ObjCAtDefsField:
3468 case Decl::ImplicitParam:
3469 case Decl::ParmVar:
3470 case Decl::NonTypeTemplateParm:
3471 case Decl::TemplateTemplateParm:
3472 case Decl::ObjCCategoryImpl:
3473 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003474 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003475 case Decl::LinkageSpec:
3476 case Decl::ObjCPropertyImpl:
3477 case Decl::FileScopeAsm:
3478 case Decl::StaticAssert:
3479 case Decl::Block:
3480 return C;
3481
3482 // Declaration kinds that don't make any sense here, but are
3483 // nonetheless harmless.
3484 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003485 break;
3486
3487 // Declaration kinds for which the definition is not resolvable.
3488 case Decl::UnresolvedUsingTypename:
3489 case Decl::UnresolvedUsingValue:
3490 break;
3491
3492 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003493 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3494 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003495
3496 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003497 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003498
3499 case Decl::Enum:
3500 case Decl::Record:
3501 case Decl::CXXRecord:
3502 case Decl::ClassTemplateSpecialization:
3503 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003504 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003505 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003506 return clang_getNullCursor();
3507
3508 case Decl::Function:
3509 case Decl::CXXMethod:
3510 case Decl::CXXConstructor:
3511 case Decl::CXXDestructor:
3512 case Decl::CXXConversion: {
3513 const FunctionDecl *Def = 0;
3514 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003515 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003516 return clang_getNullCursor();
3517 }
3518
3519 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003520 // Ask the variable if it has a definition.
3521 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3522 return MakeCXCursor(Def, CXXUnit);
3523 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003524 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003525
Douglas Gregorb6998662010-01-19 19:34:47 +00003526 case Decl::FunctionTemplate: {
3527 const FunctionDecl *Def = 0;
3528 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003529 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003530 return clang_getNullCursor();
3531 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003532
Douglas Gregorb6998662010-01-19 19:34:47 +00003533 case Decl::ClassTemplate: {
3534 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003535 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003536 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003537 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003538 return clang_getNullCursor();
3539 }
3540
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003541 case Decl::Using:
3542 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3543 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003544
3545 case Decl::UsingShadow:
3546 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003547 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003548 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003549
3550 case Decl::ObjCMethod: {
3551 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3552 if (Method->isThisDeclarationADefinition())
3553 return C;
3554
3555 // Dig out the method definition in the associated
3556 // @implementation, if we have it.
3557 // FIXME: The ASTs should make finding the definition easier.
3558 if (ObjCInterfaceDecl *Class
3559 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3560 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3561 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3562 Method->isInstanceMethod()))
3563 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003564 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003565
3566 return clang_getNullCursor();
3567 }
3568
3569 case Decl::ObjCCategory:
3570 if (ObjCCategoryImplDecl *Impl
3571 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003572 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003573 return clang_getNullCursor();
3574
3575 case Decl::ObjCProtocol:
3576 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3577 return C;
3578 return clang_getNullCursor();
3579
3580 case Decl::ObjCInterface:
3581 // There are two notions of a "definition" for an Objective-C
3582 // class: the interface and its implementation. When we resolved a
3583 // reference to an Objective-C class, produce the @interface as
3584 // the definition; when we were provided with the interface,
3585 // produce the @implementation as the definition.
3586 if (WasReference) {
3587 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3588 return C;
3589 } else if (ObjCImplementationDecl *Impl
3590 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003591 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003592 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003593
Douglas Gregorb6998662010-01-19 19:34:47 +00003594 case Decl::ObjCProperty:
3595 // FIXME: We don't really know where to find the
3596 // ObjCPropertyImplDecls that implement this property.
3597 return clang_getNullCursor();
3598
3599 case Decl::ObjCCompatibleAlias:
3600 if (ObjCInterfaceDecl *Class
3601 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3602 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003603 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003604
Douglas Gregorb6998662010-01-19 19:34:47 +00003605 return clang_getNullCursor();
3606
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003607 case Decl::ObjCForwardProtocol:
3608 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3609 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003610
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003611 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003612 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003613 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003614
3615 case Decl::Friend:
3616 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003617 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003618 return clang_getNullCursor();
3619
3620 case Decl::FriendTemplate:
3621 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003622 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003623 return clang_getNullCursor();
3624 }
3625
3626 return clang_getNullCursor();
3627}
3628
3629unsigned clang_isCursorDefinition(CXCursor C) {
3630 if (!clang_isDeclaration(C.kind))
3631 return 0;
3632
3633 return clang_getCursorDefinition(C) == C;
3634}
3635
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003636unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003637 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003638 return 0;
3639
3640 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3641 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3642 return E->getNumDecls();
3643
3644 if (OverloadedTemplateStorage *S
3645 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3646 return S->size();
3647
3648 Decl *D = Storage.get<Decl*>();
3649 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003650 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003651 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3652 return Classes->size();
3653 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3654 return Protocols->protocol_size();
3655
3656 return 0;
3657}
3658
3659CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003660 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003661 return clang_getNullCursor();
3662
3663 if (index >= clang_getNumOverloadedDecls(cursor))
3664 return clang_getNullCursor();
3665
3666 ASTUnit *Unit = getCursorASTUnit(cursor);
3667 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3668 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3669 return MakeCXCursor(E->decls_begin()[index], Unit);
3670
3671 if (OverloadedTemplateStorage *S
3672 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3673 return MakeCXCursor(S->begin()[index], Unit);
3674
3675 Decl *D = Storage.get<Decl*>();
3676 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3677 // FIXME: This is, unfortunately, linear time.
3678 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3679 std::advance(Pos, index);
3680 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3681 }
3682
3683 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3684 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3685
3686 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3687 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3688
3689 return clang_getNullCursor();
3690}
3691
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003692void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003693 const char **startBuf,
3694 const char **endBuf,
3695 unsigned *startLine,
3696 unsigned *startColumn,
3697 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003698 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003699 assert(getCursorDecl(C) && "CXCursor has null decl");
3700 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003701 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3702 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003703
Steve Naroff4ade6d62009-09-23 17:52:52 +00003704 SourceManager &SM = FD->getASTContext().getSourceManager();
3705 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3706 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3707 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3708 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3709 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3710 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3711}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003712
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003713void clang_enableStackTraces(void) {
3714 llvm::sys::PrintStackTraceOnErrorSignal();
3715}
3716
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003717void clang_executeOnThread(void (*fn)(void*), void *user_data,
3718 unsigned stack_size) {
3719 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3720}
3721
Ted Kremenekfb480492010-01-13 21:46:36 +00003722} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003723
Ted Kremenekfb480492010-01-13 21:46:36 +00003724//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003725// Token-based Operations.
3726//===----------------------------------------------------------------------===//
3727
3728/* CXToken layout:
3729 * int_data[0]: a CXTokenKind
3730 * int_data[1]: starting token location
3731 * int_data[2]: token length
3732 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003733 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003734 * otherwise unused.
3735 */
3736extern "C" {
3737
3738CXTokenKind clang_getTokenKind(CXToken CXTok) {
3739 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3740}
3741
3742CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3743 switch (clang_getTokenKind(CXTok)) {
3744 case CXToken_Identifier:
3745 case CXToken_Keyword:
3746 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003747 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3748 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003749
3750 case CXToken_Literal: {
3751 // We have stashed the starting pointer in the ptr_data field. Use it.
3752 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003753 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003754 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003755
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003756 case CXToken_Punctuation:
3757 case CXToken_Comment:
3758 break;
3759 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003760
3761 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003762 // deconstructing the source location.
3763 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3764 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003765 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003766
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003767 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3768 std::pair<FileID, unsigned> LocInfo
3769 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003770 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003771 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003772 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3773 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003774 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003775
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003776 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003777}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003778
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003779CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3780 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3781 if (!CXXUnit)
3782 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003783
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003784 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3785 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3786}
3787
3788CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3789 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003790 if (!CXXUnit)
3791 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003792
3793 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003794 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3795}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003796
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003797void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3798 CXToken **Tokens, unsigned *NumTokens) {
3799 if (Tokens)
3800 *Tokens = 0;
3801 if (NumTokens)
3802 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003803
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003804 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3805 if (!CXXUnit || !Tokens || !NumTokens)
3806 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003807
Douglas Gregorbdf60622010-03-05 21:16:25 +00003808 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3809
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003810 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003811 if (R.isInvalid())
3812 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003813
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003814 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3815 std::pair<FileID, unsigned> BeginLocInfo
3816 = SourceMgr.getDecomposedLoc(R.getBegin());
3817 std::pair<FileID, unsigned> EndLocInfo
3818 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003819
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820 // Cannot tokenize across files.
3821 if (BeginLocInfo.first != EndLocInfo.first)
3822 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003823
3824 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003825 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003826 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003827 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003828 if (Invalid)
3829 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003830
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003831 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3832 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003833 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003836 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003837 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003838 llvm::SmallVector<CXToken, 32> CXTokens;
3839 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003840 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003841 do {
3842 // Lex the next token
3843 Lex.LexFromRawLexer(Tok);
3844 if (Tok.is(tok::eof))
3845 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003847 // Initialize the CXToken.
3848 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003849
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003850 // - Common fields
3851 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3852 CXTok.int_data[2] = Tok.getLength();
3853 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003854
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855 // - Kind-specific fields
3856 if (Tok.isLiteral()) {
3857 CXTok.int_data[0] = CXToken_Literal;
3858 CXTok.ptr_data = (void *)Tok.getLiteralData();
3859 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003860 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003861 std::pair<FileID, unsigned> LocInfo
3862 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003863 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003864 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003865 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3866 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003867 return;
3868
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003869 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870 IdentifierInfo *II
3871 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003872
David Chisnall096428b2010-10-13 21:44:48 +00003873 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003874 CXTok.int_data[0] = CXToken_Keyword;
3875 }
3876 else {
3877 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3878 CXToken_Identifier
3879 : CXToken_Keyword;
3880 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003881 CXTok.ptr_data = II;
3882 } else if (Tok.is(tok::comment)) {
3883 CXTok.int_data[0] = CXToken_Comment;
3884 CXTok.ptr_data = 0;
3885 } else {
3886 CXTok.int_data[0] = CXToken_Punctuation;
3887 CXTok.ptr_data = 0;
3888 }
3889 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003890 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003892
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893 if (CXTokens.empty())
3894 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003895
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003896 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3897 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3898 *NumTokens = CXTokens.size();
3899}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003900
Ted Kremenek6db61092010-05-05 00:55:15 +00003901void clang_disposeTokens(CXTranslationUnit TU,
3902 CXToken *Tokens, unsigned NumTokens) {
3903 free(Tokens);
3904}
3905
3906} // end: extern "C"
3907
3908//===----------------------------------------------------------------------===//
3909// Token annotation APIs.
3910//===----------------------------------------------------------------------===//
3911
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003912typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003913static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3914 CXCursor parent,
3915 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003916namespace {
3917class AnnotateTokensWorker {
3918 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003919 CXToken *Tokens;
3920 CXCursor *Cursors;
3921 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003922 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003923 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003924 CursorVisitor AnnotateVis;
3925 SourceManager &SrcMgr;
3926
3927 bool MoreTokens() const { return TokIdx < NumTokens; }
3928 unsigned NextToken() const { return TokIdx; }
3929 void AdvanceToken() { ++TokIdx; }
3930 SourceLocation GetTokenLoc(unsigned tokI) {
3931 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3932 }
3933
Ted Kremenek6db61092010-05-05 00:55:15 +00003934public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003935 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003936 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3937 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003938 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003939 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003940 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3941 Decl::MaxPCHLevel, RegionOfInterest),
3942 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003943
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003944 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003945 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003946 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003947 void AnnotateTokens() {
3948 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3949 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003950};
3951}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003952
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003953void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3954 // Walk the AST within the region of interest, annotating tokens
3955 // along the way.
3956 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003957
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003958 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3959 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003960 if (Pos != Annotated.end() &&
3961 (clang_isInvalid(Cursors[I].kind) ||
3962 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003963 Cursors[I] = Pos->second;
3964 }
3965
3966 // Finish up annotating any tokens left.
3967 if (!MoreTokens())
3968 return;
3969
3970 const CXCursor &C = clang_getNullCursor();
3971 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3972 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3973 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003974 }
3975}
3976
Ted Kremenek6db61092010-05-05 00:55:15 +00003977enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003978AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003979 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003980 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003981 if (cursorRange.isInvalid())
3982 return CXChildVisit_Recurse;
3983
Douglas Gregor4419b672010-10-21 06:10:04 +00003984 if (clang_isPreprocessing(cursor.kind)) {
3985 // For macro instantiations, just note where the beginning of the macro
3986 // instantiation occurs.
3987 if (cursor.kind == CXCursor_MacroInstantiation) {
3988 Annotated[Loc.int_data] = cursor;
3989 return CXChildVisit_Recurse;
3990 }
3991
Douglas Gregor4419b672010-10-21 06:10:04 +00003992 // Items in the preprocessing record are kept separate from items in
3993 // declarations, so we keep a separate token index.
3994 unsigned SavedTokIdx = TokIdx;
3995 TokIdx = PreprocessingTokIdx;
3996
3997 // Skip tokens up until we catch up to the beginning of the preprocessing
3998 // entry.
3999 while (MoreTokens()) {
4000 const unsigned I = NextToken();
4001 SourceLocation TokLoc = GetTokenLoc(I);
4002 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4003 case RangeBefore:
4004 AdvanceToken();
4005 continue;
4006 case RangeAfter:
4007 case RangeOverlap:
4008 break;
4009 }
4010 break;
4011 }
4012
4013 // Look at all of the tokens within this range.
4014 while (MoreTokens()) {
4015 const unsigned I = NextToken();
4016 SourceLocation TokLoc = GetTokenLoc(I);
4017 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4018 case RangeBefore:
4019 assert(0 && "Infeasible");
4020 case RangeAfter:
4021 break;
4022 case RangeOverlap:
4023 Cursors[I] = cursor;
4024 AdvanceToken();
4025 continue;
4026 }
4027 break;
4028 }
4029
4030 // Save the preprocessing token index; restore the non-preprocessing
4031 // token index.
4032 PreprocessingTokIdx = TokIdx;
4033 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004034 return CXChildVisit_Recurse;
4035 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004036
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004037 if (cursorRange.isInvalid())
4038 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004039
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004040 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4041
Ted Kremeneka333c662010-05-12 05:29:33 +00004042 // Adjust the annotated range based specific declarations.
4043 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4044 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004045 Decl *D = cxcursor::getCursorDecl(cursor);
4046 // Don't visit synthesized ObjC methods, since they have no syntatic
4047 // representation in the source.
4048 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4049 if (MD->isSynthesized())
4050 return CXChildVisit_Continue;
4051 }
4052 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004053 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4054 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004055 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004056 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004057 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004058 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004059 }
4060 }
4061 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004062
Ted Kremenek3f404602010-08-14 01:14:06 +00004063 // If the location of the cursor occurs within a macro instantiation, record
4064 // the spelling location of the cursor in our annotation map. We can then
4065 // paper over the token labelings during a post-processing step to try and
4066 // get cursor mappings for tokens that are the *arguments* of a macro
4067 // instantiation.
4068 if (L.isMacroID()) {
4069 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4070 // Only invalidate the old annotation if it isn't part of a preprocessing
4071 // directive. Here we assume that the default construction of CXCursor
4072 // results in CXCursor.kind being an initialized value (i.e., 0). If
4073 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004074
Ted Kremenek3f404602010-08-14 01:14:06 +00004075 CXCursor &oldC = Annotated[rawEncoding];
4076 if (!clang_isPreprocessing(oldC.kind))
4077 oldC = cursor;
4078 }
4079
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004080 const enum CXCursorKind K = clang_getCursorKind(parent);
4081 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004082 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4083 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004084
4085 while (MoreTokens()) {
4086 const unsigned I = NextToken();
4087 SourceLocation TokLoc = GetTokenLoc(I);
4088 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4089 case RangeBefore:
4090 Cursors[I] = updateC;
4091 AdvanceToken();
4092 continue;
4093 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004094 case RangeOverlap:
4095 break;
4096 }
4097 break;
4098 }
4099
4100 // Visit children to get their cursor information.
4101 const unsigned BeforeChildren = NextToken();
4102 VisitChildren(cursor);
4103 const unsigned AfterChildren = NextToken();
4104
4105 // Adjust 'Last' to the last token within the extent of the cursor.
4106 while (MoreTokens()) {
4107 const unsigned I = NextToken();
4108 SourceLocation TokLoc = GetTokenLoc(I);
4109 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4110 case RangeBefore:
4111 assert(0 && "Infeasible");
4112 case RangeAfter:
4113 break;
4114 case RangeOverlap:
4115 Cursors[I] = updateC;
4116 AdvanceToken();
4117 continue;
4118 }
4119 break;
4120 }
4121 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004122
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004123 // Scan the tokens that are at the beginning of the cursor, but are not
4124 // capture by the child cursors.
4125
4126 // For AST elements within macros, rely on a post-annotate pass to
4127 // to correctly annotate the tokens with cursors. Otherwise we can
4128 // get confusing results of having tokens that map to cursors that really
4129 // are expanded by an instantiation.
4130 if (L.isMacroID())
4131 cursor = clang_getNullCursor();
4132
4133 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4134 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4135 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004136
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004137 Cursors[I] = cursor;
4138 }
4139 // Scan the tokens that are at the end of the cursor, but are not captured
4140 // but the child cursors.
4141 for (unsigned I = AfterChildren; I != Last; ++I)
4142 Cursors[I] = cursor;
4143
4144 TokIdx = Last;
4145 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004146}
4147
Ted Kremenek6db61092010-05-05 00:55:15 +00004148static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4149 CXCursor parent,
4150 CXClientData client_data) {
4151 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4152}
4153
Ted Kremenekab979612010-11-11 08:05:23 +00004154// This gets run a separate thread to avoid stack blowout.
4155static void runAnnotateTokensWorker(void *UserData) {
4156 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4157}
4158
Ted Kremenek6db61092010-05-05 00:55:15 +00004159extern "C" {
4160
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004161void clang_annotateTokens(CXTranslationUnit TU,
4162 CXToken *Tokens, unsigned NumTokens,
4163 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004164
4165 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004166 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004167
Douglas Gregor4419b672010-10-21 06:10:04 +00004168 // Any token we don't specifically annotate will have a NULL cursor.
4169 CXCursor C = clang_getNullCursor();
4170 for (unsigned I = 0; I != NumTokens; ++I)
4171 Cursors[I] = C;
4172
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004173 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004174 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004175 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004176
Douglas Gregorbdf60622010-03-05 21:16:25 +00004177 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004178
Douglas Gregor0396f462010-03-19 05:22:59 +00004179 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004180 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004181 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4182 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004183 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4184 clang_getTokenLocation(TU,
4185 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004186
Douglas Gregor0396f462010-03-19 05:22:59 +00004187 // A mapping from the source locations found when re-lexing or traversing the
4188 // region of interest to the corresponding cursors.
4189 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004190
4191 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004192 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004193 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4194 std::pair<FileID, unsigned> BeginLocInfo
4195 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4196 std::pair<FileID, unsigned> EndLocInfo
4197 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004198
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004199 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004200 bool Invalid = false;
4201 if (BeginLocInfo.first == EndLocInfo.first &&
4202 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4203 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004204 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4205 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004206 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004207 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004208 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004209
4210 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004211 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004212 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004213 Token Tok;
4214 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004215
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004216 reprocess:
4217 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4218 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004219 // don't see it while preprocessing these tokens later, but keep track
4220 // of all of the token locations inside this preprocessing directive so
4221 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004222 //
4223 // FIXME: Some simple tests here could identify macro definitions and
4224 // #undefs, to provide specific cursor kinds for those.
4225 std::vector<SourceLocation> Locations;
4226 do {
4227 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004228 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004229 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004230
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004231 using namespace cxcursor;
4232 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004233 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4234 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004235 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004236 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4237 Annotated[Locations[I].getRawEncoding()] = Cursor;
4238 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004240 if (Tok.isAtStartOfLine())
4241 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004242
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004243 continue;
4244 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004245
Douglas Gregor48072312010-03-18 15:23:44 +00004246 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004247 break;
4248 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004249 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004250
Douglas Gregor0396f462010-03-19 05:22:59 +00004251 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252 // a specific cursor.
4253 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4254 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004255
4256 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004257 // FIXME: We use a ridiculous stack size here because the data-recursion
4258 // algorithm uses a large stack frame than the non-data recursive version,
4259 // and AnnotationTokensWorker currently transforms the data-recursion
4260 // algorithm back into a traditional recursion by explicitly calling
4261 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004262 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004263 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4264 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004265 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4266 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004267}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004268} // end: extern "C"
4269
4270//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004271// Operations for querying linkage of a cursor.
4272//===----------------------------------------------------------------------===//
4273
4274extern "C" {
4275CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004276 if (!clang_isDeclaration(cursor.kind))
4277 return CXLinkage_Invalid;
4278
Ted Kremenek16b42592010-03-03 06:36:57 +00004279 Decl *D = cxcursor::getCursorDecl(cursor);
4280 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4281 switch (ND->getLinkage()) {
4282 case NoLinkage: return CXLinkage_NoLinkage;
4283 case InternalLinkage: return CXLinkage_Internal;
4284 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4285 case ExternalLinkage: return CXLinkage_External;
4286 };
4287
4288 return CXLinkage_Invalid;
4289}
4290} // end: extern "C"
4291
4292//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004293// Operations for querying language of a cursor.
4294//===----------------------------------------------------------------------===//
4295
4296static CXLanguageKind getDeclLanguage(const Decl *D) {
4297 switch (D->getKind()) {
4298 default:
4299 break;
4300 case Decl::ImplicitParam:
4301 case Decl::ObjCAtDefsField:
4302 case Decl::ObjCCategory:
4303 case Decl::ObjCCategoryImpl:
4304 case Decl::ObjCClass:
4305 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004306 case Decl::ObjCForwardProtocol:
4307 case Decl::ObjCImplementation:
4308 case Decl::ObjCInterface:
4309 case Decl::ObjCIvar:
4310 case Decl::ObjCMethod:
4311 case Decl::ObjCProperty:
4312 case Decl::ObjCPropertyImpl:
4313 case Decl::ObjCProtocol:
4314 return CXLanguage_ObjC;
4315 case Decl::CXXConstructor:
4316 case Decl::CXXConversion:
4317 case Decl::CXXDestructor:
4318 case Decl::CXXMethod:
4319 case Decl::CXXRecord:
4320 case Decl::ClassTemplate:
4321 case Decl::ClassTemplatePartialSpecialization:
4322 case Decl::ClassTemplateSpecialization:
4323 case Decl::Friend:
4324 case Decl::FriendTemplate:
4325 case Decl::FunctionTemplate:
4326 case Decl::LinkageSpec:
4327 case Decl::Namespace:
4328 case Decl::NamespaceAlias:
4329 case Decl::NonTypeTemplateParm:
4330 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004331 case Decl::TemplateTemplateParm:
4332 case Decl::TemplateTypeParm:
4333 case Decl::UnresolvedUsingTypename:
4334 case Decl::UnresolvedUsingValue:
4335 case Decl::Using:
4336 case Decl::UsingDirective:
4337 case Decl::UsingShadow:
4338 return CXLanguage_CPlusPlus;
4339 }
4340
4341 return CXLanguage_C;
4342}
4343
4344extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004345
4346enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4347 if (clang_isDeclaration(cursor.kind))
4348 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4349 if (D->hasAttr<UnavailableAttr>() ||
4350 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4351 return CXAvailability_Available;
4352
4353 if (D->hasAttr<DeprecatedAttr>())
4354 return CXAvailability_Deprecated;
4355 }
4356
4357 return CXAvailability_Available;
4358}
4359
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004360CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4361 if (clang_isDeclaration(cursor.kind))
4362 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4363
4364 return CXLanguage_Invalid;
4365}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004366
4367CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4368 if (clang_isDeclaration(cursor.kind)) {
4369 if (Decl *D = getCursorDecl(cursor)) {
4370 DeclContext *DC = D->getDeclContext();
4371 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4372 }
4373 }
4374
4375 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4376 if (Decl *D = getCursorDecl(cursor))
4377 return MakeCXCursor(D, getCursorASTUnit(cursor));
4378 }
4379
4380 return clang_getNullCursor();
4381}
4382
4383CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4384 if (clang_isDeclaration(cursor.kind)) {
4385 if (Decl *D = getCursorDecl(cursor)) {
4386 DeclContext *DC = D->getLexicalDeclContext();
4387 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4388 }
4389 }
4390
4391 // FIXME: Note that we can't easily compute the lexical context of a
4392 // statement or expression, so we return nothing.
4393 return clang_getNullCursor();
4394}
4395
Douglas Gregor9f592342010-10-01 20:25:15 +00004396static void CollectOverriddenMethods(DeclContext *Ctx,
4397 ObjCMethodDecl *Method,
4398 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4399 if (!Ctx)
4400 return;
4401
4402 // If we have a class or category implementation, jump straight to the
4403 // interface.
4404 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4405 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4406
4407 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4408 if (!Container)
4409 return;
4410
4411 // Check whether we have a matching method at this level.
4412 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4413 Method->isInstanceMethod()))
4414 if (Method != Overridden) {
4415 // We found an override at this level; there is no need to look
4416 // into other protocols or categories.
4417 Methods.push_back(Overridden);
4418 return;
4419 }
4420
4421 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4422 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4423 PEnd = Protocol->protocol_end();
4424 P != PEnd; ++P)
4425 CollectOverriddenMethods(*P, Method, Methods);
4426 }
4427
4428 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4429 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4430 PEnd = Category->protocol_end();
4431 P != PEnd; ++P)
4432 CollectOverriddenMethods(*P, Method, Methods);
4433 }
4434
4435 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4436 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4437 PEnd = Interface->protocol_end();
4438 P != PEnd; ++P)
4439 CollectOverriddenMethods(*P, Method, Methods);
4440
4441 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4442 Category; Category = Category->getNextClassCategory())
4443 CollectOverriddenMethods(Category, Method, Methods);
4444
4445 // We only look into the superclass if we haven't found anything yet.
4446 if (Methods.empty())
4447 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4448 return CollectOverriddenMethods(Super, Method, Methods);
4449 }
4450}
4451
4452void clang_getOverriddenCursors(CXCursor cursor,
4453 CXCursor **overridden,
4454 unsigned *num_overridden) {
4455 if (overridden)
4456 *overridden = 0;
4457 if (num_overridden)
4458 *num_overridden = 0;
4459 if (!overridden || !num_overridden)
4460 return;
4461
4462 if (!clang_isDeclaration(cursor.kind))
4463 return;
4464
4465 Decl *D = getCursorDecl(cursor);
4466 if (!D)
4467 return;
4468
4469 // Handle C++ member functions.
4470 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4471 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4472 *num_overridden = CXXMethod->size_overridden_methods();
4473 if (!*num_overridden)
4474 return;
4475
4476 *overridden = new CXCursor [*num_overridden];
4477 unsigned I = 0;
4478 for (CXXMethodDecl::method_iterator
4479 M = CXXMethod->begin_overridden_methods(),
4480 MEnd = CXXMethod->end_overridden_methods();
4481 M != MEnd; (void)++M, ++I)
4482 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4483 return;
4484 }
4485
4486 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4487 if (!Method)
4488 return;
4489
4490 // Handle Objective-C methods.
4491 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4492 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4493
4494 if (Methods.empty())
4495 return;
4496
4497 *num_overridden = Methods.size();
4498 *overridden = new CXCursor [Methods.size()];
4499 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4500 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4501}
4502
4503void clang_disposeOverriddenCursors(CXCursor *overridden) {
4504 delete [] overridden;
4505}
4506
Douglas Gregorecdcb882010-10-20 22:00:55 +00004507CXFile clang_getIncludedFile(CXCursor cursor) {
4508 if (cursor.kind != CXCursor_InclusionDirective)
4509 return 0;
4510
4511 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4512 return (void *)ID->getFile();
4513}
4514
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004515} // end: extern "C"
4516
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004517
4518//===----------------------------------------------------------------------===//
4519// C++ AST instrospection.
4520//===----------------------------------------------------------------------===//
4521
4522extern "C" {
4523unsigned clang_CXXMethod_isStatic(CXCursor C) {
4524 if (!clang_isDeclaration(C.kind))
4525 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004526
4527 CXXMethodDecl *Method = 0;
4528 Decl *D = cxcursor::getCursorDecl(C);
4529 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4530 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4531 else
4532 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4533 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004534}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004535
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004536} // end: extern "C"
4537
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004538//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004539// Attribute introspection.
4540//===----------------------------------------------------------------------===//
4541
4542extern "C" {
4543CXType clang_getIBOutletCollectionType(CXCursor C) {
4544 if (C.kind != CXCursor_IBOutletCollectionAttr)
4545 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4546
4547 IBOutletCollectionAttr *A =
4548 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4549
4550 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4551}
4552} // end: extern "C"
4553
4554//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004555// CXString Operations.
4556//===----------------------------------------------------------------------===//
4557
4558extern "C" {
4559const char *clang_getCString(CXString string) {
4560 return string.Spelling;
4561}
4562
4563void clang_disposeString(CXString string) {
4564 if (string.MustFreeString && string.Spelling)
4565 free((void*)string.Spelling);
4566}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004567
Ted Kremenekfb480492010-01-13 21:46:36 +00004568} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004569
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004570namespace clang { namespace cxstring {
4571CXString createCXString(const char *String, bool DupString){
4572 CXString Str;
4573 if (DupString) {
4574 Str.Spelling = strdup(String);
4575 Str.MustFreeString = 1;
4576 } else {
4577 Str.Spelling = String;
4578 Str.MustFreeString = 0;
4579 }
4580 return Str;
4581}
4582
4583CXString createCXString(llvm::StringRef String, bool DupString) {
4584 CXString Result;
4585 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4586 char *Spelling = (char *)malloc(String.size() + 1);
4587 memmove(Spelling, String.data(), String.size());
4588 Spelling[String.size()] = 0;
4589 Result.Spelling = Spelling;
4590 Result.MustFreeString = 1;
4591 } else {
4592 Result.Spelling = String.data();
4593 Result.MustFreeString = 0;
4594 }
4595 return Result;
4596}
4597}}
4598
Ted Kremenek04bb7162010-01-22 22:44:15 +00004599//===----------------------------------------------------------------------===//
4600// Misc. utility functions.
4601//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004602
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004603/// Default to using an 8 MB stack size on "safety" threads.
4604static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004605
4606namespace clang {
4607
4608bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004609 void (*Fn)(void*), void *UserData,
4610 unsigned Size) {
4611 if (!Size)
4612 Size = GetSafetyThreadStackSize();
4613 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004614 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4615 return CRC.RunSafely(Fn, UserData);
4616}
4617
4618unsigned GetSafetyThreadStackSize() {
4619 return SafetyStackThreadSize;
4620}
4621
4622void SetSafetyThreadStackSize(unsigned Value) {
4623 SafetyStackThreadSize = Value;
4624}
4625
4626}
4627
Ted Kremenek04bb7162010-01-22 22:44:15 +00004628extern "C" {
4629
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004630CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004631 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004632}
4633
4634} // end: extern "C"