blob: bddf3d82fff00ca1a875319e7c0834d87c3e3ecb [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 Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
37#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000038#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000039#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000040#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000042#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000043#include "llvm/Support/Mutex.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000047#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000048
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Ted Kremeneka60ed472010-11-16 08:15:36 +000053static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
54 if (!TU)
55 return 0;
56 CXTranslationUnit D = new CXTranslationUnitImpl();
57 D->TUData = TU;
58 D->StringPool = createCXStringPool();
59 return D;
60}
61
Douglas Gregor33e9abd2010-01-22 19:49:59 +000062/// \brief The result of comparing two source ranges.
63enum RangeComparisonResult {
64 /// \brief Either the ranges overlap or one of the ranges is invalid.
65 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000066
Douglas Gregor33e9abd2010-01-22 19:49:59 +000067 /// \brief The first range ends before the second range starts.
68 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000069
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070 /// \brief The first range starts after the second range ends.
71 RangeAfter
72};
73
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076static RangeComparisonResult RangeCompare(SourceManager &SM,
77 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 SourceRange R2) {
79 assert(R1.isValid() && "First range is invalid?");
80 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000081 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000082 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000085 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 return RangeAfter;
87 return RangeOverlap;
88}
89
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000090/// \brief Determine if a source location falls within, before, or after a
91/// a given source range.
92static RangeComparisonResult LocationCompare(SourceManager &SM,
93 SourceLocation L, SourceRange R) {
94 assert(R.isValid() && "First range is invalid?");
95 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000096 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
99 return RangeBefore;
100 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
101 return RangeAfter;
102 return RangeOverlap;
103}
104
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105/// \brief Translate a Clang source range into a CIndex source range.
106///
107/// Clang internally represents ranges where the end location points to the
108/// start of the token at the end. However, for external clients it is more
109/// useful to have a CXSourceRange be a proper half-open interval. This routine
110/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000111CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000113 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000115 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000117 if (EndLoc.isValid() && EndLoc.isMacroID())
118 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000119 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000120 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000121 EndLoc = EndLoc.getFileLocWithOffset(Length);
122 }
123
124 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
125 R.getBegin().getRawEncoding(),
126 EndLoc.getRawEncoding() };
127 return Result;
128}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000129
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
133
Steve Naroff89922f82009-08-31 00:59:03 +0000134namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135
136class VisitorJob {
137public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000138 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000139 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000140 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000141 ExplicitTemplateArgsVisitKind,
142 NestedNameSpecifierVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000143 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000144 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000145 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000146protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000147 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000148 CXCursor parent;
149 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000150 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
151 : parent(C), K(k) {
152 data[0] = d1;
153 data[1] = d2;
154 data[2] = d3;
155 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000156public:
157 Kind getKind() const { return K; }
158 const CXCursor &getParent() const { return parent; }
159 static bool classof(VisitorJob *VJ) { return true; }
160};
161
162typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
163
Douglas Gregorb1373d02010-01-20 20:59:29 +0000164// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000165class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000166 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000167{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000169 CXTranslationUnit TU;
170 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000171
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The declaration that serves at the parent of any statement or
176 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000177 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000179 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000180 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000181
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000183 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000184
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000185 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
186 // to the visitor. Declarations with a PCH level greater than this value will
187 // be suppressed.
188 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000189
190 /// \brief When valid, a source range to which the cursor should restrict
191 /// its search.
192 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000194 // FIXME: Eventually remove. This part of a hack to support proper
195 // iteration over all Decls contained lexically within an ObjC container.
196 DeclContext::decl_iterator *DI_current;
197 DeclContext::decl_iterator DE_current;
198
Ted Kremenekd1ded662010-11-15 23:31:32 +0000199 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
200 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
201 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
206 /// \brief Determine whether this particular source range comes before, comes
207 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000209 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
211
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000212 class SetParentRAII {
213 CXCursor &Parent;
214 Decl *&StmtParent;
215 CXCursor OldParent;
216
217 public:
218 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
219 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
220 {
221 Parent = NewParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225
226 ~SetParentRAII() {
227 Parent = OldParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231 };
232
Steve Naroff89922f82009-08-31 00:59:03 +0000233public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000234 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
235 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000238 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
239 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000240 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
241 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 {
243 Parent.kind = CXCursor_NoDeclFound;
244 Parent.data[0] = 0;
245 Parent.data[1] = 0;
246 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000249
Ted Kremenekd1ded662010-11-15 23:31:32 +0000250 ~CursorVisitor() {
251 // Free the pre-allocated worklists for data-recursion.
252 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
253 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
254 delete *I;
255 }
256 }
257
Ted Kremeneka60ed472010-11-16 08:15:36 +0000258 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
259 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000260
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000261 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000262
263 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
264 getPreprocessedEntities();
265
Douglas Gregorb1373d02010-01-20 20:59:29 +0000266 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000267
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000268 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000269 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000270 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000271 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000272 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000274 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
275 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000276 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000277 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000278 bool VisitClassTemplatePartialSpecializationDecl(
279 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000280 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000281 bool VisitEnumConstantDecl(EnumConstantDecl *D);
282 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
283 bool VisitFunctionDecl(FunctionDecl *ND);
284 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000285 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000286 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000287 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000288 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000289 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
291 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
292 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
293 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000294 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000295 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
296 bool VisitObjCImplDecl(ObjCImplDecl *D);
297 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
298 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000299 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
300 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
301 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000302 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000303 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000304 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000305 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000306 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000307 bool VisitUsingDecl(UsingDecl *D);
308 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
309 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000310
Douglas Gregor01829d32010-08-31 14:41:23 +0000311 // Name visitor
312 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000313 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000314 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000315
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000316 // Template visitors
317 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000318 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000319 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
320
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000321 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000322 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000324 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000325 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
326 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000327 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000329 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000331 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000332 bool VisitPointerTypeLoc(PointerTypeLoc TL);
333 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
334 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
335 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
336 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000337 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000339 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000340 // FIXME: Implement visitors here when the unimplemented TypeLocs get
341 // implemented
342 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000343 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000344 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000345
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000346 // Data-recursive visitor functions.
347 bool IsInRegionOfInterest(CXCursor C);
348 bool RunVisitorWorkList(VisitorWorkList &WL);
349 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000350 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000351};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000352
Ted Kremenekab188932010-01-05 19:32:54 +0000353} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000354
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000355static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000356static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
357
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000358
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000360 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361}
362
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \brief Visit the given cursor and, if requested by the visitor,
364/// its children.
365///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366/// \param Cursor the cursor to visit.
367///
368/// \param CheckRegionOfInterest if true, then the caller already checked that
369/// this cursor is within the region of interest.
370///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \returns true if the visitation should be aborted, false if it
372/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000373bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 if (clang_isInvalid(Cursor.kind))
375 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000376
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 if (clang_isDeclaration(Cursor.kind)) {
378 Decl *D = getCursorDecl(Cursor);
379 assert(D && "Invalid declaration cursor");
380 if (D->getPCHLevel() > MaxPCHLevel)
381 return false;
382
383 if (D->isImplicit())
384 return false;
385 }
386
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387 // If we have a range of interest, and this cursor doesn't intersect with it,
388 // we're done.
389 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000390 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000391 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392 return false;
393 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000394
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 switch (Visitor(Cursor, Parent, ClientData)) {
396 case CXChildVisit_Break:
397 return true;
398
399 case CXChildVisit_Continue:
400 return false;
401
402 case CXChildVisit_Recurse:
403 return VisitChildren(Cursor);
404 }
405
Douglas Gregorfd643772010-01-25 16:45:46 +0000406 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407}
408
Douglas Gregor788f5a12010-03-20 00:41:21 +0000409std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
410CursorVisitor::getPreprocessedEntities() {
411 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000412 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000413
414 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000415 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
416
417 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
418 // If we would only look at local declarations but we have a region of
419 // interest, check whether that region of interest is in the main file.
420 // If not, we should traverse all declarations.
421 // FIXME: My kingdom for a proper binary search approach to finding
422 // cursors!
423 std::pair<FileID, unsigned> Location
424 = AU->getSourceManager().getDecomposedInstantiationLoc(
425 RegionOfInterest.getBegin());
426 if (Location.first != AU->getSourceManager().getMainFileID())
427 OnlyLocalDecls = false;
428 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429
Douglas Gregor89d99802010-11-30 06:16:57 +0000430 PreprocessingRecord::iterator StartEntity, EndEntity;
431 if (OnlyLocalDecls) {
432 StartEntity = AU->pp_entity_begin();
433 EndEntity = AU->pp_entity_end();
434 } else {
435 StartEntity = PPRec.begin();
436 EndEntity = PPRec.end();
437 }
438
Douglas Gregor788f5a12010-03-20 00:41:21 +0000439 // There is no region of interest; we have to walk everything.
440 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000441 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000442
443 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000444 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000445 std::pair<FileID, unsigned> Begin
446 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
447 std::pair<FileID, unsigned> End
448 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
449
450 // The region of interest spans files; we have to walk everything.
451 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000452 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000453
454 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000455 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000456 if (ByFileMap.empty()) {
457 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000458 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000459 std::pair<FileID, unsigned> P
460 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000461
Douglas Gregor788f5a12010-03-20 00:41:21 +0000462 ByFileMap[P.first].push_back(*E);
463 }
464 }
465
466 return std::make_pair(ByFileMap[Begin.first].begin(),
467 ByFileMap[Begin.first].end());
468}
469
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000471///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472/// \returns true if the visitation should be aborted, false if it
473/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000474bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000475 if (clang_isReference(Cursor.kind)) {
476 // By definition, references have no children.
477 return false;
478 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479
480 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000481 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000482 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000483
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 if (clang_isDeclaration(Cursor.kind)) {
485 Decl *D = getCursorDecl(Cursor);
486 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000487 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000489
Douglas Gregora59e3902010-01-21 23:27:09 +0000490 if (clang_isStatement(Cursor.kind))
491 return Visit(getCursorStmt(Cursor));
492 if (clang_isExpression(Cursor.kind))
493 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000494
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000496 CXTranslationUnit tu = getCursorTU(Cursor);
497 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000498 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
499 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000500 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
501 TLEnd = CXXUnit->top_level_end();
502 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000503 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000504 return true;
505 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000506 } else if (VisitDeclContext(
507 CXXUnit->getASTContext().getTranslationUnitDecl()))
508 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000509
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000511 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 // FIXME: Once we have the ability to deserialize a preprocessing record,
513 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000514 PreprocessingRecord::iterator E, EEnd;
515 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000516 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000517 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000519
Douglas Gregor0396f462010-03-19 05:22:59 +0000520 continue;
521 }
522
523 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000524 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000525 return true;
526
527 continue;
528 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000529
530 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000531 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000532 return true;
533
534 continue;
535 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000536 }
537 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000538 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000540
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000542 return false;
543}
544
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000545bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000546 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
547 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000548
Ted Kremenek664cffd2010-07-22 11:30:19 +0000549 if (Stmt *Body = B->getBody())
550 return Visit(MakeCXCursor(Body, StmtParent, TU));
551
552 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000553}
554
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000555llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
556 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000557 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000558 if (Range.isInvalid())
559 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000560
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000561 switch (CompareRegionOfInterest(Range)) {
562 case RangeBefore:
563 // This declaration comes before the region of interest; skip it.
564 return llvm::Optional<bool>();
565
566 case RangeAfter:
567 // This declaration comes after the region of interest; we're done.
568 return false;
569
570 case RangeOverlap:
571 // This declaration overlaps the region of interest; visit it.
572 break;
573 }
574 }
575 return true;
576}
577
578bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
579 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
580
581 // FIXME: Eventually remove. This part of a hack to support proper
582 // iteration over all Decls contained lexically within an ObjC container.
583 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
584 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
585
586 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000587 Decl *D = *I;
588 if (D->getLexicalDeclContext() != DC)
589 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000590 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000591 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
592 if (!V.hasValue())
593 continue;
594 if (!V.getValue())
595 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000596 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597 return true;
598 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000599 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000600}
601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
603 llvm_unreachable("Translation units are visited directly by Visit()");
604 return false;
605}
606
607bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
608 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
609 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000610
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000611 return false;
612}
613
614bool CursorVisitor::VisitTagDecl(TagDecl *D) {
615 return VisitDeclContext(D);
616}
617
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000618bool CursorVisitor::VisitClassTemplateSpecializationDecl(
619 ClassTemplateSpecializationDecl *D) {
620 bool ShouldVisitBody = false;
621 switch (D->getSpecializationKind()) {
622 case TSK_Undeclared:
623 case TSK_ImplicitInstantiation:
624 // Nothing to visit
625 return false;
626
627 case TSK_ExplicitInstantiationDeclaration:
628 case TSK_ExplicitInstantiationDefinition:
629 break;
630
631 case TSK_ExplicitSpecialization:
632 ShouldVisitBody = true;
633 break;
634 }
635
636 // Visit the template arguments used in the specialization.
637 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
638 TypeLoc TL = SpecType->getTypeLoc();
639 if (TemplateSpecializationTypeLoc *TSTLoc
640 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
641 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
642 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
643 return true;
644 }
645 }
646
647 if (ShouldVisitBody && VisitCXXRecordDecl(D))
648 return true;
649
650 return false;
651}
652
Douglas Gregor74dbe642010-08-31 19:31:58 +0000653bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
654 ClassTemplatePartialSpecializationDecl *D) {
655 // FIXME: Visit the "outer" template parameter lists on the TagDecl
656 // before visiting these template parameters.
657 if (VisitTemplateParameters(D->getTemplateParameters()))
658 return true;
659
660 // Visit the partial specialization arguments.
661 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
662 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
663 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
664 return true;
665
666 return VisitCXXRecordDecl(D);
667}
668
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000669bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000670 // Visit the default argument.
671 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
672 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
673 if (Visit(DefArg->getTypeLoc()))
674 return true;
675
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000676 return false;
677}
678
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000679bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
680 if (Expr *Init = D->getInitExpr())
681 return Visit(MakeCXCursor(Init, StmtParent, TU));
682 return false;
683}
684
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000685bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
686 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
687 if (Visit(TSInfo->getTypeLoc()))
688 return true;
689
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000690 // Visit the nested-name-specifier, if present.
691 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
692 if (VisitNestedNameSpecifierLoc(QualifierLoc))
693 return true;
694
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000695 return false;
696}
697
Douglas Gregora67e03f2010-09-09 21:42:20 +0000698/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000699static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
700 CXXCtorInitializer const * const *X
701 = static_cast<CXXCtorInitializer const * const *>(Xp);
702 CXXCtorInitializer const * const *Y
703 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000704
705 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
706 return -1;
707 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
708 return 1;
709 else
710 return 0;
711}
712
Douglas Gregorb1373d02010-01-20 20:59:29 +0000713bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000714 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
715 // Visit the function declaration's syntactic components in the order
716 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000717 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000718 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
719
720 // If we have a function declared directly (without the use of a typedef),
721 // visit just the return type. Otherwise, just visit the function's type
722 // now.
723 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
724 (!FTL && Visit(TL)))
725 return true;
726
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000727 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000728 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
729 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000730 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000731
732 // Visit the declaration name.
733 if (VisitDeclarationNameInfo(ND->getNameInfo()))
734 return true;
735
736 // FIXME: Visit explicitly-specified template arguments!
737
738 // Visit the function parameters, if we have a function type.
739 if (FTL && VisitFunctionTypeLoc(*FTL, true))
740 return true;
741
742 // FIXME: Attributes?
743 }
744
Douglas Gregora67e03f2010-09-09 21:42:20 +0000745 if (ND->isThisDeclarationADefinition()) {
746 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
747 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000748 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000749 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
750 IEnd = Constructor->init_end();
751 I != IEnd; ++I) {
752 if (!(*I)->isWritten())
753 continue;
754
755 WrittenInits.push_back(*I);
756 }
757
758 // Sort the initializers in source order
759 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000760 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761
762 // Visit the initializers in source order
763 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000764 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000765 if (Init->isAnyMemberInitializer()) {
766 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000767 Init->getMemberLocation(), TU)))
768 return true;
769 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
770 if (Visit(BaseInfo->getTypeLoc()))
771 return true;
772 }
773
774 // Visit the initializer value.
775 if (Expr *Initializer = Init->getInit())
776 if (Visit(MakeCXCursor(Initializer, ND, TU)))
777 return true;
778 }
779 }
780
781 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
782 return true;
783 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregorb1373d02010-01-20 20:59:29 +0000785 return false;
786}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
789 if (VisitDeclaratorDecl(D))
790 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000791
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000792 if (Expr *BitWidth = D->getBitWidth())
793 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 return false;
796}
797
798bool CursorVisitor::VisitVarDecl(VarDecl *D) {
799 if (VisitDeclaratorDecl(D))
800 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 if (Expr *Init = D->getInit())
803 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 return false;
806}
807
Douglas Gregor84b51d72010-09-01 20:16:53 +0000808bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
809 if (VisitDeclaratorDecl(D))
810 return true;
811
812 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
813 if (Expr *DefArg = D->getDefaultArgument())
814 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
815
816 return false;
817}
818
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000819bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
820 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
821 // before visiting these template parameters.
822 if (VisitTemplateParameters(D->getTemplateParameters()))
823 return true;
824
825 return VisitFunctionDecl(D->getTemplatedDecl());
826}
827
Douglas Gregor39d6f072010-08-31 19:02:00 +0000828bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
829 // FIXME: Visit the "outer" template parameter lists on the TagDecl
830 // before visiting these template parameters.
831 if (VisitTemplateParameters(D->getTemplateParameters()))
832 return true;
833
834 return VisitCXXRecordDecl(D->getTemplatedDecl());
835}
836
Douglas Gregor84b51d72010-09-01 20:16:53 +0000837bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
838 if (VisitTemplateParameters(D->getTemplateParameters()))
839 return true;
840
841 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
842 VisitTemplateArgumentLoc(D->getDefaultArgument()))
843 return true;
844
845 return false;
846}
847
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000849 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
850 if (Visit(TSInfo->getTypeLoc()))
851 return true;
852
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 PEnd = ND->param_end();
855 P != PEnd; ++P) {
856 if (Visit(MakeCXCursor(*P, TU)))
857 return true;
858 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000859
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860 if (ND->isThisDeclarationADefinition() &&
861 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
862 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000863
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000864 return false;
865}
866
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000867namespace {
868 struct ContainerDeclsSort {
869 SourceManager &SM;
870 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
871 bool operator()(Decl *A, Decl *B) {
872 SourceLocation L_A = A->getLocStart();
873 SourceLocation L_B = B->getLocStart();
874 assert(L_A.isValid() && L_B.isValid());
875 return SM.isBeforeInTranslationUnit(L_A, L_B);
876 }
877 };
878}
879
Douglas Gregora59e3902010-01-21 23:27:09 +0000880bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000881 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
882 // an @implementation can lexically contain Decls that are not properly
883 // nested in the AST. When we identify such cases, we need to retrofit
884 // this nesting here.
885 if (!DI_current)
886 return VisitDeclContext(D);
887
888 // Scan the Decls that immediately come after the container
889 // in the current DeclContext. If any fall within the
890 // container's lexical region, stash them into a vector
891 // for later processing.
892 llvm::SmallVector<Decl *, 24> DeclsInContainer;
893 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000894 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000895 if (EndLoc.isValid()) {
896 DeclContext::decl_iterator next = *DI_current;
897 while (++next != DE_current) {
898 Decl *D_next = *next;
899 if (!D_next)
900 break;
901 SourceLocation L = D_next->getLocStart();
902 if (!L.isValid())
903 break;
904 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
905 *DI_current = next;
906 DeclsInContainer.push_back(D_next);
907 continue;
908 }
909 break;
910 }
911 }
912
913 // The common case.
914 if (DeclsInContainer.empty())
915 return VisitDeclContext(D);
916
917 // Get all the Decls in the DeclContext, and sort them with the
918 // additional ones we've collected. Then visit them.
919 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
920 I!=E; ++I) {
921 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000922 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
923 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000924 continue;
925 DeclsInContainer.push_back(subDecl);
926 }
927
928 // Now sort the Decls so that they appear in lexical order.
929 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
930 ContainerDeclsSort(SM));
931
932 // Now visit the decls.
933 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
934 E = DeclsInContainer.end(); I != E; ++I) {
935 CXCursor Cursor = MakeCXCursor(*I, TU);
936 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
937 if (!V.hasValue())
938 continue;
939 if (!V.getValue())
940 return false;
941 if (Visit(Cursor, true))
942 return true;
943 }
944 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000945}
946
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000948 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
949 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000950 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000951
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000952 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
953 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
954 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000955 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000956 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000957
Douglas Gregora59e3902010-01-21 23:27:09 +0000958 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000959}
960
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000961bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
962 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
963 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
964 E = PID->protocol_end(); I != E; ++I, ++PL)
965 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
966 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000967
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000968 return VisitObjCContainerDecl(PID);
969}
970
Ted Kremenek23173d72010-05-18 21:09:07 +0000971bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000972 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000973 return true;
974
Ted Kremenek23173d72010-05-18 21:09:07 +0000975 // FIXME: This implements a workaround with @property declarations also being
976 // installed in the DeclContext for the @interface. Eventually this code
977 // should be removed.
978 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
979 if (!CDecl || !CDecl->IsClassExtension())
980 return false;
981
982 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
983 if (!ID)
984 return false;
985
986 IdentifierInfo *PropertyId = PD->getIdentifier();
987 ObjCPropertyDecl *prevDecl =
988 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
989
990 if (!prevDecl)
991 return false;
992
993 // Visit synthesized methods since they will be skipped when visiting
994 // the @interface.
995 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000996 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000997 if (Visit(MakeCXCursor(MD, TU)))
998 return true;
999
1000 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001001 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001002 if (Visit(MakeCXCursor(MD, TU)))
1003 return true;
1004
1005 return false;
1006}
1007
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001009 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001010 if (D->getSuperClass() &&
1011 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001013 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001016 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1017 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1018 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001019 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001020 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021
Douglas Gregora59e3902010-01-21 23:27:09 +00001022 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001023}
1024
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001025bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1026 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001027}
1028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001030 // 'ID' could be null when dealing with invalid code.
1031 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1032 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001035 return VisitObjCImplDecl(D);
1036}
1037
1038bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1039#if 0
1040 // Issue callbacks for super class.
1041 // FIXME: No source location information!
1042 if (D->getSuperClass() &&
1043 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045 TU)))
1046 return true;
1047#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001049 return VisitObjCImplDecl(D);
1050}
1051
1052bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1053 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1054 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1055 E = D->protocol_end();
1056 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001057 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001058 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001059
1060 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001061}
1062
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1064 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1065 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1066 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001067
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001068 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001069}
1070
Douglas Gregora4ffd852010-11-17 01:03:52 +00001071bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1072 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1073 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1074
1075 return false;
1076}
1077
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001078bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1079 return VisitDeclContext(D);
1080}
1081
Douglas Gregor69319002010-08-31 23:48:11 +00001082bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001083 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001084 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1085 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001087
1088 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1089 D->getTargetNameLoc(), TU));
1090}
1091
Douglas Gregor7e242562010-09-01 19:52:22 +00001092bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001093 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001094 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1095 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001097 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001098
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001099 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1100 return true;
1101
Douglas Gregor7e242562010-09-01 19:52:22 +00001102 return VisitDeclarationNameInfo(D->getNameInfo());
1103}
1104
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001105bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001107 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1108 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001109 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001110
1111 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1112 D->getIdentLocation(), TU));
1113}
1114
Douglas Gregor7e242562010-09-01 19:52:22 +00001115bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001116 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001117 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1118 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001120 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121
Douglas Gregor7e242562010-09-01 19:52:22 +00001122 return VisitDeclarationNameInfo(D->getNameInfo());
1123}
1124
1125bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1126 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001127 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001128 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1129 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001130 return true;
1131
Douglas Gregor7e242562010-09-01 19:52:22 +00001132 return false;
1133}
1134
Douglas Gregor01829d32010-08-31 14:41:23 +00001135bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1136 switch (Name.getName().getNameKind()) {
1137 case clang::DeclarationName::Identifier:
1138 case clang::DeclarationName::CXXLiteralOperatorName:
1139 case clang::DeclarationName::CXXOperatorName:
1140 case clang::DeclarationName::CXXUsingDirective:
1141 return false;
1142
1143 case clang::DeclarationName::CXXConstructorName:
1144 case clang::DeclarationName::CXXDestructorName:
1145 case clang::DeclarationName::CXXConversionFunctionName:
1146 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1147 return Visit(TSInfo->getTypeLoc());
1148 return false;
1149
1150 case clang::DeclarationName::ObjCZeroArgSelector:
1151 case clang::DeclarationName::ObjCOneArgSelector:
1152 case clang::DeclarationName::ObjCMultiArgSelector:
1153 // FIXME: Per-identifier location info?
1154 return false;
1155 }
1156
1157 return false;
1158}
1159
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001160bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1161 SourceRange Range) {
1162 // FIXME: This whole routine is a hack to work around the lack of proper
1163 // source information in nested-name-specifiers (PR5791). Since we do have
1164 // a beginning source location, we can visit the first component of the
1165 // nested-name-specifier, if it's a single-token component.
1166 if (!NNS)
1167 return false;
1168
1169 // Get the first component in the nested-name-specifier.
1170 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1171 NNS = Prefix;
1172
1173 switch (NNS->getKind()) {
1174 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001175 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1176 TU));
1177
Douglas Gregor14aba762011-02-24 02:36:08 +00001178 case NestedNameSpecifier::NamespaceAlias:
1179 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1180 Range.getBegin(), TU));
1181
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001182 case NestedNameSpecifier::TypeSpec: {
1183 // If the type has a form where we know that the beginning of the source
1184 // range matches up with a reference cursor. Visit the appropriate reference
1185 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001186 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001187 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1188 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1189 if (const TagType *Tag = dyn_cast<TagType>(T))
1190 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1191 if (const TemplateSpecializationType *TST
1192 = dyn_cast<TemplateSpecializationType>(T))
1193 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1194 break;
1195 }
1196
1197 case NestedNameSpecifier::TypeSpecWithTemplate:
1198 case NestedNameSpecifier::Global:
1199 case NestedNameSpecifier::Identifier:
1200 break;
1201 }
1202
1203 return false;
1204}
1205
Douglas Gregordc355712011-02-25 00:36:19 +00001206bool
1207CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1208 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1209 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1210 Qualifiers.push_back(Qualifier);
1211
1212 while (!Qualifiers.empty()) {
1213 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1214 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1215 switch (NNS->getKind()) {
1216 case NestedNameSpecifier::Namespace:
1217 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001218 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001219 TU)))
1220 return true;
1221
1222 break;
1223
1224 case NestedNameSpecifier::NamespaceAlias:
1225 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001226 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001227 TU)))
1228 return true;
1229
1230 break;
1231
1232 case NestedNameSpecifier::TypeSpec:
1233 case NestedNameSpecifier::TypeSpecWithTemplate:
1234 if (Visit(Q.getTypeLoc()))
1235 return true;
1236
1237 break;
1238
1239 case NestedNameSpecifier::Global:
1240 case NestedNameSpecifier::Identifier:
1241 break;
1242 }
1243 }
1244
1245 return false;
1246}
1247
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001248bool CursorVisitor::VisitTemplateParameters(
1249 const TemplateParameterList *Params) {
1250 if (!Params)
1251 return false;
1252
1253 for (TemplateParameterList::const_iterator P = Params->begin(),
1254 PEnd = Params->end();
1255 P != PEnd; ++P) {
1256 if (Visit(MakeCXCursor(*P, TU)))
1257 return true;
1258 }
1259
1260 return false;
1261}
1262
Douglas Gregor0b36e612010-08-31 20:37:03 +00001263bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1264 switch (Name.getKind()) {
1265 case TemplateName::Template:
1266 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1267
1268 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001269 // Visit the overloaded template set.
1270 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1271 return true;
1272
Douglas Gregor0b36e612010-08-31 20:37:03 +00001273 return false;
1274
1275 case TemplateName::DependentTemplate:
1276 // FIXME: Visit nested-name-specifier.
1277 return false;
1278
1279 case TemplateName::QualifiedTemplate:
1280 // FIXME: Visit nested-name-specifier.
1281 return Visit(MakeCursorTemplateRef(
1282 Name.getAsQualifiedTemplateName()->getDecl(),
1283 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001284
1285 case TemplateName::SubstTemplateTemplateParmPack:
1286 return Visit(MakeCursorTemplateRef(
1287 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1288 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001289 }
1290
1291 return false;
1292}
1293
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001294bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1295 switch (TAL.getArgument().getKind()) {
1296 case TemplateArgument::Null:
1297 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001298 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001299 return false;
1300
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301 case TemplateArgument::Type:
1302 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1303 return Visit(TSInfo->getTypeLoc());
1304 return false;
1305
1306 case TemplateArgument::Declaration:
1307 if (Expr *E = TAL.getSourceDeclExpression())
1308 return Visit(MakeCXCursor(E, StmtParent, TU));
1309 return false;
1310
1311 case TemplateArgument::Expression:
1312 if (Expr *E = TAL.getSourceExpression())
1313 return Visit(MakeCXCursor(E, StmtParent, TU));
1314 return false;
1315
1316 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001317 case TemplateArgument::TemplateExpansion:
1318 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001319 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001320 }
1321
1322 return false;
1323}
1324
Ted Kremeneka0536d82010-05-07 01:04:29 +00001325bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1326 return VisitDeclContext(D);
1327}
1328
Douglas Gregor01829d32010-08-31 14:41:23 +00001329bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1330 return Visit(TL.getUnqualifiedLoc());
1331}
1332
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001334 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335
1336 // Some builtin types (such as Objective-C's "id", "sel", and
1337 // "Class") have associated declarations. Create cursors for those.
1338 QualType VisitType;
1339 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001340 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001342 case BuiltinType::Char_U:
1343 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001344 case BuiltinType::Char16:
1345 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001346 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001347 case BuiltinType::UInt:
1348 case BuiltinType::ULong:
1349 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001350 case BuiltinType::UInt128:
1351 case BuiltinType::Char_S:
1352 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001353 case BuiltinType::WChar_U:
1354 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001355 case BuiltinType::Short:
1356 case BuiltinType::Int:
1357 case BuiltinType::Long:
1358 case BuiltinType::LongLong:
1359 case BuiltinType::Int128:
1360 case BuiltinType::Float:
1361 case BuiltinType::Double:
1362 case BuiltinType::LongDouble:
1363 case BuiltinType::NullPtr:
1364 case BuiltinType::Overload:
1365 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001366 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001367
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001368 case BuiltinType::ObjCId:
1369 VisitType = Context.getObjCIdType();
1370 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001371
1372 case BuiltinType::ObjCClass:
1373 VisitType = Context.getObjCClassType();
1374 break;
1375
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376 case BuiltinType::ObjCSel:
1377 VisitType = Context.getObjCSelType();
1378 break;
1379 }
1380
1381 if (!VisitType.isNull()) {
1382 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001383 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384 TU));
1385 }
1386
1387 return false;
1388}
1389
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001390bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1391 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1392}
1393
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1395 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1396}
1397
1398bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1399 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1400}
1401
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001402bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001403 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001404 // no context information with which we can match up the depth/index in the
1405 // type to the appropriate
1406 return false;
1407}
1408
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1410 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1411 return true;
1412
John McCallc12c5bb2010-05-15 11:32:37 +00001413 return false;
1414}
1415
1416bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1417 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1418 return true;
1419
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001420 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1421 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1422 TU)))
1423 return true;
1424 }
1425
1426 return false;
1427}
1428
1429bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001430 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001431}
1432
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001433bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1434 return Visit(TL.getInnerLoc());
1435}
1436
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001437bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1438 return Visit(TL.getPointeeLoc());
1439}
1440
1441bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1442 return Visit(TL.getPointeeLoc());
1443}
1444
1445bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1446 return Visit(TL.getPointeeLoc());
1447}
1448
1449bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001450 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001451}
1452
1453bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455}
1456
Douglas Gregor01829d32010-08-31 14:41:23 +00001457bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1458 bool SkipResultType) {
1459 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001460 return true;
1461
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001462 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001463 if (Decl *D = TL.getArg(I))
1464 if (Visit(MakeCXCursor(D, TU)))
1465 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001466
1467 return false;
1468}
1469
1470bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1471 if (Visit(TL.getElementLoc()))
1472 return true;
1473
1474 if (Expr *Size = TL.getSizeExpr())
1475 return Visit(MakeCXCursor(Size, StmtParent, TU));
1476
1477 return false;
1478}
1479
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001480bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1481 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001482 // Visit the template name.
1483 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1484 TL.getTemplateNameLoc()))
1485 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001486
1487 // Visit the template arguments.
1488 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1489 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1490 return true;
1491
1492 return false;
1493}
1494
Douglas Gregor2332c112010-01-21 20:48:56 +00001495bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1496 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1497}
1498
1499bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1500 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1501 return Visit(TSInfo->getTypeLoc());
1502
1503 return false;
1504}
1505
Douglas Gregor7536dd52010-12-20 02:24:11 +00001506bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1507 return Visit(TL.getPatternLoc());
1508}
1509
Ted Kremenek3064ef92010-08-27 21:34:58 +00001510bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001511 // Visit the nested-name-specifier, if present.
1512 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1513 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1514 return true;
1515
Ted Kremenek3064ef92010-08-27 21:34:58 +00001516 if (D->isDefinition()) {
1517 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1518 E = D->bases_end(); I != E; ++I) {
1519 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1520 return true;
1521 }
1522 }
1523
1524 return VisitTagDecl(D);
1525}
1526
Ted Kremenek09dfa372010-02-18 05:46:33 +00001527bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001528 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1529 i != e; ++i)
1530 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001531 return true;
1532
1533 return false;
1534}
1535
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001536//===----------------------------------------------------------------------===//
1537// Data-recursive visitor methods.
1538//===----------------------------------------------------------------------===//
1539
Ted Kremenek28a71942010-11-13 00:36:47 +00001540namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001541#define DEF_JOB(NAME, DATA, KIND)\
1542class NAME : public VisitorJob {\
1543public:\
1544 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1545 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001546 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001547};
1548
1549DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1550DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001551DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001552DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001553DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1554 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001555DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001556#undef DEF_JOB
1557
1558class DeclVisit : public VisitorJob {
1559public:
1560 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1561 VisitorJob(parent, VisitorJob::DeclVisitKind,
1562 d, isFirst ? (void*) 1 : (void*) 0) {}
1563 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001564 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001565 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001566 Decl *get() const { return static_cast<Decl*>(data[0]); }
1567 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001568};
Ted Kremenek035dc412010-11-13 00:36:50 +00001569class TypeLocVisit : public VisitorJob {
1570public:
1571 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1572 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1573 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1574
1575 static bool classof(const VisitorJob *VJ) {
1576 return VJ->getKind() == TypeLocVisitKind;
1577 }
1578
Ted Kremenek82f3c502010-11-15 22:23:26 +00001579 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001580 QualType T = QualType::getFromOpaquePtr(data[0]);
1581 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001582 }
1583};
1584
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001585class LabelRefVisit : public VisitorJob {
1586public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001587 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1588 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001589 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001590
1591 static bool classof(const VisitorJob *VJ) {
1592 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1593 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001594 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001595 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001596 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001597};
1598class NestedNameSpecifierVisit : public VisitorJob {
1599public:
1600 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1601 CXCursor parent)
1602 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001603 NS, R.getBegin().getPtrEncoding(),
1604 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001605 static bool classof(const VisitorJob *VJ) {
1606 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1607 }
1608 NestedNameSpecifier *get() const {
1609 return static_cast<NestedNameSpecifier*>(data[0]);
1610 }
1611 SourceRange getSourceRange() const {
1612 SourceLocation A =
1613 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1614 SourceLocation B =
1615 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1616 return SourceRange(A, B);
1617 }
1618};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001619
1620class NestedNameSpecifierLocVisit : public VisitorJob {
1621public:
1622 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1623 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1624 Qualifier.getNestedNameSpecifier(),
1625 Qualifier.getOpaqueData()) { }
1626
1627 static bool classof(const VisitorJob *VJ) {
1628 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1629 }
1630
1631 NestedNameSpecifierLoc get() const {
1632 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1633 data[1]);
1634 }
1635};
1636
Ted Kremenekf64d8032010-11-18 00:02:32 +00001637class DeclarationNameInfoVisit : public VisitorJob {
1638public:
1639 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1640 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1641 static bool classof(const VisitorJob *VJ) {
1642 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1643 }
1644 DeclarationNameInfo get() const {
1645 Stmt *S = static_cast<Stmt*>(data[0]);
1646 switch (S->getStmtClass()) {
1647 default:
1648 llvm_unreachable("Unhandled Stmt");
1649 case Stmt::CXXDependentScopeMemberExprClass:
1650 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1651 case Stmt::DependentScopeDeclRefExprClass:
1652 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1653 }
1654 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001655};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001656class MemberRefVisit : public VisitorJob {
1657public:
1658 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1659 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001660 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001661 static bool classof(const VisitorJob *VJ) {
1662 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1663 }
1664 FieldDecl *get() const {
1665 return static_cast<FieldDecl*>(data[0]);
1666 }
1667 SourceLocation getLoc() const {
1668 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1669 }
1670};
Ted Kremenek28a71942010-11-13 00:36:47 +00001671class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1672 VisitorWorkList &WL;
1673 CXCursor Parent;
1674public:
1675 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1676 : WL(wl), Parent(parent) {}
1677
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001678 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001679 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001680 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001681 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001682 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001683 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001684 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001685 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001686 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001687 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001688 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001689 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001690 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001691 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001692 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001693 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001694 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001695 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1697 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001698 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001699 void VisitIfStmt(IfStmt *If);
1700 void VisitInitListExpr(InitListExpr *IE);
1701 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001702 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001703 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1705 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001706 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001707 void VisitStmt(Stmt *S);
1708 void VisitSwitchStmt(SwitchStmt *S);
1709 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001710 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001711 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001712 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001713 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001714 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001715
Ted Kremenek28a71942010-11-13 00:36:47 +00001716private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001717 void AddDeclarationNameInfo(Stmt *S);
1718 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001719 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001720 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001721 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001722 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001723 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001724 void AddTypeLoc(TypeSourceInfo *TI);
1725 void EnqueueChildren(Stmt *S);
1726};
1727} // end anonyous namespace
1728
Ted Kremenekf64d8032010-11-18 00:02:32 +00001729void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1730 // 'S' should always be non-null, since it comes from the
1731 // statement we are visiting.
1732 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1733}
1734void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1735 SourceRange R) {
1736 if (N)
1737 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1738}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001739
1740void
1741EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1742 if (Qualifier)
1743 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1744}
1745
Ted Kremenek28a71942010-11-13 00:36:47 +00001746void EnqueueVisitor::AddStmt(Stmt *S) {
1747 if (S)
1748 WL.push_back(StmtVisit(S, Parent));
1749}
Ted Kremenek035dc412010-11-13 00:36:50 +00001750void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001752 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001753}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001754void EnqueueVisitor::
1755 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1756 if (A)
1757 WL.push_back(ExplicitTemplateArgsVisit(
1758 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1759}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001760void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1761 if (D)
1762 WL.push_back(MemberRefVisit(D, L, Parent));
1763}
Ted Kremenek28a71942010-11-13 00:36:47 +00001764void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1765 if (TI)
1766 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1767 }
1768void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001769 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001770 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001771 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001772 }
1773 if (size == WL.size())
1774 return;
1775 // Now reverse the entries we just added. This will match the DFS
1776 // ordering performed by the worklist.
1777 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1778 std::reverse(I, E);
1779}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001780void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1781 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1782}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001783void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1784 AddDecl(B->getBlockDecl());
1785}
Ted Kremenek28a71942010-11-13 00:36:47 +00001786void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1787 EnqueueChildren(E);
1788 AddTypeLoc(E->getTypeSourceInfo());
1789}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001790void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1791 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1792 E = S->body_rend(); I != E; ++I) {
1793 AddStmt(*I);
1794 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001795}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001796void EnqueueVisitor::
1797VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1798 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1799 AddDeclarationNameInfo(E);
1800 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1801 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1802 if (!E->isImplicitAccess())
1803 AddStmt(E->getBase());
1804}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001805void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1806 // Enqueue the initializer or constructor arguments.
1807 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1808 AddStmt(E->getConstructorArg(I-1));
1809 // Enqueue the array size, if any.
1810 AddStmt(E->getArraySize());
1811 // Enqueue the allocated type.
1812 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1813 // Enqueue the placement arguments.
1814 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1815 AddStmt(E->getPlacementArg(I-1));
1816}
Ted Kremenek28a71942010-11-13 00:36:47 +00001817void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001818 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1819 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001820 AddStmt(CE->getCallee());
1821 AddStmt(CE->getArg(0));
1822}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001823void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1824 // Visit the name of the type being destroyed.
1825 AddTypeLoc(E->getDestroyedTypeInfo());
1826 // Visit the scope type that looks disturbingly like the nested-name-specifier
1827 // but isn't.
1828 AddTypeLoc(E->getScopeTypeInfo());
1829 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001830 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1831 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001832 // Visit base expression.
1833 AddStmt(E->getBase());
1834}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001835void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1836 AddTypeLoc(E->getTypeSourceInfo());
1837}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001838void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1839 EnqueueChildren(E);
1840 AddTypeLoc(E->getTypeSourceInfo());
1841}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001842void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1843 EnqueueChildren(E);
1844 if (E->isTypeOperand())
1845 AddTypeLoc(E->getTypeOperandSourceInfo());
1846}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001847
1848void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1849 *E) {
1850 EnqueueChildren(E);
1851 AddTypeLoc(E->getTypeSourceInfo());
1852}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001853void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1854 EnqueueChildren(E);
1855 if (E->isTypeOperand())
1856 AddTypeLoc(E->getTypeOperandSourceInfo());
1857}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001858void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001859 if (DR->hasExplicitTemplateArgs()) {
1860 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1861 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001862 WL.push_back(DeclRefExprParts(DR, Parent));
1863}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001864void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1865 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1866 AddDeclarationNameInfo(E);
1867 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1868 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1869}
Ted Kremenek035dc412010-11-13 00:36:50 +00001870void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1871 unsigned size = WL.size();
1872 bool isFirst = true;
1873 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1874 D != DEnd; ++D) {
1875 AddDecl(*D, isFirst);
1876 isFirst = false;
1877 }
1878 if (size == WL.size())
1879 return;
1880 // Now reverse the entries we just added. This will match the DFS
1881 // ordering performed by the worklist.
1882 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1883 std::reverse(I, E);
1884}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001885void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1886 AddStmt(E->getInit());
1887 typedef DesignatedInitExpr::Designator Designator;
1888 for (DesignatedInitExpr::reverse_designators_iterator
1889 D = E->designators_rbegin(), DEnd = E->designators_rend();
1890 D != DEnd; ++D) {
1891 if (D->isFieldDesignator()) {
1892 if (FieldDecl *Field = D->getField())
1893 AddMemberRef(Field, D->getFieldLoc());
1894 continue;
1895 }
1896 if (D->isArrayDesignator()) {
1897 AddStmt(E->getArrayIndex(*D));
1898 continue;
1899 }
1900 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1901 AddStmt(E->getArrayRangeEnd(*D));
1902 AddStmt(E->getArrayRangeStart(*D));
1903 }
1904}
Ted Kremenek28a71942010-11-13 00:36:47 +00001905void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1906 EnqueueChildren(E);
1907 AddTypeLoc(E->getTypeInfoAsWritten());
1908}
1909void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1910 AddStmt(FS->getBody());
1911 AddStmt(FS->getInc());
1912 AddStmt(FS->getCond());
1913 AddDecl(FS->getConditionVariable());
1914 AddStmt(FS->getInit());
1915}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001916void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1917 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1918}
Ted Kremenek28a71942010-11-13 00:36:47 +00001919void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1920 AddStmt(If->getElse());
1921 AddStmt(If->getThen());
1922 AddStmt(If->getCond());
1923 AddDecl(If->getConditionVariable());
1924}
1925void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1926 // We care about the syntactic form of the initializer list, only.
1927 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1928 IE = Syntactic;
1929 EnqueueChildren(IE);
1930}
1931void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001932 WL.push_back(MemberExprParts(M, Parent));
1933
1934 // If the base of the member access expression is an implicit 'this', don't
1935 // visit it.
1936 // FIXME: If we ever want to show these implicit accesses, this will be
1937 // unfortunate. However, clang_getCursor() relies on this behavior.
1938 if (CXXThisExpr *This
1939 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1940 if (This->isImplicit())
1941 return;
1942
Ted Kremenek28a71942010-11-13 00:36:47 +00001943 AddStmt(M->getBase());
1944}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001945void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1946 AddTypeLoc(E->getEncodedTypeSourceInfo());
1947}
Ted Kremenek28a71942010-11-13 00:36:47 +00001948void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1949 EnqueueChildren(M);
1950 AddTypeLoc(M->getClassReceiverTypeInfo());
1951}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001952void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1953 // Visit the components of the offsetof expression.
1954 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1955 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1956 const OffsetOfNode &Node = E->getComponent(I-1);
1957 switch (Node.getKind()) {
1958 case OffsetOfNode::Array:
1959 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1960 break;
1961 case OffsetOfNode::Field:
1962 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1963 break;
1964 case OffsetOfNode::Identifier:
1965 case OffsetOfNode::Base:
1966 continue;
1967 }
1968 }
1969 // Visit the type into which we're computing the offset.
1970 AddTypeLoc(E->getTypeSourceInfo());
1971}
Ted Kremenek28a71942010-11-13 00:36:47 +00001972void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001973 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001974 WL.push_back(OverloadExprParts(E, Parent));
1975}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001976void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1977 EnqueueChildren(E);
1978 if (E->isArgumentType())
1979 AddTypeLoc(E->getArgumentTypeInfo());
1980}
Ted Kremenek28a71942010-11-13 00:36:47 +00001981void EnqueueVisitor::VisitStmt(Stmt *S) {
1982 EnqueueChildren(S);
1983}
1984void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1985 AddStmt(S->getBody());
1986 AddStmt(S->getCond());
1987 AddDecl(S->getConditionVariable());
1988}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001989
Ted Kremenek28a71942010-11-13 00:36:47 +00001990void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1991 AddStmt(W->getBody());
1992 AddStmt(W->getCond());
1993 AddDecl(W->getConditionVariable());
1994}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001995void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1996 AddTypeLoc(E->getQueriedTypeSourceInfo());
1997}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001998
1999void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002000 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002001 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002002}
2003
Ted Kremenek28a71942010-11-13 00:36:47 +00002004void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2005 VisitOverloadExpr(U);
2006 if (!U->isImplicitAccess())
2007 AddStmt(U->getBase());
2008}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002009void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2010 AddStmt(E->getSubExpr());
2011 AddTypeLoc(E->getWrittenTypeInfo());
2012}
Douglas Gregor94d96292011-01-19 20:34:17 +00002013void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2014 WL.push_back(SizeOfPackExprParts(E, Parent));
2015}
Ted Kremenek60458782010-11-12 21:34:16 +00002016
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002017void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002018 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002019}
2020
2021bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2022 if (RegionOfInterest.isValid()) {
2023 SourceRange Range = getRawCursorExtent(C);
2024 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2025 return false;
2026 }
2027 return true;
2028}
2029
2030bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2031 while (!WL.empty()) {
2032 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002033 VisitorJob LI = WL.back();
2034 WL.pop_back();
2035
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002036 // Set the Parent field, then back to its old value once we're done.
2037 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2038
2039 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002040 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002041 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002042 if (!D)
2043 continue;
2044
2045 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002046 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002047 return true;
2048
2049 continue;
2050 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002051 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2052 const ExplicitTemplateArgumentList *ArgList =
2053 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2054 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2055 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2056 Arg != ArgEnd; ++Arg) {
2057 if (VisitTemplateArgumentLoc(*Arg))
2058 return true;
2059 }
2060 continue;
2061 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002062 case VisitorJob::TypeLocVisitKind: {
2063 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002064 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002065 return true;
2066 continue;
2067 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002068 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002069 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002070 if (LabelStmt *stmt = LS->getStmt()) {
2071 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2072 TU))) {
2073 return true;
2074 }
2075 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002076 continue;
2077 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002078
Ted Kremenekf64d8032010-11-18 00:02:32 +00002079 case VisitorJob::NestedNameSpecifierVisitKind: {
2080 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2081 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2082 return true;
2083 continue;
2084 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002085
2086 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2087 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2088 if (VisitNestedNameSpecifierLoc(V->get()))
2089 return true;
2090 continue;
2091 }
2092
Ted Kremenekf64d8032010-11-18 00:02:32 +00002093 case VisitorJob::DeclarationNameInfoVisitKind: {
2094 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2095 ->get()))
2096 return true;
2097 continue;
2098 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002099 case VisitorJob::MemberRefVisitKind: {
2100 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2101 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2102 return true;
2103 continue;
2104 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002105 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002106 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002107 if (!S)
2108 continue;
2109
Ted Kremenekf1107452010-11-12 18:26:56 +00002110 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002111 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002112 if (!IsInRegionOfInterest(Cursor))
2113 continue;
2114 switch (Visitor(Cursor, Parent, ClientData)) {
2115 case CXChildVisit_Break: return true;
2116 case CXChildVisit_Continue: break;
2117 case CXChildVisit_Recurse:
2118 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002119 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002120 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002121 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002122 }
2123 case VisitorJob::MemberExprPartsKind: {
2124 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002125 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002126
2127 // Visit the nested-name-specifier
2128 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2129 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2130 return true;
2131
2132 // Visit the declaration name.
2133 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2134 return true;
2135
2136 // Visit the explicitly-specified template arguments, if any.
2137 if (M->hasExplicitTemplateArgs()) {
2138 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2139 *ArgEnd = Arg + M->getNumTemplateArgs();
2140 Arg != ArgEnd; ++Arg) {
2141 if (VisitTemplateArgumentLoc(*Arg))
2142 return true;
2143 }
2144 }
2145 continue;
2146 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002147 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002148 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002149 // Visit nested-name-specifier, if present.
2150 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2151 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2152 return true;
2153 // Visit declaration name.
2154 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2155 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002156 continue;
2157 }
Ted Kremenek60458782010-11-12 21:34:16 +00002158 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002159 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002160 // Visit the nested-name-specifier.
2161 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2162 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2163 return true;
2164 // Visit the declaration name.
2165 if (VisitDeclarationNameInfo(O->getNameInfo()))
2166 return true;
2167 // Visit the overloaded declaration reference.
2168 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2169 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002170 continue;
2171 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002172 case VisitorJob::SizeOfPackExprPartsKind: {
2173 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2174 NamedDecl *Pack = E->getPack();
2175 if (isa<TemplateTypeParmDecl>(Pack)) {
2176 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2177 E->getPackLoc(), TU)))
2178 return true;
2179
2180 continue;
2181 }
2182
2183 if (isa<TemplateTemplateParmDecl>(Pack)) {
2184 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2185 E->getPackLoc(), TU)))
2186 return true;
2187
2188 continue;
2189 }
2190
2191 // Non-type template parameter packs and function parameter packs are
2192 // treated like DeclRefExpr cursors.
2193 continue;
2194 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002195 }
2196 }
2197 return false;
2198}
2199
Ted Kremenekcdba6592010-11-18 00:42:18 +00002200bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002201 VisitorWorkList *WL = 0;
2202 if (!WorkListFreeList.empty()) {
2203 WL = WorkListFreeList.back();
2204 WL->clear();
2205 WorkListFreeList.pop_back();
2206 }
2207 else {
2208 WL = new VisitorWorkList();
2209 WorkListCache.push_back(WL);
2210 }
2211 EnqueueWorkList(*WL, S);
2212 bool result = RunVisitorWorkList(*WL);
2213 WorkListFreeList.push_back(WL);
2214 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002215}
2216
2217//===----------------------------------------------------------------------===//
2218// Misc. API hooks.
2219//===----------------------------------------------------------------------===//
2220
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002221static llvm::sys::Mutex EnableMultithreadingMutex;
2222static bool EnabledMultithreading;
2223
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002224extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002225CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2226 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002227 // Disable pretty stack trace functionality, which will otherwise be a very
2228 // poor citizen of the world and set up all sorts of signal handlers.
2229 llvm::DisablePrettyStackTrace = true;
2230
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002231 // We use crash recovery to make some of our APIs more reliable, implicitly
2232 // enable it.
2233 llvm::CrashRecoveryContext::Enable();
2234
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002235 // Enable support for multithreading in LLVM.
2236 {
2237 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2238 if (!EnabledMultithreading) {
2239 llvm::llvm_start_multithreaded();
2240 EnabledMultithreading = true;
2241 }
2242 }
2243
Douglas Gregora030b7c2010-01-22 20:35:53 +00002244 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002245 if (excludeDeclarationsFromPCH)
2246 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002247 if (displayDiagnostics)
2248 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002249 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002250}
2251
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002252void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002253 if (CIdx)
2254 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002255}
2256
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002257CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002258 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002259 if (!CIdx)
2260 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002261
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002262 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002263 FileSystemOptions FileSystemOpts;
2264 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002265
Douglas Gregor28019772010-04-05 23:52:57 +00002266 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002267 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002268 CXXIdx->getOnlyLocalDecls(),
2269 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002270 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002271}
2272
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002273unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002274 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002275 CXTranslationUnit_CacheCompletionResults |
2276 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002277}
2278
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002279CXTranslationUnit
2280clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2281 const char *source_filename,
2282 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002283 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002284 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002285 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002286 return clang_parseTranslationUnit(CIdx, source_filename,
2287 command_line_args, num_command_line_args,
2288 unsaved_files, num_unsaved_files,
2289 CXTranslationUnit_DetailedPreprocessingRecord);
2290}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002291
2292struct ParseTranslationUnitInfo {
2293 CXIndex CIdx;
2294 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002295 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002296 int num_command_line_args;
2297 struct CXUnsavedFile *unsaved_files;
2298 unsigned num_unsaved_files;
2299 unsigned options;
2300 CXTranslationUnit result;
2301};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002302static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002303 ParseTranslationUnitInfo *PTUI =
2304 static_cast<ParseTranslationUnitInfo*>(UserData);
2305 CXIndex CIdx = PTUI->CIdx;
2306 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002307 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002308 int num_command_line_args = PTUI->num_command_line_args;
2309 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2310 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2311 unsigned options = PTUI->options;
2312 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002313
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002314 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002315 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002316
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002317 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2318
Douglas Gregor44c181a2010-07-23 00:33:23 +00002319 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002320 bool CompleteTranslationUnit
2321 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002322 bool CacheCodeCompetionResults
2323 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002324 bool CXXPrecompilePreamble
2325 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2326 bool CXXChainedPCH
2327 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002328
Douglas Gregor5352ac02010-01-28 00:27:43 +00002329 // Configure the diagnostics.
2330 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002331 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002332 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2333 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002334
Douglas Gregor4db64a42010-01-23 00:14:00 +00002335 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2336 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002337 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002338 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002339 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002340 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2341 Buffer));
2342 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002343
Douglas Gregorb10daed2010-10-11 16:52:23 +00002344 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002345
Ted Kremenek139ba862009-10-22 00:03:57 +00002346 // The 'source_filename' argument is optional. If the caller does not
2347 // specify it then it is assumed that the source file is specified
2348 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002349 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002350 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002351
2352 // Since the Clang C library is primarily used by batch tools dealing with
2353 // (often very broken) source code, where spell-checking can have a
2354 // significant negative impact on performance (particularly when
2355 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002356 // Only do this if we haven't found a spell-checking-related argument.
2357 bool FoundSpellCheckingArgument = false;
2358 for (int I = 0; I != num_command_line_args; ++I) {
2359 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2360 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2361 FoundSpellCheckingArgument = true;
2362 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002363 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002364 }
2365 if (!FoundSpellCheckingArgument)
2366 Args.push_back("-fno-spell-checking");
2367
2368 Args.insert(Args.end(), command_line_args,
2369 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002370
Douglas Gregor44c181a2010-07-23 00:33:23 +00002371 // Do we need the detailed preprocessing record?
2372 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002373 Args.push_back("-Xclang");
2374 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002375 }
2376
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002377 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002378 llvm::OwningPtr<ASTUnit> Unit(
2379 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2380 Diags,
2381 CXXIdx->getClangResourcesPath(),
2382 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002383 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002384 RemappedFiles.data(),
2385 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002386 PrecompilePreamble,
2387 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002388 CacheCodeCompetionResults,
2389 CXXPrecompilePreamble,
2390 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002391
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002392 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002393 // Make sure to check that 'Unit' is non-NULL.
2394 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2395 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2396 DEnd = Unit->stored_diag_end();
2397 D != DEnd; ++D) {
2398 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2399 CXString Msg = clang_formatDiagnostic(&Diag,
2400 clang_defaultDiagnosticDisplayOptions());
2401 fprintf(stderr, "%s\n", clang_getCString(Msg));
2402 clang_disposeString(Msg);
2403 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002404#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002405 // On Windows, force a flush, since there may be multiple copies of
2406 // stderr and stdout in the file system, all with different buffers
2407 // but writing to the same device.
2408 fflush(stderr);
2409#endif
2410 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002411 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002412
Ted Kremeneka60ed472010-11-16 08:15:36 +00002413 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002414}
2415CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2416 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002417 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002418 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002419 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002420 unsigned num_unsaved_files,
2421 unsigned options) {
2422 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002423 num_command_line_args, unsaved_files,
2424 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002425 llvm::CrashRecoveryContext CRC;
2426
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002427 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002428 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2429 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2430 fprintf(stderr, " 'command_line_args' : [");
2431 for (int i = 0; i != num_command_line_args; ++i) {
2432 if (i)
2433 fprintf(stderr, ", ");
2434 fprintf(stderr, "'%s'", command_line_args[i]);
2435 }
2436 fprintf(stderr, "],\n");
2437 fprintf(stderr, " 'unsaved_files' : [");
2438 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2439 if (i)
2440 fprintf(stderr, ", ");
2441 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2442 unsaved_files[i].Length);
2443 }
2444 fprintf(stderr, "],\n");
2445 fprintf(stderr, " 'options' : %d,\n", options);
2446 fprintf(stderr, "}\n");
2447
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002448 return 0;
2449 }
2450
2451 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002452}
2453
Douglas Gregor19998442010-08-13 15:35:05 +00002454unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2455 return CXSaveTranslationUnit_None;
2456}
2457
2458int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2459 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002460 if (!TU)
2461 return 1;
2462
Ted Kremeneka60ed472010-11-16 08:15:36 +00002463 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002464}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002465
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002466void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002467 if (CTUnit) {
2468 // If the translation unit has been marked as unsafe to free, just discard
2469 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002470 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002471 return;
2472
Ted Kremeneka60ed472010-11-16 08:15:36 +00002473 delete static_cast<ASTUnit *>(CTUnit->TUData);
2474 disposeCXStringPool(CTUnit->StringPool);
2475 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002476 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002477}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002478
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002479unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2480 return CXReparse_None;
2481}
2482
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002483struct ReparseTranslationUnitInfo {
2484 CXTranslationUnit TU;
2485 unsigned num_unsaved_files;
2486 struct CXUnsavedFile *unsaved_files;
2487 unsigned options;
2488 int result;
2489};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002490
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002491static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002492 ReparseTranslationUnitInfo *RTUI =
2493 static_cast<ReparseTranslationUnitInfo*>(UserData);
2494 CXTranslationUnit TU = RTUI->TU;
2495 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2496 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2497 unsigned options = RTUI->options;
2498 (void) options;
2499 RTUI->result = 1;
2500
Douglas Gregorabc563f2010-07-19 21:46:24 +00002501 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002502 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002503
Ted Kremeneka60ed472010-11-16 08:15:36 +00002504 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002505 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002506
2507 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2508 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2509 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2510 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002511 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002512 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2513 Buffer));
2514 }
2515
Douglas Gregor593b0c12010-09-23 18:47:53 +00002516 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2517 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002518}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002519
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002520int clang_reparseTranslationUnit(CXTranslationUnit TU,
2521 unsigned num_unsaved_files,
2522 struct CXUnsavedFile *unsaved_files,
2523 unsigned options) {
2524 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2525 options, 0 };
2526 llvm::CrashRecoveryContext CRC;
2527
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002528 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002529 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002530 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002531 return 1;
2532 }
2533
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002534
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002535 return RTUI.result;
2536}
2537
Douglas Gregordf95a132010-08-09 20:45:32 +00002538
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002539CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002540 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002541 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002542
Ted Kremeneka60ed472010-11-16 08:15:36 +00002543 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002544 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002545}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002546
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002547CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002548 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002549 return Result;
2550}
2551
Ted Kremenekfb480492010-01-13 21:46:36 +00002552} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002553
Ted Kremenekfb480492010-01-13 21:46:36 +00002554//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002555// CXSourceLocation and CXSourceRange Operations.
2556//===----------------------------------------------------------------------===//
2557
Douglas Gregorb9790342010-01-22 21:44:22 +00002558extern "C" {
2559CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002560 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002561 return Result;
2562}
2563
2564unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002565 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2566 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2567 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002568}
2569
2570CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2571 CXFile file,
2572 unsigned line,
2573 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002574 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002575 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002576
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002577 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002578 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002579 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002580 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002581 = CXXUnit->getSourceManager().getLocation(File, line, column);
2582 if (SLoc.isInvalid()) {
2583 if (Logging)
2584 llvm::errs() << "clang_getLocation(\"" << File->getName()
2585 << "\", " << line << ", " << column << ") = invalid\n";
2586 return clang_getNullLocation();
2587 }
2588
2589 if (Logging)
2590 llvm::errs() << "clang_getLocation(\"" << File->getName()
2591 << "\", " << line << ", " << column << ") = "
2592 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002593
2594 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2595}
2596
2597CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2598 CXFile file,
2599 unsigned offset) {
2600 if (!tu || !file)
2601 return clang_getNullLocation();
2602
Ted Kremeneka60ed472010-11-16 08:15:36 +00002603 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002604 SourceLocation Start
2605 = CXXUnit->getSourceManager().getLocation(
2606 static_cast<const FileEntry *>(file),
2607 1, 1);
2608 if (Start.isInvalid()) return clang_getNullLocation();
2609
2610 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2611
2612 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002613
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002614 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002615}
2616
Douglas Gregor5352ac02010-01-28 00:27:43 +00002617CXSourceRange clang_getNullRange() {
2618 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2619 return Result;
2620}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002621
Douglas Gregor5352ac02010-01-28 00:27:43 +00002622CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2623 if (begin.ptr_data[0] != end.ptr_data[0] ||
2624 begin.ptr_data[1] != end.ptr_data[1])
2625 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002626
2627 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002628 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002629 return Result;
2630}
2631
Douglas Gregor46766dc2010-01-26 19:19:08 +00002632void clang_getInstantiationLocation(CXSourceLocation location,
2633 CXFile *file,
2634 unsigned *line,
2635 unsigned *column,
2636 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002637 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2638
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002639 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002640 if (file)
2641 *file = 0;
2642 if (line)
2643 *line = 0;
2644 if (column)
2645 *column = 0;
2646 if (offset)
2647 *offset = 0;
2648 return;
2649 }
2650
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002651 const SourceManager &SM =
2652 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002653 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002654
2655 if (file)
2656 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2657 if (line)
2658 *line = SM.getInstantiationLineNumber(InstLoc);
2659 if (column)
2660 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002661 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002662 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002663}
2664
Douglas Gregora9b06d42010-11-09 06:24:54 +00002665void clang_getSpellingLocation(CXSourceLocation location,
2666 CXFile *file,
2667 unsigned *line,
2668 unsigned *column,
2669 unsigned *offset) {
2670 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2671
2672 if (!location.ptr_data[0] || Loc.isInvalid()) {
2673 if (file)
2674 *file = 0;
2675 if (line)
2676 *line = 0;
2677 if (column)
2678 *column = 0;
2679 if (offset)
2680 *offset = 0;
2681 return;
2682 }
2683
2684 const SourceManager &SM =
2685 *static_cast<const SourceManager*>(location.ptr_data[0]);
2686 SourceLocation SpellLoc = Loc;
2687 if (SpellLoc.isMacroID()) {
2688 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2689 if (SimpleSpellingLoc.isFileID() &&
2690 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2691 SpellLoc = SimpleSpellingLoc;
2692 else
2693 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2694 }
2695
2696 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2697 FileID FID = LocInfo.first;
2698 unsigned FileOffset = LocInfo.second;
2699
2700 if (file)
2701 *file = (void *)SM.getFileEntryForID(FID);
2702 if (line)
2703 *line = SM.getLineNumber(FID, FileOffset);
2704 if (column)
2705 *column = SM.getColumnNumber(FID, FileOffset);
2706 if (offset)
2707 *offset = FileOffset;
2708}
2709
Douglas Gregor1db19de2010-01-19 21:36:55 +00002710CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002711 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002712 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002713 return Result;
2714}
2715
2716CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002717 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002718 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002719 return Result;
2720}
2721
Douglas Gregorb9790342010-01-22 21:44:22 +00002722} // end: extern "C"
2723
Douglas Gregor1db19de2010-01-19 21:36:55 +00002724//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002725// CXFile Operations.
2726//===----------------------------------------------------------------------===//
2727
2728extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002729CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002730 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002731 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002732
Steve Naroff88145032009-10-27 14:35:18 +00002733 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002734 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002735}
2736
2737time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002738 if (!SFile)
2739 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002740
Steve Naroff88145032009-10-27 14:35:18 +00002741 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2742 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002743}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002744
Douglas Gregorb9790342010-01-22 21:44:22 +00002745CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2746 if (!tu)
2747 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002748
Ted Kremeneka60ed472010-11-16 08:15:36 +00002749 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002750
Douglas Gregorb9790342010-01-22 21:44:22 +00002751 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002752 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002753}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002754
Ted Kremenekfb480492010-01-13 21:46:36 +00002755} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002756
Ted Kremenekfb480492010-01-13 21:46:36 +00002757//===----------------------------------------------------------------------===//
2758// CXCursor Operations.
2759//===----------------------------------------------------------------------===//
2760
Ted Kremenekfb480492010-01-13 21:46:36 +00002761static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002762 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2763 return getDeclFromExpr(CE->getSubExpr());
2764
Ted Kremenekfb480492010-01-13 21:46:36 +00002765 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2766 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002767 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2768 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002769 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2770 return ME->getMemberDecl();
2771 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2772 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002773 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002774 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002775
Ted Kremenekfb480492010-01-13 21:46:36 +00002776 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2777 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002778 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2779 if (!CE->isElidable())
2780 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002781 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2782 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002783
Douglas Gregordb1314e2010-10-01 21:11:22 +00002784 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2785 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002786 if (SubstNonTypeTemplateParmPackExpr *NTTP
2787 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2788 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002789 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2790 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2791 isa<ParmVarDecl>(SizeOfPack->getPack()))
2792 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002793
Ted Kremenekfb480492010-01-13 21:46:36 +00002794 return 0;
2795}
2796
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002797static SourceLocation getLocationFromExpr(Expr *E) {
2798 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2799 return /*FIXME:*/Msg->getLeftLoc();
2800 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2801 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002802 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2803 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002804 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2805 return Member->getMemberLoc();
2806 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2807 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002808 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2809 return SizeOfPack->getPackLoc();
2810
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002811 return E->getLocStart();
2812}
2813
Ted Kremenekfb480492010-01-13 21:46:36 +00002814extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002815
2816unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002817 CXCursorVisitor visitor,
2818 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002819 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2820 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002821 return CursorVis.VisitChildren(parent);
2822}
2823
David Chisnall3387c652010-11-03 14:12:26 +00002824#ifndef __has_feature
2825#define __has_feature(x) 0
2826#endif
2827#if __has_feature(blocks)
2828typedef enum CXChildVisitResult
2829 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2830
2831static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2832 CXClientData client_data) {
2833 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2834 return block(cursor, parent);
2835}
2836#else
2837// If we are compiled with a compiler that doesn't have native blocks support,
2838// define and call the block manually, so the
2839typedef struct _CXChildVisitResult
2840{
2841 void *isa;
2842 int flags;
2843 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002844 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2845 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002846} *CXCursorVisitorBlock;
2847
2848static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2849 CXClientData client_data) {
2850 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2851 return block->invoke(block, cursor, parent);
2852}
2853#endif
2854
2855
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002856unsigned clang_visitChildrenWithBlock(CXCursor parent,
2857 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002858 return clang_visitChildren(parent, visitWithBlock, block);
2859}
2860
Douglas Gregor78205d42010-01-20 21:45:58 +00002861static CXString getDeclSpelling(Decl *D) {
2862 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002863 if (!ND) {
2864 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2865 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2866 return createCXString(Property->getIdentifier()->getName());
2867
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002868 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002869 }
2870
Douglas Gregor78205d42010-01-20 21:45:58 +00002871 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002872 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002873
Douglas Gregor78205d42010-01-20 21:45:58 +00002874 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2875 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2876 // and returns different names. NamedDecl returns the class name and
2877 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002878 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002879
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002880 if (isa<UsingDirectiveDecl>(D))
2881 return createCXString("");
2882
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002883 llvm::SmallString<1024> S;
2884 llvm::raw_svector_ostream os(S);
2885 ND->printName(os);
2886
2887 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002888}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002889
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002890CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002891 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002892 return clang_getTranslationUnitSpelling(
2893 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002894
Steve Narofff334b4e2009-09-02 18:26:48 +00002895 if (clang_isReference(C.kind)) {
2896 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002897 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002898 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002899 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002900 }
2901 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002902 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002903 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002904 }
2905 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002906 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002907 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002908 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002909 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002910 case CXCursor_CXXBaseSpecifier: {
2911 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2912 return createCXString(B->getType().getAsString());
2913 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002914 case CXCursor_TypeRef: {
2915 TypeDecl *Type = getCursorTypeRef(C).first;
2916 assert(Type && "Missing type decl");
2917
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002918 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2919 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002920 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002921 case CXCursor_TemplateRef: {
2922 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002923 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002924
2925 return createCXString(Template->getNameAsString());
2926 }
Douglas Gregor69319002010-08-31 23:48:11 +00002927
2928 case CXCursor_NamespaceRef: {
2929 NamedDecl *NS = getCursorNamespaceRef(C).first;
2930 assert(NS && "Missing namespace decl");
2931
2932 return createCXString(NS->getNameAsString());
2933 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002934
Douglas Gregora67e03f2010-09-09 21:42:20 +00002935 case CXCursor_MemberRef: {
2936 FieldDecl *Field = getCursorMemberRef(C).first;
2937 assert(Field && "Missing member decl");
2938
2939 return createCXString(Field->getNameAsString());
2940 }
2941
Douglas Gregor36897b02010-09-10 00:22:18 +00002942 case CXCursor_LabelRef: {
2943 LabelStmt *Label = getCursorLabelRef(C).first;
2944 assert(Label && "Missing label");
2945
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002946 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002947 }
2948
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002949 case CXCursor_OverloadedDeclRef: {
2950 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2951 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2952 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2953 return createCXString(ND->getNameAsString());
2954 return createCXString("");
2955 }
2956 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2957 return createCXString(E->getName().getAsString());
2958 OverloadedTemplateStorage *Ovl
2959 = Storage.get<OverloadedTemplateStorage*>();
2960 if (Ovl->size() == 0)
2961 return createCXString("");
2962 return createCXString((*Ovl->begin())->getNameAsString());
2963 }
2964
Daniel Dunbaracca7252009-11-30 20:42:49 +00002965 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002966 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002967 }
2968 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002969
2970 if (clang_isExpression(C.kind)) {
2971 Decl *D = getDeclFromExpr(getCursorExpr(C));
2972 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002973 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002974 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002975 }
2976
Douglas Gregor36897b02010-09-10 00:22:18 +00002977 if (clang_isStatement(C.kind)) {
2978 Stmt *S = getCursorStmt(C);
2979 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002980 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002981
2982 return createCXString("");
2983 }
2984
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002985 if (C.kind == CXCursor_MacroInstantiation)
2986 return createCXString(getCursorMacroInstantiation(C)->getName()
2987 ->getNameStart());
2988
Douglas Gregor572feb22010-03-18 18:04:21 +00002989 if (C.kind == CXCursor_MacroDefinition)
2990 return createCXString(getCursorMacroDefinition(C)->getName()
2991 ->getNameStart());
2992
Douglas Gregorecdcb882010-10-20 22:00:55 +00002993 if (C.kind == CXCursor_InclusionDirective)
2994 return createCXString(getCursorInclusionDirective(C)->getFileName());
2995
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002996 if (clang_isDeclaration(C.kind))
2997 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002998
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002999 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003000}
3001
Douglas Gregor358559d2010-10-02 22:49:11 +00003002CXString clang_getCursorDisplayName(CXCursor C) {
3003 if (!clang_isDeclaration(C.kind))
3004 return clang_getCursorSpelling(C);
3005
3006 Decl *D = getCursorDecl(C);
3007 if (!D)
3008 return createCXString("");
3009
3010 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3011 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3012 D = FunTmpl->getTemplatedDecl();
3013
3014 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3015 llvm::SmallString<64> Str;
3016 llvm::raw_svector_ostream OS(Str);
3017 OS << Function->getNameAsString();
3018 if (Function->getPrimaryTemplate())
3019 OS << "<>";
3020 OS << "(";
3021 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3022 if (I)
3023 OS << ", ";
3024 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3025 }
3026
3027 if (Function->isVariadic()) {
3028 if (Function->getNumParams())
3029 OS << ", ";
3030 OS << "...";
3031 }
3032 OS << ")";
3033 return createCXString(OS.str());
3034 }
3035
3036 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3037 llvm::SmallString<64> Str;
3038 llvm::raw_svector_ostream OS(Str);
3039 OS << ClassTemplate->getNameAsString();
3040 OS << "<";
3041 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3042 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3043 if (I)
3044 OS << ", ";
3045
3046 NamedDecl *Param = Params->getParam(I);
3047 if (Param->getIdentifier()) {
3048 OS << Param->getIdentifier()->getName();
3049 continue;
3050 }
3051
3052 // There is no parameter name, which makes this tricky. Try to come up
3053 // with something useful that isn't too long.
3054 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3055 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3056 else if (NonTypeTemplateParmDecl *NTTP
3057 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3058 OS << NTTP->getType().getAsString(Policy);
3059 else
3060 OS << "template<...> class";
3061 }
3062
3063 OS << ">";
3064 return createCXString(OS.str());
3065 }
3066
3067 if (ClassTemplateSpecializationDecl *ClassSpec
3068 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3069 // If the type was explicitly written, use that.
3070 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3071 return createCXString(TSInfo->getType().getAsString(Policy));
3072
3073 llvm::SmallString<64> Str;
3074 llvm::raw_svector_ostream OS(Str);
3075 OS << ClassSpec->getNameAsString();
3076 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003077 ClassSpec->getTemplateArgs().data(),
3078 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003079 Policy);
3080 return createCXString(OS.str());
3081 }
3082
3083 return clang_getCursorSpelling(C);
3084}
3085
Ted Kremeneke68fff62010-02-17 00:41:32 +00003086CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003087 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003088 case CXCursor_FunctionDecl:
3089 return createCXString("FunctionDecl");
3090 case CXCursor_TypedefDecl:
3091 return createCXString("TypedefDecl");
3092 case CXCursor_EnumDecl:
3093 return createCXString("EnumDecl");
3094 case CXCursor_EnumConstantDecl:
3095 return createCXString("EnumConstantDecl");
3096 case CXCursor_StructDecl:
3097 return createCXString("StructDecl");
3098 case CXCursor_UnionDecl:
3099 return createCXString("UnionDecl");
3100 case CXCursor_ClassDecl:
3101 return createCXString("ClassDecl");
3102 case CXCursor_FieldDecl:
3103 return createCXString("FieldDecl");
3104 case CXCursor_VarDecl:
3105 return createCXString("VarDecl");
3106 case CXCursor_ParmDecl:
3107 return createCXString("ParmDecl");
3108 case CXCursor_ObjCInterfaceDecl:
3109 return createCXString("ObjCInterfaceDecl");
3110 case CXCursor_ObjCCategoryDecl:
3111 return createCXString("ObjCCategoryDecl");
3112 case CXCursor_ObjCProtocolDecl:
3113 return createCXString("ObjCProtocolDecl");
3114 case CXCursor_ObjCPropertyDecl:
3115 return createCXString("ObjCPropertyDecl");
3116 case CXCursor_ObjCIvarDecl:
3117 return createCXString("ObjCIvarDecl");
3118 case CXCursor_ObjCInstanceMethodDecl:
3119 return createCXString("ObjCInstanceMethodDecl");
3120 case CXCursor_ObjCClassMethodDecl:
3121 return createCXString("ObjCClassMethodDecl");
3122 case CXCursor_ObjCImplementationDecl:
3123 return createCXString("ObjCImplementationDecl");
3124 case CXCursor_ObjCCategoryImplDecl:
3125 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003126 case CXCursor_CXXMethod:
3127 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003128 case CXCursor_UnexposedDecl:
3129 return createCXString("UnexposedDecl");
3130 case CXCursor_ObjCSuperClassRef:
3131 return createCXString("ObjCSuperClassRef");
3132 case CXCursor_ObjCProtocolRef:
3133 return createCXString("ObjCProtocolRef");
3134 case CXCursor_ObjCClassRef:
3135 return createCXString("ObjCClassRef");
3136 case CXCursor_TypeRef:
3137 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003138 case CXCursor_TemplateRef:
3139 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003140 case CXCursor_NamespaceRef:
3141 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003142 case CXCursor_MemberRef:
3143 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003144 case CXCursor_LabelRef:
3145 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003146 case CXCursor_OverloadedDeclRef:
3147 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003148 case CXCursor_UnexposedExpr:
3149 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003150 case CXCursor_BlockExpr:
3151 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003152 case CXCursor_DeclRefExpr:
3153 return createCXString("DeclRefExpr");
3154 case CXCursor_MemberRefExpr:
3155 return createCXString("MemberRefExpr");
3156 case CXCursor_CallExpr:
3157 return createCXString("CallExpr");
3158 case CXCursor_ObjCMessageExpr:
3159 return createCXString("ObjCMessageExpr");
3160 case CXCursor_UnexposedStmt:
3161 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003162 case CXCursor_LabelStmt:
3163 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003164 case CXCursor_InvalidFile:
3165 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003166 case CXCursor_InvalidCode:
3167 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003168 case CXCursor_NoDeclFound:
3169 return createCXString("NoDeclFound");
3170 case CXCursor_NotImplemented:
3171 return createCXString("NotImplemented");
3172 case CXCursor_TranslationUnit:
3173 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003174 case CXCursor_UnexposedAttr:
3175 return createCXString("UnexposedAttr");
3176 case CXCursor_IBActionAttr:
3177 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003178 case CXCursor_IBOutletAttr:
3179 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003180 case CXCursor_IBOutletCollectionAttr:
3181 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003182 case CXCursor_PreprocessingDirective:
3183 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003184 case CXCursor_MacroDefinition:
3185 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003186 case CXCursor_MacroInstantiation:
3187 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003188 case CXCursor_InclusionDirective:
3189 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003190 case CXCursor_Namespace:
3191 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003192 case CXCursor_LinkageSpec:
3193 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003194 case CXCursor_CXXBaseSpecifier:
3195 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003196 case CXCursor_Constructor:
3197 return createCXString("CXXConstructor");
3198 case CXCursor_Destructor:
3199 return createCXString("CXXDestructor");
3200 case CXCursor_ConversionFunction:
3201 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003202 case CXCursor_TemplateTypeParameter:
3203 return createCXString("TemplateTypeParameter");
3204 case CXCursor_NonTypeTemplateParameter:
3205 return createCXString("NonTypeTemplateParameter");
3206 case CXCursor_TemplateTemplateParameter:
3207 return createCXString("TemplateTemplateParameter");
3208 case CXCursor_FunctionTemplate:
3209 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003210 case CXCursor_ClassTemplate:
3211 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003212 case CXCursor_ClassTemplatePartialSpecialization:
3213 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003214 case CXCursor_NamespaceAlias:
3215 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003216 case CXCursor_UsingDirective:
3217 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003218 case CXCursor_UsingDeclaration:
3219 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003220 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003221
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003222 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003223 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003224}
Steve Naroff89922f82009-08-31 00:59:03 +00003225
Ted Kremeneke68fff62010-02-17 00:41:32 +00003226enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3227 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003228 CXClientData client_data) {
3229 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003230
3231 // If our current best cursor is the construction of a temporary object,
3232 // don't replace that cursor with a type reference, because we want
3233 // clang_getCursor() to point at the constructor.
3234 if (clang_isExpression(BestCursor->kind) &&
3235 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3236 cursor.kind == CXCursor_TypeRef)
3237 return CXChildVisit_Recurse;
3238
Douglas Gregor85fe1562010-12-10 07:23:11 +00003239 // Don't override a preprocessing cursor with another preprocessing
3240 // cursor; we want the outermost preprocessing cursor.
3241 if (clang_isPreprocessing(cursor.kind) &&
3242 clang_isPreprocessing(BestCursor->kind))
3243 return CXChildVisit_Recurse;
3244
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003245 *BestCursor = cursor;
3246 return CXChildVisit_Recurse;
3247}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003248
Douglas Gregorb9790342010-01-22 21:44:22 +00003249CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3250 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003251 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003252
Ted Kremeneka60ed472010-11-16 08:15:36 +00003253 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003254 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3255
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003256 // Translate the given source location to make it point at the beginning of
3257 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003258 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003259
3260 // Guard against an invalid SourceLocation, or we may assert in one
3261 // of the following calls.
3262 if (SLoc.isInvalid())
3263 return clang_getNullCursor();
3264
Douglas Gregor40749ee2010-11-03 00:35:38 +00003265 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003266 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3267 CXXUnit->getASTContext().getLangOptions());
3268
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003269 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3270 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003271 // FIXME: Would be great to have a "hint" cursor, then walk from that
3272 // hint cursor upward until we find a cursor whose source range encloses
3273 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003274 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3275 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003276 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003277 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003278 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003279
3280 if (Logging) {
3281 CXFile SearchFile;
3282 unsigned SearchLine, SearchColumn;
3283 CXFile ResultFile;
3284 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003285 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3286 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003287 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3288
3289 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3290 0);
3291 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3292 &ResultColumn, 0);
3293 SearchFileName = clang_getFileName(SearchFile);
3294 ResultFileName = clang_getFileName(ResultFile);
3295 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003296 USR = clang_getCursorUSR(Result);
3297 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003298 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3299 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003300 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3301 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003302 clang_disposeString(SearchFileName);
3303 clang_disposeString(ResultFileName);
3304 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003305 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003306
3307 CXCursor Definition = clang_getCursorDefinition(Result);
3308 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3309 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3310 CXString DefinitionKindSpelling
3311 = clang_getCursorKindSpelling(Definition.kind);
3312 CXFile DefinitionFile;
3313 unsigned DefinitionLine, DefinitionColumn;
3314 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3315 &DefinitionLine, &DefinitionColumn, 0);
3316 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3317 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3318 clang_getCString(DefinitionKindSpelling),
3319 clang_getCString(DefinitionFileName),
3320 DefinitionLine, DefinitionColumn);
3321 clang_disposeString(DefinitionFileName);
3322 clang_disposeString(DefinitionKindSpelling);
3323 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003324 }
3325
Ted Kremeneke68fff62010-02-17 00:41:32 +00003326 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003327}
3328
Ted Kremenek73885552009-11-17 19:28:59 +00003329CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003330 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003331}
3332
3333unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003334 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003335}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003336
Douglas Gregor9ce55842010-11-20 00:09:34 +00003337unsigned clang_hashCursor(CXCursor C) {
3338 unsigned Index = 0;
3339 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3340 Index = 1;
3341
3342 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3343 std::make_pair(C.kind, C.data[Index]));
3344}
3345
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003346unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003347 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3348}
3349
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003350unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003351 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3352}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003353
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003354unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003355 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3356}
3357
Douglas Gregor97b98722010-01-19 23:20:36 +00003358unsigned clang_isExpression(enum CXCursorKind K) {
3359 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3360}
3361
3362unsigned clang_isStatement(enum CXCursorKind K) {
3363 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3364}
3365
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003366unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3367 return K == CXCursor_TranslationUnit;
3368}
3369
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003370unsigned clang_isPreprocessing(enum CXCursorKind K) {
3371 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3372}
3373
Ted Kremenekad6eff62010-03-08 21:17:29 +00003374unsigned clang_isUnexposed(enum CXCursorKind K) {
3375 switch (K) {
3376 case CXCursor_UnexposedDecl:
3377 case CXCursor_UnexposedExpr:
3378 case CXCursor_UnexposedStmt:
3379 case CXCursor_UnexposedAttr:
3380 return true;
3381 default:
3382 return false;
3383 }
3384}
3385
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003386CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003387 return C.kind;
3388}
3389
Douglas Gregor98258af2010-01-18 22:46:11 +00003390CXSourceLocation clang_getCursorLocation(CXCursor C) {
3391 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003392 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003393 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003394 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3395 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003396 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003397 }
3398
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003399 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003400 std::pair<ObjCProtocolDecl *, SourceLocation> P
3401 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003402 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003403 }
3404
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003405 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003406 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3407 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003408 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003409 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003410
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003411 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003412 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003413 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003414 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003415
3416 case CXCursor_TemplateRef: {
3417 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3418 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3419 }
3420
Douglas Gregor69319002010-08-31 23:48:11 +00003421 case CXCursor_NamespaceRef: {
3422 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3423 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3424 }
3425
Douglas Gregora67e03f2010-09-09 21:42:20 +00003426 case CXCursor_MemberRef: {
3427 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3428 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3429 }
3430
Ted Kremenek3064ef92010-08-27 21:34:58 +00003431 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003432 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3433 if (!BaseSpec)
3434 return clang_getNullLocation();
3435
3436 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3437 return cxloc::translateSourceLocation(getCursorContext(C),
3438 TSInfo->getTypeLoc().getBeginLoc());
3439
3440 return cxloc::translateSourceLocation(getCursorContext(C),
3441 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003442 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003443
Douglas Gregor36897b02010-09-10 00:22:18 +00003444 case CXCursor_LabelRef: {
3445 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3446 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3447 }
3448
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003449 case CXCursor_OverloadedDeclRef:
3450 return cxloc::translateSourceLocation(getCursorContext(C),
3451 getCursorOverloadedDeclRef(C).second);
3452
Douglas Gregorf46034a2010-01-18 23:41:10 +00003453 default:
3454 // FIXME: Need a way to enumerate all non-reference cases.
3455 llvm_unreachable("Missed a reference kind");
3456 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003457 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003458
3459 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003460 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003461 getLocationFromExpr(getCursorExpr(C)));
3462
Douglas Gregor36897b02010-09-10 00:22:18 +00003463 if (clang_isStatement(C.kind))
3464 return cxloc::translateSourceLocation(getCursorContext(C),
3465 getCursorStmt(C)->getLocStart());
3466
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003467 if (C.kind == CXCursor_PreprocessingDirective) {
3468 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3469 return cxloc::translateSourceLocation(getCursorContext(C), L);
3470 }
Douglas Gregor48072312010-03-18 15:23:44 +00003471
3472 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003473 SourceLocation L
3474 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003475 return cxloc::translateSourceLocation(getCursorContext(C), L);
3476 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003477
3478 if (C.kind == CXCursor_MacroDefinition) {
3479 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3480 return cxloc::translateSourceLocation(getCursorContext(C), L);
3481 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003482
3483 if (C.kind == CXCursor_InclusionDirective) {
3484 SourceLocation L
3485 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3486 return cxloc::translateSourceLocation(getCursorContext(C), L);
3487 }
3488
Ted Kremenek9a700d22010-05-12 06:16:13 +00003489 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003490 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003491
Douglas Gregorf46034a2010-01-18 23:41:10 +00003492 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003493 SourceLocation Loc = D->getLocation();
3494 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3495 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003496 // FIXME: Multiple variables declared in a single declaration
3497 // currently lack the information needed to correctly determine their
3498 // ranges when accounting for the type-specifier. We use context
3499 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3500 // and if so, whether it is the first decl.
3501 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3502 if (!cxcursor::isFirstInDeclGroup(C))
3503 Loc = VD->getLocation();
3504 }
3505
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003506 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003507}
Douglas Gregora7bde202010-01-19 00:34:46 +00003508
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003509} // end extern "C"
3510
3511static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003512 if (clang_isReference(C.kind)) {
3513 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003514 case CXCursor_ObjCSuperClassRef:
3515 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003516
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003517 case CXCursor_ObjCProtocolRef:
3518 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003519
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003520 case CXCursor_ObjCClassRef:
3521 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003522
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003523 case CXCursor_TypeRef:
3524 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003525
3526 case CXCursor_TemplateRef:
3527 return getCursorTemplateRef(C).second;
3528
Douglas Gregor69319002010-08-31 23:48:11 +00003529 case CXCursor_NamespaceRef:
3530 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003531
3532 case CXCursor_MemberRef:
3533 return getCursorMemberRef(C).second;
3534
Ted Kremenek3064ef92010-08-27 21:34:58 +00003535 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003536 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003537
Douglas Gregor36897b02010-09-10 00:22:18 +00003538 case CXCursor_LabelRef:
3539 return getCursorLabelRef(C).second;
3540
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003541 case CXCursor_OverloadedDeclRef:
3542 return getCursorOverloadedDeclRef(C).second;
3543
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003544 default:
3545 // FIXME: Need a way to enumerate all non-reference cases.
3546 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003547 }
3548 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003549
3550 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003551 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003552
3553 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003554 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003555
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003556 if (C.kind == CXCursor_PreprocessingDirective)
3557 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003558
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003559 if (C.kind == CXCursor_MacroInstantiation)
3560 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003561
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003562 if (C.kind == CXCursor_MacroDefinition)
3563 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003564
3565 if (C.kind == CXCursor_InclusionDirective)
3566 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3567
Ted Kremenek007a7c92010-11-01 23:26:51 +00003568 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3569 Decl *D = cxcursor::getCursorDecl(C);
3570 SourceRange R = D->getSourceRange();
3571 // FIXME: Multiple variables declared in a single declaration
3572 // currently lack the information needed to correctly determine their
3573 // ranges when accounting for the type-specifier. We use context
3574 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3575 // and if so, whether it is the first decl.
3576 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3577 if (!cxcursor::isFirstInDeclGroup(C))
3578 R.setBegin(VD->getLocation());
3579 }
3580 return R;
3581 }
Douglas Gregor66537982010-11-17 17:14:07 +00003582 return SourceRange();
3583}
3584
3585/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3586/// the decl-specifier-seq for declarations.
3587static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3588 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3589 Decl *D = cxcursor::getCursorDecl(C);
3590 SourceRange R = D->getSourceRange();
3591
3592 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3593 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3594 TypeLoc TL = TI->getTypeLoc();
3595 SourceLocation TLoc = TL.getSourceRange().getBegin();
3596 if (TLoc.isValid() && R.getBegin().isValid() &&
3597 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3598 R.setBegin(TLoc);
3599 }
3600
3601 // FIXME: Multiple variables declared in a single declaration
3602 // currently lack the information needed to correctly determine their
3603 // ranges when accounting for the type-specifier. We use context
3604 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3605 // and if so, whether it is the first decl.
3606 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3607 if (!cxcursor::isFirstInDeclGroup(C))
3608 R.setBegin(VD->getLocation());
3609 }
3610 }
3611
3612 return R;
3613 }
3614
3615 return getRawCursorExtent(C);
3616}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003617
3618extern "C" {
3619
3620CXSourceRange clang_getCursorExtent(CXCursor C) {
3621 SourceRange R = getRawCursorExtent(C);
3622 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003623 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003624
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003625 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003626}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003627
3628CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003629 if (clang_isInvalid(C.kind))
3630 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003631
Ted Kremeneka60ed472010-11-16 08:15:36 +00003632 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003633 if (clang_isDeclaration(C.kind)) {
3634 Decl *D = getCursorDecl(C);
3635 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003636 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003637 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003638 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003639 if (ObjCForwardProtocolDecl *Protocols
3640 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003641 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003642 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3643 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3644 return MakeCXCursor(Property, tu);
3645
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003646 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003647 }
3648
Douglas Gregor97b98722010-01-19 23:20:36 +00003649 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003650 Expr *E = getCursorExpr(C);
3651 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003652 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003653 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003654
3655 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003656 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003657
Douglas Gregor97b98722010-01-19 23:20:36 +00003658 return clang_getNullCursor();
3659 }
3660
Douglas Gregor36897b02010-09-10 00:22:18 +00003661 if (clang_isStatement(C.kind)) {
3662 Stmt *S = getCursorStmt(C);
3663 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003664 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003665
3666 return clang_getNullCursor();
3667 }
3668
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003669 if (C.kind == CXCursor_MacroInstantiation) {
3670 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003671 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003672 }
3673
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003674 if (!clang_isReference(C.kind))
3675 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003676
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003677 switch (C.kind) {
3678 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003679 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003680
3681 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003682 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003683
3684 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003685 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003686
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003687 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003688 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003689
3690 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003691 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003692
Douglas Gregor69319002010-08-31 23:48:11 +00003693 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003694 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003695
Douglas Gregora67e03f2010-09-09 21:42:20 +00003696 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003697 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003698
Ted Kremenek3064ef92010-08-27 21:34:58 +00003699 case CXCursor_CXXBaseSpecifier: {
3700 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3701 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003702 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003703 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003704
Douglas Gregor36897b02010-09-10 00:22:18 +00003705 case CXCursor_LabelRef:
3706 // FIXME: We end up faking the "parent" declaration here because we
3707 // don't want to make CXCursor larger.
3708 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003709 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3710 .getTranslationUnitDecl(),
3711 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003712
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003713 case CXCursor_OverloadedDeclRef:
3714 return C;
3715
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003716 default:
3717 // We would prefer to enumerate all non-reference cursor kinds here.
3718 llvm_unreachable("Unhandled reference cursor kind");
3719 break;
3720 }
3721 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003722
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003723 return clang_getNullCursor();
3724}
3725
Douglas Gregorb6998662010-01-19 19:34:47 +00003726CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003727 if (clang_isInvalid(C.kind))
3728 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003729
Ted Kremeneka60ed472010-11-16 08:15:36 +00003730 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003731
Douglas Gregorb6998662010-01-19 19:34:47 +00003732 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003733 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003734 C = clang_getCursorReferenced(C);
3735 WasReference = true;
3736 }
3737
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003738 if (C.kind == CXCursor_MacroInstantiation)
3739 return clang_getCursorReferenced(C);
3740
Douglas Gregorb6998662010-01-19 19:34:47 +00003741 if (!clang_isDeclaration(C.kind))
3742 return clang_getNullCursor();
3743
3744 Decl *D = getCursorDecl(C);
3745 if (!D)
3746 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003747
Douglas Gregorb6998662010-01-19 19:34:47 +00003748 switch (D->getKind()) {
3749 // Declaration kinds that don't really separate the notions of
3750 // declaration and definition.
3751 case Decl::Namespace:
3752 case Decl::Typedef:
3753 case Decl::TemplateTypeParm:
3754 case Decl::EnumConstant:
3755 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003756 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003757 case Decl::ObjCIvar:
3758 case Decl::ObjCAtDefsField:
3759 case Decl::ImplicitParam:
3760 case Decl::ParmVar:
3761 case Decl::NonTypeTemplateParm:
3762 case Decl::TemplateTemplateParm:
3763 case Decl::ObjCCategoryImpl:
3764 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003765 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003766 case Decl::LinkageSpec:
3767 case Decl::ObjCPropertyImpl:
3768 case Decl::FileScopeAsm:
3769 case Decl::StaticAssert:
3770 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003771 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003772 return C;
3773
3774 // Declaration kinds that don't make any sense here, but are
3775 // nonetheless harmless.
3776 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003777 break;
3778
3779 // Declaration kinds for which the definition is not resolvable.
3780 case Decl::UnresolvedUsingTypename:
3781 case Decl::UnresolvedUsingValue:
3782 break;
3783
3784 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003785 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003786 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003787
3788 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003789 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003790
3791 case Decl::Enum:
3792 case Decl::Record:
3793 case Decl::CXXRecord:
3794 case Decl::ClassTemplateSpecialization:
3795 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003796 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003797 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003798 return clang_getNullCursor();
3799
3800 case Decl::Function:
3801 case Decl::CXXMethod:
3802 case Decl::CXXConstructor:
3803 case Decl::CXXDestructor:
3804 case Decl::CXXConversion: {
3805 const FunctionDecl *Def = 0;
3806 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003807 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003808 return clang_getNullCursor();
3809 }
3810
3811 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003812 // Ask the variable if it has a definition.
3813 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003814 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003815 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003816 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003817
Douglas Gregorb6998662010-01-19 19:34:47 +00003818 case Decl::FunctionTemplate: {
3819 const FunctionDecl *Def = 0;
3820 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003821 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003822 return clang_getNullCursor();
3823 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003824
Douglas Gregorb6998662010-01-19 19:34:47 +00003825 case Decl::ClassTemplate: {
3826 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003827 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003828 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003829 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003830 return clang_getNullCursor();
3831 }
3832
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003833 case Decl::Using:
3834 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003835 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003836
3837 case Decl::UsingShadow:
3838 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003839 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003840 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003841
3842 case Decl::ObjCMethod: {
3843 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3844 if (Method->isThisDeclarationADefinition())
3845 return C;
3846
3847 // Dig out the method definition in the associated
3848 // @implementation, if we have it.
3849 // FIXME: The ASTs should make finding the definition easier.
3850 if (ObjCInterfaceDecl *Class
3851 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3852 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3853 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3854 Method->isInstanceMethod()))
3855 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003856 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003857
3858 return clang_getNullCursor();
3859 }
3860
3861 case Decl::ObjCCategory:
3862 if (ObjCCategoryImplDecl *Impl
3863 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003864 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003865 return clang_getNullCursor();
3866
3867 case Decl::ObjCProtocol:
3868 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3869 return C;
3870 return clang_getNullCursor();
3871
3872 case Decl::ObjCInterface:
3873 // There are two notions of a "definition" for an Objective-C
3874 // class: the interface and its implementation. When we resolved a
3875 // reference to an Objective-C class, produce the @interface as
3876 // the definition; when we were provided with the interface,
3877 // produce the @implementation as the definition.
3878 if (WasReference) {
3879 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3880 return C;
3881 } else if (ObjCImplementationDecl *Impl
3882 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003883 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003884 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003885
Douglas Gregorb6998662010-01-19 19:34:47 +00003886 case Decl::ObjCProperty:
3887 // FIXME: We don't really know where to find the
3888 // ObjCPropertyImplDecls that implement this property.
3889 return clang_getNullCursor();
3890
3891 case Decl::ObjCCompatibleAlias:
3892 if (ObjCInterfaceDecl *Class
3893 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3894 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003896
Douglas Gregorb6998662010-01-19 19:34:47 +00003897 return clang_getNullCursor();
3898
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003899 case Decl::ObjCForwardProtocol:
3900 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003901 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003902
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003903 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003904 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003905 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003906
3907 case Decl::Friend:
3908 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003909 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003910 return clang_getNullCursor();
3911
3912 case Decl::FriendTemplate:
3913 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003914 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003915 return clang_getNullCursor();
3916 }
3917
3918 return clang_getNullCursor();
3919}
3920
3921unsigned clang_isCursorDefinition(CXCursor C) {
3922 if (!clang_isDeclaration(C.kind))
3923 return 0;
3924
3925 return clang_getCursorDefinition(C) == C;
3926}
3927
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003928CXCursor clang_getCanonicalCursor(CXCursor C) {
3929 if (!clang_isDeclaration(C.kind))
3930 return C;
3931
3932 if (Decl *D = getCursorDecl(C))
3933 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3934
3935 return C;
3936}
3937
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003938unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003939 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003940 return 0;
3941
3942 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3943 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3944 return E->getNumDecls();
3945
3946 if (OverloadedTemplateStorage *S
3947 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3948 return S->size();
3949
3950 Decl *D = Storage.get<Decl*>();
3951 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003952 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003953 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3954 return Classes->size();
3955 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3956 return Protocols->protocol_size();
3957
3958 return 0;
3959}
3960
3961CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003962 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003963 return clang_getNullCursor();
3964
3965 if (index >= clang_getNumOverloadedDecls(cursor))
3966 return clang_getNullCursor();
3967
Ted Kremeneka60ed472010-11-16 08:15:36 +00003968 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003969 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3970 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003971 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003972
3973 if (OverloadedTemplateStorage *S
3974 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003975 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003976
3977 Decl *D = Storage.get<Decl*>();
3978 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3979 // FIXME: This is, unfortunately, linear time.
3980 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3981 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003982 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003983 }
3984
3985 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003986 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003987
3988 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003989 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003990
3991 return clang_getNullCursor();
3992}
3993
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003994void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003995 const char **startBuf,
3996 const char **endBuf,
3997 unsigned *startLine,
3998 unsigned *startColumn,
3999 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004000 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004001 assert(getCursorDecl(C) && "CXCursor has null decl");
4002 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004003 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4004 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004005
Steve Naroff4ade6d62009-09-23 17:52:52 +00004006 SourceManager &SM = FD->getASTContext().getSourceManager();
4007 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4008 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4009 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4010 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4011 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4012 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4013}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004014
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004015void clang_enableStackTraces(void) {
4016 llvm::sys::PrintStackTraceOnErrorSignal();
4017}
4018
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004019void clang_executeOnThread(void (*fn)(void*), void *user_data,
4020 unsigned stack_size) {
4021 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4022}
4023
Ted Kremenekfb480492010-01-13 21:46:36 +00004024} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004025
Ted Kremenekfb480492010-01-13 21:46:36 +00004026//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004027// Token-based Operations.
4028//===----------------------------------------------------------------------===//
4029
4030/* CXToken layout:
4031 * int_data[0]: a CXTokenKind
4032 * int_data[1]: starting token location
4033 * int_data[2]: token length
4034 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004035 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004036 * otherwise unused.
4037 */
4038extern "C" {
4039
4040CXTokenKind clang_getTokenKind(CXToken CXTok) {
4041 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4042}
4043
4044CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4045 switch (clang_getTokenKind(CXTok)) {
4046 case CXToken_Identifier:
4047 case CXToken_Keyword:
4048 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004049 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4050 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004051
4052 case CXToken_Literal: {
4053 // We have stashed the starting pointer in the ptr_data field. Use it.
4054 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004055 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004056 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004057
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004058 case CXToken_Punctuation:
4059 case CXToken_Comment:
4060 break;
4061 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004062
4063 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004064 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004065 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004066 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004067 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004068
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004069 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4070 std::pair<FileID, unsigned> LocInfo
4071 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004072 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004073 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004074 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4075 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004076 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004077
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004078 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004079}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004080
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004081CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004083 if (!CXXUnit)
4084 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004085
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004086 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4087 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4088}
4089
4090CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004091 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004092 if (!CXXUnit)
4093 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004094
4095 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004096 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4097}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004098
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004099void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4100 CXToken **Tokens, unsigned *NumTokens) {
4101 if (Tokens)
4102 *Tokens = 0;
4103 if (NumTokens)
4104 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004105
Ted Kremeneka60ed472010-11-16 08:15:36 +00004106 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004107 if (!CXXUnit || !Tokens || !NumTokens)
4108 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004109
Douglas Gregorbdf60622010-03-05 21:16:25 +00004110 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4111
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004112 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004113 if (R.isInvalid())
4114 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004115
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004116 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4117 std::pair<FileID, unsigned> BeginLocInfo
4118 = SourceMgr.getDecomposedLoc(R.getBegin());
4119 std::pair<FileID, unsigned> EndLocInfo
4120 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004121
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004122 // Cannot tokenize across files.
4123 if (BeginLocInfo.first != EndLocInfo.first)
4124 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004125
4126 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004127 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004128 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004129 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004130 if (Invalid)
4131 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004132
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004133 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4134 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004135 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004136 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004137
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004138 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004139 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004140 llvm::SmallVector<CXToken, 32> CXTokens;
4141 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004142 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004143 do {
4144 // Lex the next token
4145 Lex.LexFromRawLexer(Tok);
4146 if (Tok.is(tok::eof))
4147 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004148
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004149 // Initialize the CXToken.
4150 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004151
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004152 // - Common fields
4153 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4154 CXTok.int_data[2] = Tok.getLength();
4155 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004156
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004157 // - Kind-specific fields
4158 if (Tok.isLiteral()) {
4159 CXTok.int_data[0] = CXToken_Literal;
4160 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004161 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004162 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004163 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004164 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004165
David Chisnall096428b2010-10-13 21:44:48 +00004166 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004167 CXTok.int_data[0] = CXToken_Keyword;
4168 }
4169 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004170 CXTok.int_data[0] = Tok.is(tok::identifier)
4171 ? CXToken_Identifier
4172 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004173 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004174 CXTok.ptr_data = II;
4175 } else if (Tok.is(tok::comment)) {
4176 CXTok.int_data[0] = CXToken_Comment;
4177 CXTok.ptr_data = 0;
4178 } else {
4179 CXTok.int_data[0] = CXToken_Punctuation;
4180 CXTok.ptr_data = 0;
4181 }
4182 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004183 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004184 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004185
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004186 if (CXTokens.empty())
4187 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004188
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004189 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4190 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4191 *NumTokens = CXTokens.size();
4192}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004193
Ted Kremenek6db61092010-05-05 00:55:15 +00004194void clang_disposeTokens(CXTranslationUnit TU,
4195 CXToken *Tokens, unsigned NumTokens) {
4196 free(Tokens);
4197}
4198
4199} // end: extern "C"
4200
4201//===----------------------------------------------------------------------===//
4202// Token annotation APIs.
4203//===----------------------------------------------------------------------===//
4204
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004205typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004206static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4207 CXCursor parent,
4208 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004209namespace {
4210class AnnotateTokensWorker {
4211 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004212 CXToken *Tokens;
4213 CXCursor *Cursors;
4214 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004215 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004216 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004217 CursorVisitor AnnotateVis;
4218 SourceManager &SrcMgr;
4219
4220 bool MoreTokens() const { return TokIdx < NumTokens; }
4221 unsigned NextToken() const { return TokIdx; }
4222 void AdvanceToken() { ++TokIdx; }
4223 SourceLocation GetTokenLoc(unsigned tokI) {
4224 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4225 }
4226
Ted Kremenek6db61092010-05-05 00:55:15 +00004227public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004228 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004230 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004231 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004232 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004233 AnnotateVis(tu,
4234 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004235 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004236 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004237
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004239 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004240 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004241 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004242 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004243 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004244};
4245}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004246
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004247void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4248 // Walk the AST within the region of interest, annotating tokens
4249 // along the way.
4250 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004251
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4253 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004254 if (Pos != Annotated.end() &&
4255 (clang_isInvalid(Cursors[I].kind) ||
4256 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004257 Cursors[I] = Pos->second;
4258 }
4259
4260 // Finish up annotating any tokens left.
4261 if (!MoreTokens())
4262 return;
4263
4264 const CXCursor &C = clang_getNullCursor();
4265 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4266 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4267 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004268 }
4269}
4270
Ted Kremenek6db61092010-05-05 00:55:15 +00004271enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004272AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004273 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004274 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004275 if (cursorRange.isInvalid())
4276 return CXChildVisit_Recurse;
4277
Douglas Gregor4419b672010-10-21 06:10:04 +00004278 if (clang_isPreprocessing(cursor.kind)) {
4279 // For macro instantiations, just note where the beginning of the macro
4280 // instantiation occurs.
4281 if (cursor.kind == CXCursor_MacroInstantiation) {
4282 Annotated[Loc.int_data] = cursor;
4283 return CXChildVisit_Recurse;
4284 }
4285
Douglas Gregor4419b672010-10-21 06:10:04 +00004286 // Items in the preprocessing record are kept separate from items in
4287 // declarations, so we keep a separate token index.
4288 unsigned SavedTokIdx = TokIdx;
4289 TokIdx = PreprocessingTokIdx;
4290
4291 // Skip tokens up until we catch up to the beginning of the preprocessing
4292 // entry.
4293 while (MoreTokens()) {
4294 const unsigned I = NextToken();
4295 SourceLocation TokLoc = GetTokenLoc(I);
4296 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4297 case RangeBefore:
4298 AdvanceToken();
4299 continue;
4300 case RangeAfter:
4301 case RangeOverlap:
4302 break;
4303 }
4304 break;
4305 }
4306
4307 // Look at all of the tokens within this range.
4308 while (MoreTokens()) {
4309 const unsigned I = NextToken();
4310 SourceLocation TokLoc = GetTokenLoc(I);
4311 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4312 case RangeBefore:
4313 assert(0 && "Infeasible");
4314 case RangeAfter:
4315 break;
4316 case RangeOverlap:
4317 Cursors[I] = cursor;
4318 AdvanceToken();
4319 continue;
4320 }
4321 break;
4322 }
4323
4324 // Save the preprocessing token index; restore the non-preprocessing
4325 // token index.
4326 PreprocessingTokIdx = TokIdx;
4327 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004328 return CXChildVisit_Recurse;
4329 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004330
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004331 if (cursorRange.isInvalid())
4332 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004333
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004334 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4335
Ted Kremeneka333c662010-05-12 05:29:33 +00004336 // Adjust the annotated range based specific declarations.
4337 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4338 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004339 Decl *D = cxcursor::getCursorDecl(cursor);
4340 // Don't visit synthesized ObjC methods, since they have no syntatic
4341 // representation in the source.
4342 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4343 if (MD->isSynthesized())
4344 return CXChildVisit_Continue;
4345 }
4346 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004347 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4348 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004349 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004350 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004351 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004352 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004353 }
4354 }
4355 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004356
Ted Kremenek3f404602010-08-14 01:14:06 +00004357 // If the location of the cursor occurs within a macro instantiation, record
4358 // the spelling location of the cursor in our annotation map. We can then
4359 // paper over the token labelings during a post-processing step to try and
4360 // get cursor mappings for tokens that are the *arguments* of a macro
4361 // instantiation.
4362 if (L.isMacroID()) {
4363 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4364 // Only invalidate the old annotation if it isn't part of a preprocessing
4365 // directive. Here we assume that the default construction of CXCursor
4366 // results in CXCursor.kind being an initialized value (i.e., 0). If
4367 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004368
Ted Kremenek3f404602010-08-14 01:14:06 +00004369 CXCursor &oldC = Annotated[rawEncoding];
4370 if (!clang_isPreprocessing(oldC.kind))
4371 oldC = cursor;
4372 }
4373
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004374 const enum CXCursorKind K = clang_getCursorKind(parent);
4375 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004376 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4377 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004378
4379 while (MoreTokens()) {
4380 const unsigned I = NextToken();
4381 SourceLocation TokLoc = GetTokenLoc(I);
4382 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4383 case RangeBefore:
4384 Cursors[I] = updateC;
4385 AdvanceToken();
4386 continue;
4387 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004388 case RangeOverlap:
4389 break;
4390 }
4391 break;
4392 }
4393
4394 // Visit children to get their cursor information.
4395 const unsigned BeforeChildren = NextToken();
4396 VisitChildren(cursor);
4397 const unsigned AfterChildren = NextToken();
4398
4399 // Adjust 'Last' to the last token within the extent of the cursor.
4400 while (MoreTokens()) {
4401 const unsigned I = NextToken();
4402 SourceLocation TokLoc = GetTokenLoc(I);
4403 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4404 case RangeBefore:
4405 assert(0 && "Infeasible");
4406 case RangeAfter:
4407 break;
4408 case RangeOverlap:
4409 Cursors[I] = updateC;
4410 AdvanceToken();
4411 continue;
4412 }
4413 break;
4414 }
4415 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004416
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004417 // Scan the tokens that are at the beginning of the cursor, but are not
4418 // capture by the child cursors.
4419
4420 // For AST elements within macros, rely on a post-annotate pass to
4421 // to correctly annotate the tokens with cursors. Otherwise we can
4422 // get confusing results of having tokens that map to cursors that really
4423 // are expanded by an instantiation.
4424 if (L.isMacroID())
4425 cursor = clang_getNullCursor();
4426
4427 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4428 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4429 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004430
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004431 Cursors[I] = cursor;
4432 }
4433 // Scan the tokens that are at the end of the cursor, but are not captured
4434 // but the child cursors.
4435 for (unsigned I = AfterChildren; I != Last; ++I)
4436 Cursors[I] = cursor;
4437
4438 TokIdx = Last;
4439 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004440}
4441
Ted Kremenek6db61092010-05-05 00:55:15 +00004442static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4443 CXCursor parent,
4444 CXClientData client_data) {
4445 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4446}
4447
Ted Kremenekab979612010-11-11 08:05:23 +00004448// This gets run a separate thread to avoid stack blowout.
4449static void runAnnotateTokensWorker(void *UserData) {
4450 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4451}
4452
Ted Kremenek6db61092010-05-05 00:55:15 +00004453extern "C" {
4454
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004455void clang_annotateTokens(CXTranslationUnit TU,
4456 CXToken *Tokens, unsigned NumTokens,
4457 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004458
4459 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004460 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004461
Douglas Gregor4419b672010-10-21 06:10:04 +00004462 // Any token we don't specifically annotate will have a NULL cursor.
4463 CXCursor C = clang_getNullCursor();
4464 for (unsigned I = 0; I != NumTokens; ++I)
4465 Cursors[I] = C;
4466
Ted Kremeneka60ed472010-11-16 08:15:36 +00004467 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004468 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004469 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004470
Douglas Gregorbdf60622010-03-05 21:16:25 +00004471 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004472
Douglas Gregor0396f462010-03-19 05:22:59 +00004473 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004474 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004475 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4476 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004477 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4478 clang_getTokenLocation(TU,
4479 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004480
Douglas Gregor0396f462010-03-19 05:22:59 +00004481 // A mapping from the source locations found when re-lexing or traversing the
4482 // region of interest to the corresponding cursors.
4483 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004484
4485 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004486 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004487 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4488 std::pair<FileID, unsigned> BeginLocInfo
4489 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4490 std::pair<FileID, unsigned> EndLocInfo
4491 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004492
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004493 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004494 bool Invalid = false;
4495 if (BeginLocInfo.first == EndLocInfo.first &&
4496 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4497 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004498 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4499 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004500 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004501 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004502 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004503
4504 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004505 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004506 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004507 Token Tok;
4508 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004509
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004510 reprocess:
4511 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4512 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004513 // don't see it while preprocessing these tokens later, but keep track
4514 // of all of the token locations inside this preprocessing directive so
4515 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004516 //
4517 // FIXME: Some simple tests here could identify macro definitions and
4518 // #undefs, to provide specific cursor kinds for those.
4519 std::vector<SourceLocation> Locations;
4520 do {
4521 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004522 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004523 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004524
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004525 using namespace cxcursor;
4526 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004527 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4528 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004529 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004530 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4531 Annotated[Locations[I].getRawEncoding()] = Cursor;
4532 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004533
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004534 if (Tok.isAtStartOfLine())
4535 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004536
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004537 continue;
4538 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004539
Douglas Gregor48072312010-03-18 15:23:44 +00004540 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004541 break;
4542 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004543 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004544
Douglas Gregor0396f462010-03-19 05:22:59 +00004545 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004546 // a specific cursor.
4547 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004548 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004549
4550 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004551 // FIXME: We use a ridiculous stack size here because the data-recursion
4552 // algorithm uses a large stack frame than the non-data recursive version,
4553 // and AnnotationTokensWorker currently transforms the data-recursion
4554 // algorithm back into a traditional recursion by explicitly calling
4555 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004556 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004557 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4558 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004559 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4560 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004561}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004562} // end: extern "C"
4563
4564//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004565// Operations for querying linkage of a cursor.
4566//===----------------------------------------------------------------------===//
4567
4568extern "C" {
4569CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004570 if (!clang_isDeclaration(cursor.kind))
4571 return CXLinkage_Invalid;
4572
Ted Kremenek16b42592010-03-03 06:36:57 +00004573 Decl *D = cxcursor::getCursorDecl(cursor);
4574 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4575 switch (ND->getLinkage()) {
4576 case NoLinkage: return CXLinkage_NoLinkage;
4577 case InternalLinkage: return CXLinkage_Internal;
4578 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4579 case ExternalLinkage: return CXLinkage_External;
4580 };
4581
4582 return CXLinkage_Invalid;
4583}
4584} // end: extern "C"
4585
4586//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004587// Operations for querying language of a cursor.
4588//===----------------------------------------------------------------------===//
4589
4590static CXLanguageKind getDeclLanguage(const Decl *D) {
4591 switch (D->getKind()) {
4592 default:
4593 break;
4594 case Decl::ImplicitParam:
4595 case Decl::ObjCAtDefsField:
4596 case Decl::ObjCCategory:
4597 case Decl::ObjCCategoryImpl:
4598 case Decl::ObjCClass:
4599 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004600 case Decl::ObjCForwardProtocol:
4601 case Decl::ObjCImplementation:
4602 case Decl::ObjCInterface:
4603 case Decl::ObjCIvar:
4604 case Decl::ObjCMethod:
4605 case Decl::ObjCProperty:
4606 case Decl::ObjCPropertyImpl:
4607 case Decl::ObjCProtocol:
4608 return CXLanguage_ObjC;
4609 case Decl::CXXConstructor:
4610 case Decl::CXXConversion:
4611 case Decl::CXXDestructor:
4612 case Decl::CXXMethod:
4613 case Decl::CXXRecord:
4614 case Decl::ClassTemplate:
4615 case Decl::ClassTemplatePartialSpecialization:
4616 case Decl::ClassTemplateSpecialization:
4617 case Decl::Friend:
4618 case Decl::FriendTemplate:
4619 case Decl::FunctionTemplate:
4620 case Decl::LinkageSpec:
4621 case Decl::Namespace:
4622 case Decl::NamespaceAlias:
4623 case Decl::NonTypeTemplateParm:
4624 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004625 case Decl::TemplateTemplateParm:
4626 case Decl::TemplateTypeParm:
4627 case Decl::UnresolvedUsingTypename:
4628 case Decl::UnresolvedUsingValue:
4629 case Decl::Using:
4630 case Decl::UsingDirective:
4631 case Decl::UsingShadow:
4632 return CXLanguage_CPlusPlus;
4633 }
4634
4635 return CXLanguage_C;
4636}
4637
4638extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004639
4640enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4641 if (clang_isDeclaration(cursor.kind))
4642 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4643 if (D->hasAttr<UnavailableAttr>() ||
4644 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4645 return CXAvailability_Available;
4646
4647 if (D->hasAttr<DeprecatedAttr>())
4648 return CXAvailability_Deprecated;
4649 }
4650
4651 return CXAvailability_Available;
4652}
4653
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004654CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4655 if (clang_isDeclaration(cursor.kind))
4656 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4657
4658 return CXLanguage_Invalid;
4659}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004660
4661 /// \brief If the given cursor is the "templated" declaration
4662 /// descibing a class or function template, return the class or
4663 /// function template.
4664static Decl *maybeGetTemplateCursor(Decl *D) {
4665 if (!D)
4666 return 0;
4667
4668 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4669 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4670 return FunTmpl;
4671
4672 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4673 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4674 return ClassTmpl;
4675
4676 return D;
4677}
4678
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004679CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4680 if (clang_isDeclaration(cursor.kind)) {
4681 if (Decl *D = getCursorDecl(cursor)) {
4682 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004683 if (!DC)
4684 return clang_getNullCursor();
4685
4686 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4687 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004688 }
4689 }
4690
4691 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4692 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004693 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004694 }
4695
4696 return clang_getNullCursor();
4697}
4698
4699CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4700 if (clang_isDeclaration(cursor.kind)) {
4701 if (Decl *D = getCursorDecl(cursor)) {
4702 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004703 if (!DC)
4704 return clang_getNullCursor();
4705
4706 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4707 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004708 }
4709 }
4710
4711 // FIXME: Note that we can't easily compute the lexical context of a
4712 // statement or expression, so we return nothing.
4713 return clang_getNullCursor();
4714}
4715
Douglas Gregor9f592342010-10-01 20:25:15 +00004716static void CollectOverriddenMethods(DeclContext *Ctx,
4717 ObjCMethodDecl *Method,
4718 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4719 if (!Ctx)
4720 return;
4721
4722 // If we have a class or category implementation, jump straight to the
4723 // interface.
4724 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4725 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4726
4727 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4728 if (!Container)
4729 return;
4730
4731 // Check whether we have a matching method at this level.
4732 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4733 Method->isInstanceMethod()))
4734 if (Method != Overridden) {
4735 // We found an override at this level; there is no need to look
4736 // into other protocols or categories.
4737 Methods.push_back(Overridden);
4738 return;
4739 }
4740
4741 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4742 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4743 PEnd = Protocol->protocol_end();
4744 P != PEnd; ++P)
4745 CollectOverriddenMethods(*P, Method, Methods);
4746 }
4747
4748 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4749 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4750 PEnd = Category->protocol_end();
4751 P != PEnd; ++P)
4752 CollectOverriddenMethods(*P, Method, Methods);
4753 }
4754
4755 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4756 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4757 PEnd = Interface->protocol_end();
4758 P != PEnd; ++P)
4759 CollectOverriddenMethods(*P, Method, Methods);
4760
4761 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4762 Category; Category = Category->getNextClassCategory())
4763 CollectOverriddenMethods(Category, Method, Methods);
4764
4765 // We only look into the superclass if we haven't found anything yet.
4766 if (Methods.empty())
4767 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4768 return CollectOverriddenMethods(Super, Method, Methods);
4769 }
4770}
4771
4772void clang_getOverriddenCursors(CXCursor cursor,
4773 CXCursor **overridden,
4774 unsigned *num_overridden) {
4775 if (overridden)
4776 *overridden = 0;
4777 if (num_overridden)
4778 *num_overridden = 0;
4779 if (!overridden || !num_overridden)
4780 return;
4781
4782 if (!clang_isDeclaration(cursor.kind))
4783 return;
4784
4785 Decl *D = getCursorDecl(cursor);
4786 if (!D)
4787 return;
4788
4789 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004790 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004791 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4792 *num_overridden = CXXMethod->size_overridden_methods();
4793 if (!*num_overridden)
4794 return;
4795
4796 *overridden = new CXCursor [*num_overridden];
4797 unsigned I = 0;
4798 for (CXXMethodDecl::method_iterator
4799 M = CXXMethod->begin_overridden_methods(),
4800 MEnd = CXXMethod->end_overridden_methods();
4801 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004802 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004803 return;
4804 }
4805
4806 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4807 if (!Method)
4808 return;
4809
4810 // Handle Objective-C methods.
4811 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4812 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4813
4814 if (Methods.empty())
4815 return;
4816
4817 *num_overridden = Methods.size();
4818 *overridden = new CXCursor [Methods.size()];
4819 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004820 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004821}
4822
4823void clang_disposeOverriddenCursors(CXCursor *overridden) {
4824 delete [] overridden;
4825}
4826
Douglas Gregorecdcb882010-10-20 22:00:55 +00004827CXFile clang_getIncludedFile(CXCursor cursor) {
4828 if (cursor.kind != CXCursor_InclusionDirective)
4829 return 0;
4830
4831 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4832 return (void *)ID->getFile();
4833}
4834
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004835} // end: extern "C"
4836
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004837
4838//===----------------------------------------------------------------------===//
4839// C++ AST instrospection.
4840//===----------------------------------------------------------------------===//
4841
4842extern "C" {
4843unsigned clang_CXXMethod_isStatic(CXCursor C) {
4844 if (!clang_isDeclaration(C.kind))
4845 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004846
4847 CXXMethodDecl *Method = 0;
4848 Decl *D = cxcursor::getCursorDecl(C);
4849 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4850 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4851 else
4852 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4853 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004854}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004855
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004856} // end: extern "C"
4857
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004858//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004859// Attribute introspection.
4860//===----------------------------------------------------------------------===//
4861
4862extern "C" {
4863CXType clang_getIBOutletCollectionType(CXCursor C) {
4864 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004865 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004866
4867 IBOutletCollectionAttr *A =
4868 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4869
Ted Kremeneka60ed472010-11-16 08:15:36 +00004870 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004871}
4872} // end: extern "C"
4873
4874//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004875// Misc. utility functions.
4876//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004877
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004878/// Default to using an 8 MB stack size on "safety" threads.
4879static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004880
4881namespace clang {
4882
4883bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004884 void (*Fn)(void*), void *UserData,
4885 unsigned Size) {
4886 if (!Size)
4887 Size = GetSafetyThreadStackSize();
4888 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004889 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4890 return CRC.RunSafely(Fn, UserData);
4891}
4892
4893unsigned GetSafetyThreadStackSize() {
4894 return SafetyStackThreadSize;
4895}
4896
4897void SetSafetyThreadStackSize(unsigned Value) {
4898 SafetyStackThreadSize = Value;
4899}
4900
4901}
4902
Ted Kremenek04bb7162010-01-22 22:44:15 +00004903extern "C" {
4904
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004905CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004906 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004907}
4908
4909} // end: extern "C"