blob: dfcf220ff49d75228e97683d1566d2d98e0c5ea2 [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,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000143 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000144 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000145protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000146 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147 CXCursor parent;
148 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
150 : parent(C), K(k) {
151 data[0] = d1;
152 data[1] = d2;
153 data[2] = d3;
154 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000155public:
156 Kind getKind() const { return K; }
157 const CXCursor &getParent() const { return parent; }
158 static bool classof(VisitorJob *VJ) { return true; }
159};
160
161typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
162
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000164class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000165 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000168 CXTranslationUnit TU;
169 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The declaration that serves at the parent of any statement or
175 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000176 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000178 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000179 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000184 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
185 // to the visitor. Declarations with a PCH level greater than this value will
186 // be suppressed.
187 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188
189 /// \brief When valid, a source range to which the cursor should restrict
190 /// its search.
191 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000193 // FIXME: Eventually remove. This part of a hack to support proper
194 // iteration over all Decls contained lexically within an ObjC container.
195 DeclContext::decl_iterator *DI_current;
196 DeclContext::decl_iterator DE_current;
197
Ted Kremenekd1ded662010-11-15 23:31:32 +0000198 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
199 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
200 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000204
205 /// \brief Determine whether this particular source range comes before, comes
206 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000208 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
210
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000211 class SetParentRAII {
212 CXCursor &Parent;
213 Decl *&StmtParent;
214 CXCursor OldParent;
215
216 public:
217 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
218 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
219 {
220 Parent = NewParent;
221 if (clang_isDeclaration(Parent.kind))
222 StmtParent = getCursorDecl(Parent);
223 }
224
225 ~SetParentRAII() {
226 Parent = OldParent;
227 if (clang_isDeclaration(Parent.kind))
228 StmtParent = getCursorDecl(Parent);
229 }
230 };
231
Steve Naroff89922f82009-08-31 00:59:03 +0000232public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000233 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
234 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000237 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
238 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000239 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
240 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 {
242 Parent.kind = CXCursor_NoDeclFound;
243 Parent.data[0] = 0;
244 Parent.data[1] = 0;
245 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000246 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000247 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000248
Ted Kremenekd1ded662010-11-15 23:31:32 +0000249 ~CursorVisitor() {
250 // Free the pre-allocated worklists for data-recursion.
251 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
252 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
253 delete *I;
254 }
255 }
256
Ted Kremeneka60ed472010-11-16 08:15:36 +0000257 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
258 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000259
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000260 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000261
262 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
263 getPreprocessedEntities();
264
Douglas Gregorb1373d02010-01-20 20:59:29 +0000265 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000266
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000268 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000269 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000270 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000271 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000273 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
274 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000276 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000277 bool VisitClassTemplatePartialSpecializationDecl(
278 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000279 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000280 bool VisitEnumConstantDecl(EnumConstantDecl *D);
281 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
282 bool VisitFunctionDecl(FunctionDecl *ND);
283 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000284 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000285 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000287 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000288 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
290 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
291 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
292 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000293 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
295 bool VisitObjCImplDecl(ObjCImplDecl *D);
296 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
297 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
299 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
300 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000301 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000302 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000303 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000304 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000305 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000306 bool VisitUsingDecl(UsingDecl *D);
307 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
308 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000309
Douglas Gregor01829d32010-08-31 14:41:23 +0000310 // Name visitor
311 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000312 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000313 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000314
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000315 // Template visitors
316 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000317 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000318 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
319
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000320 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000321 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000323 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000324 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
325 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000326 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000327 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000328 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000329 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000330 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitPointerTypeLoc(PointerTypeLoc TL);
332 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
333 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
334 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
335 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000336 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000337 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000338 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000339 // FIXME: Implement visitors here when the unimplemented TypeLocs get
340 // implemented
341 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000342 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000343 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000345 // Data-recursive visitor functions.
346 bool IsInRegionOfInterest(CXCursor C);
347 bool RunVisitorWorkList(VisitorWorkList &WL);
348 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000349 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000350};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000351
Ted Kremenekab188932010-01-05 19:32:54 +0000352} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000353
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000354static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000355static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000357
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000358RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000359 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360}
361
Douglas Gregorb1373d02010-01-20 20:59:29 +0000362/// \brief Visit the given cursor and, if requested by the visitor,
363/// its children.
364///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365/// \param Cursor the cursor to visit.
366///
367/// \param CheckRegionOfInterest if true, then the caller already checked that
368/// this cursor is within the region of interest.
369///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370/// \returns true if the visitation should be aborted, false if it
371/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373 if (clang_isInvalid(Cursor.kind))
374 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000375
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 if (clang_isDeclaration(Cursor.kind)) {
377 Decl *D = getCursorDecl(Cursor);
378 assert(D && "Invalid declaration cursor");
379 if (D->getPCHLevel() > MaxPCHLevel)
380 return false;
381
382 if (D->isImplicit())
383 return false;
384 }
385
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000386 // If we have a range of interest, and this cursor doesn't intersect with it,
387 // we're done.
388 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000389 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000390 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391 return false;
392 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000393
Douglas Gregorb1373d02010-01-20 20:59:29 +0000394 switch (Visitor(Cursor, Parent, ClientData)) {
395 case CXChildVisit_Break:
396 return true;
397
398 case CXChildVisit_Continue:
399 return false;
400
401 case CXChildVisit_Recurse:
402 return VisitChildren(Cursor);
403 }
404
Douglas Gregorfd643772010-01-25 16:45:46 +0000405 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406}
407
Douglas Gregor788f5a12010-03-20 00:41:21 +0000408std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
409CursorVisitor::getPreprocessedEntities() {
410 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000411 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000412
413 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000414 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
415
416 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
417 // If we would only look at local declarations but we have a region of
418 // interest, check whether that region of interest is in the main file.
419 // If not, we should traverse all declarations.
420 // FIXME: My kingdom for a proper binary search approach to finding
421 // cursors!
422 std::pair<FileID, unsigned> Location
423 = AU->getSourceManager().getDecomposedInstantiationLoc(
424 RegionOfInterest.getBegin());
425 if (Location.first != AU->getSourceManager().getMainFileID())
426 OnlyLocalDecls = false;
427 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000428
Douglas Gregor89d99802010-11-30 06:16:57 +0000429 PreprocessingRecord::iterator StartEntity, EndEntity;
430 if (OnlyLocalDecls) {
431 StartEntity = AU->pp_entity_begin();
432 EndEntity = AU->pp_entity_end();
433 } else {
434 StartEntity = PPRec.begin();
435 EndEntity = PPRec.end();
436 }
437
Douglas Gregor788f5a12010-03-20 00:41:21 +0000438 // There is no region of interest; we have to walk everything.
439 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000440 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000441
442 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000443 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000444 std::pair<FileID, unsigned> Begin
445 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
446 std::pair<FileID, unsigned> End
447 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
448
449 // The region of interest spans files; we have to walk everything.
450 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000451 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000452
453 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000454 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000455 if (ByFileMap.empty()) {
456 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000457 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000458 std::pair<FileID, unsigned> P
459 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000460
Douglas Gregor788f5a12010-03-20 00:41:21 +0000461 ByFileMap[P.first].push_back(*E);
462 }
463 }
464
465 return std::make_pair(ByFileMap[Begin.first].begin(),
466 ByFileMap[Begin.first].end());
467}
468
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000470///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471/// \returns true if the visitation should be aborted, false if it
472/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000473bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000474 if (clang_isReference(Cursor.kind)) {
475 // By definition, references have no children.
476 return false;
477 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478
479 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000481 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 if (clang_isDeclaration(Cursor.kind)) {
484 Decl *D = getCursorDecl(Cursor);
485 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000486 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000488
Douglas Gregora59e3902010-01-21 23:27:09 +0000489 if (clang_isStatement(Cursor.kind))
490 return Visit(getCursorStmt(Cursor));
491 if (clang_isExpression(Cursor.kind))
492 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000493
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000495 CXTranslationUnit tu = getCursorTU(Cursor);
496 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000497 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
498 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000499 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
500 TLEnd = CXXUnit->top_level_end();
501 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000502 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000503 return true;
504 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000505 } else if (VisitDeclContext(
506 CXXUnit->getASTContext().getTranslationUnitDecl()))
507 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000508
Douglas Gregor0396f462010-03-19 05:22:59 +0000509 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000510 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000511 // FIXME: Once we have the ability to deserialize a preprocessing record,
512 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000513 PreprocessingRecord::iterator E, EEnd;
514 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000515 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000516 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000518
Douglas Gregor0396f462010-03-19 05:22:59 +0000519 continue;
520 }
521
522 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000523 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000524 return true;
525
526 continue;
527 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000528
529 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000530 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000531 return true;
532
533 continue;
534 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000535 }
536 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000537 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000538 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000539
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 return false;
542}
543
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000544bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000545 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
546 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000547
Ted Kremenek664cffd2010-07-22 11:30:19 +0000548 if (Stmt *Body = B->getBody())
549 return Visit(MakeCXCursor(Body, StmtParent, TU));
550
551 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000552}
553
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000554llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
555 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000556 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000557 if (Range.isInvalid())
558 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000559
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000560 switch (CompareRegionOfInterest(Range)) {
561 case RangeBefore:
562 // This declaration comes before the region of interest; skip it.
563 return llvm::Optional<bool>();
564
565 case RangeAfter:
566 // This declaration comes after the region of interest; we're done.
567 return false;
568
569 case RangeOverlap:
570 // This declaration overlaps the region of interest; visit it.
571 break;
572 }
573 }
574 return true;
575}
576
577bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
578 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
579
580 // FIXME: Eventually remove. This part of a hack to support proper
581 // iteration over all Decls contained lexically within an ObjC container.
582 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
583 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
584
585 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000586 Decl *D = *I;
587 if (D->getLexicalDeclContext() != DC)
588 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000589 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000590 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
591 if (!V.hasValue())
592 continue;
593 if (!V.getValue())
594 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000595 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000596 return true;
597 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000598 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000599}
600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
602 llvm_unreachable("Translation units are visited directly by Visit()");
603 return false;
604}
605
606bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
607 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
608 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000610 return false;
611}
612
613bool CursorVisitor::VisitTagDecl(TagDecl *D) {
614 return VisitDeclContext(D);
615}
616
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000617bool CursorVisitor::VisitClassTemplateSpecializationDecl(
618 ClassTemplateSpecializationDecl *D) {
619 bool ShouldVisitBody = false;
620 switch (D->getSpecializationKind()) {
621 case TSK_Undeclared:
622 case TSK_ImplicitInstantiation:
623 // Nothing to visit
624 return false;
625
626 case TSK_ExplicitInstantiationDeclaration:
627 case TSK_ExplicitInstantiationDefinition:
628 break;
629
630 case TSK_ExplicitSpecialization:
631 ShouldVisitBody = true;
632 break;
633 }
634
635 // Visit the template arguments used in the specialization.
636 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
637 TypeLoc TL = SpecType->getTypeLoc();
638 if (TemplateSpecializationTypeLoc *TSTLoc
639 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
640 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
641 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
642 return true;
643 }
644 }
645
646 if (ShouldVisitBody && VisitCXXRecordDecl(D))
647 return true;
648
649 return false;
650}
651
Douglas Gregor74dbe642010-08-31 19:31:58 +0000652bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
653 ClassTemplatePartialSpecializationDecl *D) {
654 // FIXME: Visit the "outer" template parameter lists on the TagDecl
655 // before visiting these template parameters.
656 if (VisitTemplateParameters(D->getTemplateParameters()))
657 return true;
658
659 // Visit the partial specialization arguments.
660 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
661 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
662 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
663 return true;
664
665 return VisitCXXRecordDecl(D);
666}
667
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000668bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000669 // Visit the default argument.
670 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
671 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
672 if (Visit(DefArg->getTypeLoc()))
673 return true;
674
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000675 return false;
676}
677
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000678bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
679 if (Expr *Init = D->getInitExpr())
680 return Visit(MakeCXCursor(Init, StmtParent, TU));
681 return false;
682}
683
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000684bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
685 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
686 if (Visit(TSInfo->getTypeLoc()))
687 return true;
688
689 return false;
690}
691
Douglas Gregora67e03f2010-09-09 21:42:20 +0000692/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000693static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
694 CXXCtorInitializer const * const *X
695 = static_cast<CXXCtorInitializer const * const *>(Xp);
696 CXXCtorInitializer const * const *Y
697 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000698
699 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
700 return -1;
701 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
702 return 1;
703 else
704 return 0;
705}
706
Douglas Gregorb1373d02010-01-20 20:59:29 +0000707bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000708 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
709 // Visit the function declaration's syntactic components in the order
710 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000711 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000712 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
713
714 // If we have a function declared directly (without the use of a typedef),
715 // visit just the return type. Otherwise, just visit the function's type
716 // now.
717 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
718 (!FTL && Visit(TL)))
719 return true;
720
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000721 // Visit the nested-name-specifier, if present.
722 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
723 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
724 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000725
726 // Visit the declaration name.
727 if (VisitDeclarationNameInfo(ND->getNameInfo()))
728 return true;
729
730 // FIXME: Visit explicitly-specified template arguments!
731
732 // Visit the function parameters, if we have a function type.
733 if (FTL && VisitFunctionTypeLoc(*FTL, true))
734 return true;
735
736 // FIXME: Attributes?
737 }
738
Douglas Gregora67e03f2010-09-09 21:42:20 +0000739 if (ND->isThisDeclarationADefinition()) {
740 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
741 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000742 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000743 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
744 IEnd = Constructor->init_end();
745 I != IEnd; ++I) {
746 if (!(*I)->isWritten())
747 continue;
748
749 WrittenInits.push_back(*I);
750 }
751
752 // Sort the initializers in source order
753 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000754 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000755
756 // Visit the initializers in source order
757 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000758 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000759 if (Init->isAnyMemberInitializer()) {
760 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761 Init->getMemberLocation(), TU)))
762 return true;
763 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
764 if (Visit(BaseInfo->getTypeLoc()))
765 return true;
766 }
767
768 // Visit the initializer value.
769 if (Expr *Initializer = Init->getInit())
770 if (Visit(MakeCXCursor(Initializer, ND, TU)))
771 return true;
772 }
773 }
774
775 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
776 return true;
777 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000778
Douglas Gregorb1373d02010-01-20 20:59:29 +0000779 return false;
780}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000781
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000782bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
783 if (VisitDeclaratorDecl(D))
784 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000786 if (Expr *BitWidth = D->getBitWidth())
787 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000788
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000789 return false;
790}
791
792bool CursorVisitor::VisitVarDecl(VarDecl *D) {
793 if (VisitDeclaratorDecl(D))
794 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000795
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796 if (Expr *Init = D->getInit())
797 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799 return false;
800}
801
Douglas Gregor84b51d72010-09-01 20:16:53 +0000802bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
803 if (VisitDeclaratorDecl(D))
804 return true;
805
806 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
807 if (Expr *DefArg = D->getDefaultArgument())
808 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
809
810 return false;
811}
812
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000813bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
814 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
815 // before visiting these template parameters.
816 if (VisitTemplateParameters(D->getTemplateParameters()))
817 return true;
818
819 return VisitFunctionDecl(D->getTemplatedDecl());
820}
821
Douglas Gregor39d6f072010-08-31 19:02:00 +0000822bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
823 // FIXME: Visit the "outer" template parameter lists on the TagDecl
824 // before visiting these template parameters.
825 if (VisitTemplateParameters(D->getTemplateParameters()))
826 return true;
827
828 return VisitCXXRecordDecl(D->getTemplatedDecl());
829}
830
Douglas Gregor84b51d72010-09-01 20:16:53 +0000831bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
832 if (VisitTemplateParameters(D->getTemplateParameters()))
833 return true;
834
835 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
836 VisitTemplateArgumentLoc(D->getDefaultArgument()))
837 return true;
838
839 return false;
840}
841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000843 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
844 if (Visit(TSInfo->getTypeLoc()))
845 return true;
846
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000847 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848 PEnd = ND->param_end();
849 P != PEnd; ++P) {
850 if (Visit(MakeCXCursor(*P, TU)))
851 return true;
852 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 if (ND->isThisDeclarationADefinition() &&
855 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
856 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000857
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000858 return false;
859}
860
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000861namespace {
862 struct ContainerDeclsSort {
863 SourceManager &SM;
864 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
865 bool operator()(Decl *A, Decl *B) {
866 SourceLocation L_A = A->getLocStart();
867 SourceLocation L_B = B->getLocStart();
868 assert(L_A.isValid() && L_B.isValid());
869 return SM.isBeforeInTranslationUnit(L_A, L_B);
870 }
871 };
872}
873
Douglas Gregora59e3902010-01-21 23:27:09 +0000874bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000875 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
876 // an @implementation can lexically contain Decls that are not properly
877 // nested in the AST. When we identify such cases, we need to retrofit
878 // this nesting here.
879 if (!DI_current)
880 return VisitDeclContext(D);
881
882 // Scan the Decls that immediately come after the container
883 // in the current DeclContext. If any fall within the
884 // container's lexical region, stash them into a vector
885 // for later processing.
886 llvm::SmallVector<Decl *, 24> DeclsInContainer;
887 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000888 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000889 if (EndLoc.isValid()) {
890 DeclContext::decl_iterator next = *DI_current;
891 while (++next != DE_current) {
892 Decl *D_next = *next;
893 if (!D_next)
894 break;
895 SourceLocation L = D_next->getLocStart();
896 if (!L.isValid())
897 break;
898 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
899 *DI_current = next;
900 DeclsInContainer.push_back(D_next);
901 continue;
902 }
903 break;
904 }
905 }
906
907 // The common case.
908 if (DeclsInContainer.empty())
909 return VisitDeclContext(D);
910
911 // Get all the Decls in the DeclContext, and sort them with the
912 // additional ones we've collected. Then visit them.
913 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
914 I!=E; ++I) {
915 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000916 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
917 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000918 continue;
919 DeclsInContainer.push_back(subDecl);
920 }
921
922 // Now sort the Decls so that they appear in lexical order.
923 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
924 ContainerDeclsSort(SM));
925
926 // Now visit the decls.
927 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
928 E = DeclsInContainer.end(); I != E; ++I) {
929 CXCursor Cursor = MakeCXCursor(*I, TU);
930 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
931 if (!V.hasValue())
932 continue;
933 if (!V.getValue())
934 return false;
935 if (Visit(Cursor, true))
936 return true;
937 }
938 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000939}
940
Douglas Gregorb1373d02010-01-20 20:59:29 +0000941bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000942 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
943 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000944 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000945
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000946 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
947 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
948 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000949 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000950 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000951
Douglas Gregora59e3902010-01-21 23:27:09 +0000952 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000953}
954
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000955bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
956 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
957 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
958 E = PID->protocol_end(); I != E; ++I, ++PL)
959 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
960 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000961
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000962 return VisitObjCContainerDecl(PID);
963}
964
Ted Kremenek23173d72010-05-18 21:09:07 +0000965bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000966 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000967 return true;
968
Ted Kremenek23173d72010-05-18 21:09:07 +0000969 // FIXME: This implements a workaround with @property declarations also being
970 // installed in the DeclContext for the @interface. Eventually this code
971 // should be removed.
972 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
973 if (!CDecl || !CDecl->IsClassExtension())
974 return false;
975
976 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
977 if (!ID)
978 return false;
979
980 IdentifierInfo *PropertyId = PD->getIdentifier();
981 ObjCPropertyDecl *prevDecl =
982 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
983
984 if (!prevDecl)
985 return false;
986
987 // Visit synthesized methods since they will be skipped when visiting
988 // the @interface.
989 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000990 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000991 if (Visit(MakeCXCursor(MD, TU)))
992 return true;
993
994 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000995 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000996 if (Visit(MakeCXCursor(MD, TU)))
997 return true;
998
999 return false;
1000}
1001
Douglas Gregorb1373d02010-01-20 20:59:29 +00001002bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001003 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001004 if (D->getSuperClass() &&
1005 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001007 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001009
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001010 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1011 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1012 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001013 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregora59e3902010-01-21 23:27:09 +00001016 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001017}
1018
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001019bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1020 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001021}
1022
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001023bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001024 // 'ID' could be null when dealing with invalid code.
1025 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1026 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1027 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029 return VisitObjCImplDecl(D);
1030}
1031
1032bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1033#if 0
1034 // Issue callbacks for super class.
1035 // FIXME: No source location information!
1036 if (D->getSuperClass() &&
1037 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001038 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001039 TU)))
1040 return true;
1041#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043 return VisitObjCImplDecl(D);
1044}
1045
1046bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1047 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1048 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1049 E = D->protocol_end();
1050 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001051 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001052 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001053
1054 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001055}
1056
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001057bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1058 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1059 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1060 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001063}
1064
Douglas Gregora4ffd852010-11-17 01:03:52 +00001065bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1066 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1067 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1068
1069 return false;
1070}
1071
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001072bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1073 return VisitDeclContext(D);
1074}
1075
Douglas Gregor69319002010-08-31 23:48:11 +00001076bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
1078 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1079 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1080 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001081
1082 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1083 D->getTargetNameLoc(), TU));
1084}
1085
Douglas Gregor7e242562010-09-01 19:52:22 +00001086bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001088 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1089 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001091 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001092
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001093 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1094 return true;
1095
Douglas Gregor7e242562010-09-01 19:52:22 +00001096 return VisitDeclarationNameInfo(D->getNameInfo());
1097}
1098
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001099bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 // Visit nested-name-specifier.
1101 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1102 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1103 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001104
1105 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1106 D->getIdentLocation(), TU));
1107}
1108
Douglas Gregor7e242562010-09-01 19:52:22 +00001109bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001111 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1112 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001113 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001114 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115
Douglas Gregor7e242562010-09-01 19:52:22 +00001116 return VisitDeclarationNameInfo(D->getNameInfo());
1117}
1118
1119bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1120 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001122 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1123 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001124 return true;
1125
Douglas Gregor7e242562010-09-01 19:52:22 +00001126 return false;
1127}
1128
Douglas Gregor01829d32010-08-31 14:41:23 +00001129bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1130 switch (Name.getName().getNameKind()) {
1131 case clang::DeclarationName::Identifier:
1132 case clang::DeclarationName::CXXLiteralOperatorName:
1133 case clang::DeclarationName::CXXOperatorName:
1134 case clang::DeclarationName::CXXUsingDirective:
1135 return false;
1136
1137 case clang::DeclarationName::CXXConstructorName:
1138 case clang::DeclarationName::CXXDestructorName:
1139 case clang::DeclarationName::CXXConversionFunctionName:
1140 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1141 return Visit(TSInfo->getTypeLoc());
1142 return false;
1143
1144 case clang::DeclarationName::ObjCZeroArgSelector:
1145 case clang::DeclarationName::ObjCOneArgSelector:
1146 case clang::DeclarationName::ObjCMultiArgSelector:
1147 // FIXME: Per-identifier location info?
1148 return false;
1149 }
1150
1151 return false;
1152}
1153
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001154bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1155 SourceRange Range) {
1156 // FIXME: This whole routine is a hack to work around the lack of proper
1157 // source information in nested-name-specifiers (PR5791). Since we do have
1158 // a beginning source location, we can visit the first component of the
1159 // nested-name-specifier, if it's a single-token component.
1160 if (!NNS)
1161 return false;
1162
1163 // Get the first component in the nested-name-specifier.
1164 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1165 NNS = Prefix;
1166
1167 switch (NNS->getKind()) {
1168 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001169 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1170 TU));
1171
Douglas Gregor14aba762011-02-24 02:36:08 +00001172 case NestedNameSpecifier::NamespaceAlias:
1173 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1174 Range.getBegin(), TU));
1175
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001176 case NestedNameSpecifier::TypeSpec: {
1177 // If the type has a form where we know that the beginning of the source
1178 // range matches up with a reference cursor. Visit the appropriate reference
1179 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001180 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001181 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1182 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1183 if (const TagType *Tag = dyn_cast<TagType>(T))
1184 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1185 if (const TemplateSpecializationType *TST
1186 = dyn_cast<TemplateSpecializationType>(T))
1187 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1188 break;
1189 }
1190
1191 case NestedNameSpecifier::TypeSpecWithTemplate:
1192 case NestedNameSpecifier::Global:
1193 case NestedNameSpecifier::Identifier:
1194 break;
1195 }
1196
1197 return false;
1198}
1199
Douglas Gregordc355712011-02-25 00:36:19 +00001200bool
1201CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1202 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1203 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1204 Qualifiers.push_back(Qualifier);
1205
1206 while (!Qualifiers.empty()) {
1207 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1208 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1209 switch (NNS->getKind()) {
1210 case NestedNameSpecifier::Namespace:
1211 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1212 Q.getLocalSourceRange().getBegin(),
1213 TU)))
1214 return true;
1215
1216 break;
1217
1218 case NestedNameSpecifier::NamespaceAlias:
1219 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1220 Q.getLocalSourceRange().getBegin(),
1221 TU)))
1222 return true;
1223
1224 break;
1225
1226 case NestedNameSpecifier::TypeSpec:
1227 case NestedNameSpecifier::TypeSpecWithTemplate:
1228 if (Visit(Q.getTypeLoc()))
1229 return true;
1230
1231 break;
1232
1233 case NestedNameSpecifier::Global:
1234 case NestedNameSpecifier::Identifier:
1235 break;
1236 }
1237 }
1238
1239 return false;
1240}
1241
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001242bool CursorVisitor::VisitTemplateParameters(
1243 const TemplateParameterList *Params) {
1244 if (!Params)
1245 return false;
1246
1247 for (TemplateParameterList::const_iterator P = Params->begin(),
1248 PEnd = Params->end();
1249 P != PEnd; ++P) {
1250 if (Visit(MakeCXCursor(*P, TU)))
1251 return true;
1252 }
1253
1254 return false;
1255}
1256
Douglas Gregor0b36e612010-08-31 20:37:03 +00001257bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1258 switch (Name.getKind()) {
1259 case TemplateName::Template:
1260 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1261
1262 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001263 // Visit the overloaded template set.
1264 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1265 return true;
1266
Douglas Gregor0b36e612010-08-31 20:37:03 +00001267 return false;
1268
1269 case TemplateName::DependentTemplate:
1270 // FIXME: Visit nested-name-specifier.
1271 return false;
1272
1273 case TemplateName::QualifiedTemplate:
1274 // FIXME: Visit nested-name-specifier.
1275 return Visit(MakeCursorTemplateRef(
1276 Name.getAsQualifiedTemplateName()->getDecl(),
1277 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001278
1279 case TemplateName::SubstTemplateTemplateParmPack:
1280 return Visit(MakeCursorTemplateRef(
1281 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1282 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001283 }
1284
1285 return false;
1286}
1287
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001288bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1289 switch (TAL.getArgument().getKind()) {
1290 case TemplateArgument::Null:
1291 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001292 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001293 return false;
1294
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001295 case TemplateArgument::Type:
1296 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1297 return Visit(TSInfo->getTypeLoc());
1298 return false;
1299
1300 case TemplateArgument::Declaration:
1301 if (Expr *E = TAL.getSourceDeclExpression())
1302 return Visit(MakeCXCursor(E, StmtParent, TU));
1303 return false;
1304
1305 case TemplateArgument::Expression:
1306 if (Expr *E = TAL.getSourceExpression())
1307 return Visit(MakeCXCursor(E, StmtParent, TU));
1308 return false;
1309
1310 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001311 case TemplateArgument::TemplateExpansion:
1312 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001313 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001314 }
1315
1316 return false;
1317}
1318
Ted Kremeneka0536d82010-05-07 01:04:29 +00001319bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1320 return VisitDeclContext(D);
1321}
1322
Douglas Gregor01829d32010-08-31 14:41:23 +00001323bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1324 return Visit(TL.getUnqualifiedLoc());
1325}
1326
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001327bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001328 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001329
1330 // Some builtin types (such as Objective-C's "id", "sel", and
1331 // "Class") have associated declarations. Create cursors for those.
1332 QualType VisitType;
1333 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001334 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001336 case BuiltinType::Char_U:
1337 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338 case BuiltinType::Char16:
1339 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001340 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341 case BuiltinType::UInt:
1342 case BuiltinType::ULong:
1343 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001344 case BuiltinType::UInt128:
1345 case BuiltinType::Char_S:
1346 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001347 case BuiltinType::WChar_U:
1348 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001349 case BuiltinType::Short:
1350 case BuiltinType::Int:
1351 case BuiltinType::Long:
1352 case BuiltinType::LongLong:
1353 case BuiltinType::Int128:
1354 case BuiltinType::Float:
1355 case BuiltinType::Double:
1356 case BuiltinType::LongDouble:
1357 case BuiltinType::NullPtr:
1358 case BuiltinType::Overload:
1359 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001360 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001361
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001362 case BuiltinType::ObjCId:
1363 VisitType = Context.getObjCIdType();
1364 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001365
1366 case BuiltinType::ObjCClass:
1367 VisitType = Context.getObjCClassType();
1368 break;
1369
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370 case BuiltinType::ObjCSel:
1371 VisitType = Context.getObjCSelType();
1372 break;
1373 }
1374
1375 if (!VisitType.isNull()) {
1376 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378 TU));
1379 }
1380
1381 return false;
1382}
1383
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001384bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1385 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1386}
1387
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1389 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1390}
1391
1392bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1393 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1394}
1395
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001396bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001397 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001398 // no context information with which we can match up the depth/index in the
1399 // type to the appropriate
1400 return false;
1401}
1402
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001403bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1404 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1405 return true;
1406
John McCallc12c5bb2010-05-15 11:32:37 +00001407 return false;
1408}
1409
1410bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1411 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1412 return true;
1413
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001414 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1415 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1416 TU)))
1417 return true;
1418 }
1419
1420 return false;
1421}
1422
1423bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001424 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001425}
1426
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001427bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1428 return Visit(TL.getInnerLoc());
1429}
1430
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001431bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1432 return Visit(TL.getPointeeLoc());
1433}
1434
1435bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1436 return Visit(TL.getPointeeLoc());
1437}
1438
1439bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1440 return Visit(TL.getPointeeLoc());
1441}
1442
1443bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001444 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001445}
1446
1447bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001448 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001449}
1450
Douglas Gregor01829d32010-08-31 14:41:23 +00001451bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1452 bool SkipResultType) {
1453 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001454 return true;
1455
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001456 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001457 if (Decl *D = TL.getArg(I))
1458 if (Visit(MakeCXCursor(D, TU)))
1459 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001460
1461 return false;
1462}
1463
1464bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1465 if (Visit(TL.getElementLoc()))
1466 return true;
1467
1468 if (Expr *Size = TL.getSizeExpr())
1469 return Visit(MakeCXCursor(Size, StmtParent, TU));
1470
1471 return false;
1472}
1473
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001474bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1475 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001476 // Visit the template name.
1477 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1478 TL.getTemplateNameLoc()))
1479 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001480
1481 // Visit the template arguments.
1482 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1483 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1484 return true;
1485
1486 return false;
1487}
1488
Douglas Gregor2332c112010-01-21 20:48:56 +00001489bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1490 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1491}
1492
1493bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1494 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1495 return Visit(TSInfo->getTypeLoc());
1496
1497 return false;
1498}
1499
Douglas Gregor7536dd52010-12-20 02:24:11 +00001500bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1501 return Visit(TL.getPatternLoc());
1502}
1503
Ted Kremenek3064ef92010-08-27 21:34:58 +00001504bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1505 if (D->isDefinition()) {
1506 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1507 E = D->bases_end(); I != E; ++I) {
1508 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1509 return true;
1510 }
1511 }
1512
1513 return VisitTagDecl(D);
1514}
1515
Ted Kremenek09dfa372010-02-18 05:46:33 +00001516bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001517 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1518 i != e; ++i)
1519 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001520 return true;
1521
1522 return false;
1523}
1524
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001525//===----------------------------------------------------------------------===//
1526// Data-recursive visitor methods.
1527//===----------------------------------------------------------------------===//
1528
Ted Kremenek28a71942010-11-13 00:36:47 +00001529namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001530#define DEF_JOB(NAME, DATA, KIND)\
1531class NAME : public VisitorJob {\
1532public:\
1533 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1534 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001535 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001536};
1537
1538DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1539DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001540DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001541DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001542DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1543 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001544DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001545#undef DEF_JOB
1546
1547class DeclVisit : public VisitorJob {
1548public:
1549 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1550 VisitorJob(parent, VisitorJob::DeclVisitKind,
1551 d, isFirst ? (void*) 1 : (void*) 0) {}
1552 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001553 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001554 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001555 Decl *get() const { return static_cast<Decl*>(data[0]); }
1556 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001557};
Ted Kremenek035dc412010-11-13 00:36:50 +00001558class TypeLocVisit : public VisitorJob {
1559public:
1560 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1561 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1562 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1563
1564 static bool classof(const VisitorJob *VJ) {
1565 return VJ->getKind() == TypeLocVisitKind;
1566 }
1567
Ted Kremenek82f3c502010-11-15 22:23:26 +00001568 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001569 QualType T = QualType::getFromOpaquePtr(data[0]);
1570 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001571 }
1572};
1573
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001574class LabelRefVisit : public VisitorJob {
1575public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001576 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1577 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001578 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001579
1580 static bool classof(const VisitorJob *VJ) {
1581 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1582 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001583 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001584 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001585 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001586};
1587class NestedNameSpecifierVisit : public VisitorJob {
1588public:
1589 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1590 CXCursor parent)
1591 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001592 NS, R.getBegin().getPtrEncoding(),
1593 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001594 static bool classof(const VisitorJob *VJ) {
1595 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1596 }
1597 NestedNameSpecifier *get() const {
1598 return static_cast<NestedNameSpecifier*>(data[0]);
1599 }
1600 SourceRange getSourceRange() const {
1601 SourceLocation A =
1602 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1603 SourceLocation B =
1604 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1605 return SourceRange(A, B);
1606 }
1607};
1608class DeclarationNameInfoVisit : public VisitorJob {
1609public:
1610 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1611 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1612 static bool classof(const VisitorJob *VJ) {
1613 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1614 }
1615 DeclarationNameInfo get() const {
1616 Stmt *S = static_cast<Stmt*>(data[0]);
1617 switch (S->getStmtClass()) {
1618 default:
1619 llvm_unreachable("Unhandled Stmt");
1620 case Stmt::CXXDependentScopeMemberExprClass:
1621 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1622 case Stmt::DependentScopeDeclRefExprClass:
1623 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1624 }
1625 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001626};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001627class MemberRefVisit : public VisitorJob {
1628public:
1629 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1630 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001631 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001632 static bool classof(const VisitorJob *VJ) {
1633 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1634 }
1635 FieldDecl *get() const {
1636 return static_cast<FieldDecl*>(data[0]);
1637 }
1638 SourceLocation getLoc() const {
1639 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1640 }
1641};
Ted Kremenek28a71942010-11-13 00:36:47 +00001642class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1643 VisitorWorkList &WL;
1644 CXCursor Parent;
1645public:
1646 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1647 : WL(wl), Parent(parent) {}
1648
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001649 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001650 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001651 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001652 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001653 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001654 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001655 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001656 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001657 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001658 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001659 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001660 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001661 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001662 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001663 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001664 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001665 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001666 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001667 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1668 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001669 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001670 void VisitIfStmt(IfStmt *If);
1671 void VisitInitListExpr(InitListExpr *IE);
1672 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001673 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001674 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001675 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1676 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001677 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001678 void VisitStmt(Stmt *S);
1679 void VisitSwitchStmt(SwitchStmt *S);
1680 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001681 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001682 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001683 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001684 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001685 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001686
Ted Kremenek28a71942010-11-13 00:36:47 +00001687private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001688 void AddDeclarationNameInfo(Stmt *S);
1689 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001690 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001691 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001692 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001693 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001694 void AddTypeLoc(TypeSourceInfo *TI);
1695 void EnqueueChildren(Stmt *S);
1696};
1697} // end anonyous namespace
1698
Ted Kremenekf64d8032010-11-18 00:02:32 +00001699void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1700 // 'S' should always be non-null, since it comes from the
1701 // statement we are visiting.
1702 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1703}
1704void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1705 SourceRange R) {
1706 if (N)
1707 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1708}
Ted Kremenek28a71942010-11-13 00:36:47 +00001709void EnqueueVisitor::AddStmt(Stmt *S) {
1710 if (S)
1711 WL.push_back(StmtVisit(S, Parent));
1712}
Ted Kremenek035dc412010-11-13 00:36:50 +00001713void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001714 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001715 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001716}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001717void EnqueueVisitor::
1718 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1719 if (A)
1720 WL.push_back(ExplicitTemplateArgsVisit(
1721 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1722}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001723void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1724 if (D)
1725 WL.push_back(MemberRefVisit(D, L, Parent));
1726}
Ted Kremenek28a71942010-11-13 00:36:47 +00001727void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1728 if (TI)
1729 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1730 }
1731void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001732 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001733 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001734 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001735 }
1736 if (size == WL.size())
1737 return;
1738 // Now reverse the entries we just added. This will match the DFS
1739 // ordering performed by the worklist.
1740 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1741 std::reverse(I, E);
1742}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001743void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1744 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1745}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001746void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1747 AddDecl(B->getBlockDecl());
1748}
Ted Kremenek28a71942010-11-13 00:36:47 +00001749void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1750 EnqueueChildren(E);
1751 AddTypeLoc(E->getTypeSourceInfo());
1752}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001753void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1754 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1755 E = S->body_rend(); I != E; ++I) {
1756 AddStmt(*I);
1757 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001758}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001759void EnqueueVisitor::
1760VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1761 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1762 AddDeclarationNameInfo(E);
1763 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1764 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1765 if (!E->isImplicitAccess())
1766 AddStmt(E->getBase());
1767}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001768void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1769 // Enqueue the initializer or constructor arguments.
1770 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1771 AddStmt(E->getConstructorArg(I-1));
1772 // Enqueue the array size, if any.
1773 AddStmt(E->getArraySize());
1774 // Enqueue the allocated type.
1775 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1776 // Enqueue the placement arguments.
1777 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1778 AddStmt(E->getPlacementArg(I-1));
1779}
Ted Kremenek28a71942010-11-13 00:36:47 +00001780void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001781 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1782 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001783 AddStmt(CE->getCallee());
1784 AddStmt(CE->getArg(0));
1785}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001786void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1787 // Visit the name of the type being destroyed.
1788 AddTypeLoc(E->getDestroyedTypeInfo());
1789 // Visit the scope type that looks disturbingly like the nested-name-specifier
1790 // but isn't.
1791 AddTypeLoc(E->getScopeTypeInfo());
1792 // Visit the nested-name-specifier.
1793 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1794 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1795 // Visit base expression.
1796 AddStmt(E->getBase());
1797}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001798void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1799 AddTypeLoc(E->getTypeSourceInfo());
1800}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001801void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1802 EnqueueChildren(E);
1803 AddTypeLoc(E->getTypeSourceInfo());
1804}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001805void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1806 EnqueueChildren(E);
1807 if (E->isTypeOperand())
1808 AddTypeLoc(E->getTypeOperandSourceInfo());
1809}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001810
1811void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1812 *E) {
1813 EnqueueChildren(E);
1814 AddTypeLoc(E->getTypeSourceInfo());
1815}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001816void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1817 EnqueueChildren(E);
1818 if (E->isTypeOperand())
1819 AddTypeLoc(E->getTypeOperandSourceInfo());
1820}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001821void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001822 if (DR->hasExplicitTemplateArgs()) {
1823 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1824 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001825 WL.push_back(DeclRefExprParts(DR, Parent));
1826}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001827void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1828 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1829 AddDeclarationNameInfo(E);
1830 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1831 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1832}
Ted Kremenek035dc412010-11-13 00:36:50 +00001833void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1834 unsigned size = WL.size();
1835 bool isFirst = true;
1836 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1837 D != DEnd; ++D) {
1838 AddDecl(*D, isFirst);
1839 isFirst = false;
1840 }
1841 if (size == WL.size())
1842 return;
1843 // Now reverse the entries we just added. This will match the DFS
1844 // ordering performed by the worklist.
1845 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1846 std::reverse(I, E);
1847}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001848void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1849 AddStmt(E->getInit());
1850 typedef DesignatedInitExpr::Designator Designator;
1851 for (DesignatedInitExpr::reverse_designators_iterator
1852 D = E->designators_rbegin(), DEnd = E->designators_rend();
1853 D != DEnd; ++D) {
1854 if (D->isFieldDesignator()) {
1855 if (FieldDecl *Field = D->getField())
1856 AddMemberRef(Field, D->getFieldLoc());
1857 continue;
1858 }
1859 if (D->isArrayDesignator()) {
1860 AddStmt(E->getArrayIndex(*D));
1861 continue;
1862 }
1863 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1864 AddStmt(E->getArrayRangeEnd(*D));
1865 AddStmt(E->getArrayRangeStart(*D));
1866 }
1867}
Ted Kremenek28a71942010-11-13 00:36:47 +00001868void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1869 EnqueueChildren(E);
1870 AddTypeLoc(E->getTypeInfoAsWritten());
1871}
1872void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1873 AddStmt(FS->getBody());
1874 AddStmt(FS->getInc());
1875 AddStmt(FS->getCond());
1876 AddDecl(FS->getConditionVariable());
1877 AddStmt(FS->getInit());
1878}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001879void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1880 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1881}
Ted Kremenek28a71942010-11-13 00:36:47 +00001882void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1883 AddStmt(If->getElse());
1884 AddStmt(If->getThen());
1885 AddStmt(If->getCond());
1886 AddDecl(If->getConditionVariable());
1887}
1888void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1889 // We care about the syntactic form of the initializer list, only.
1890 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1891 IE = Syntactic;
1892 EnqueueChildren(IE);
1893}
1894void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001895 WL.push_back(MemberExprParts(M, Parent));
1896
1897 // If the base of the member access expression is an implicit 'this', don't
1898 // visit it.
1899 // FIXME: If we ever want to show these implicit accesses, this will be
1900 // unfortunate. However, clang_getCursor() relies on this behavior.
1901 if (CXXThisExpr *This
1902 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1903 if (This->isImplicit())
1904 return;
1905
Ted Kremenek28a71942010-11-13 00:36:47 +00001906 AddStmt(M->getBase());
1907}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001908void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1909 AddTypeLoc(E->getEncodedTypeSourceInfo());
1910}
Ted Kremenek28a71942010-11-13 00:36:47 +00001911void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1912 EnqueueChildren(M);
1913 AddTypeLoc(M->getClassReceiverTypeInfo());
1914}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001915void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1916 // Visit the components of the offsetof expression.
1917 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1918 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1919 const OffsetOfNode &Node = E->getComponent(I-1);
1920 switch (Node.getKind()) {
1921 case OffsetOfNode::Array:
1922 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1923 break;
1924 case OffsetOfNode::Field:
1925 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1926 break;
1927 case OffsetOfNode::Identifier:
1928 case OffsetOfNode::Base:
1929 continue;
1930 }
1931 }
1932 // Visit the type into which we're computing the offset.
1933 AddTypeLoc(E->getTypeSourceInfo());
1934}
Ted Kremenek28a71942010-11-13 00:36:47 +00001935void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001936 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001937 WL.push_back(OverloadExprParts(E, Parent));
1938}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001939void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1940 EnqueueChildren(E);
1941 if (E->isArgumentType())
1942 AddTypeLoc(E->getArgumentTypeInfo());
1943}
Ted Kremenek28a71942010-11-13 00:36:47 +00001944void EnqueueVisitor::VisitStmt(Stmt *S) {
1945 EnqueueChildren(S);
1946}
1947void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1948 AddStmt(S->getBody());
1949 AddStmt(S->getCond());
1950 AddDecl(S->getConditionVariable());
1951}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001952
Ted Kremenek28a71942010-11-13 00:36:47 +00001953void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1954 AddStmt(W->getBody());
1955 AddStmt(W->getCond());
1956 AddDecl(W->getConditionVariable());
1957}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001958void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1959 AddTypeLoc(E->getQueriedTypeSourceInfo());
1960}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001961
1962void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00001963 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00001964 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00001965}
1966
Ted Kremenek28a71942010-11-13 00:36:47 +00001967void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1968 VisitOverloadExpr(U);
1969 if (!U->isImplicitAccess())
1970 AddStmt(U->getBase());
1971}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001972void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1973 AddStmt(E->getSubExpr());
1974 AddTypeLoc(E->getWrittenTypeInfo());
1975}
Douglas Gregor94d96292011-01-19 20:34:17 +00001976void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1977 WL.push_back(SizeOfPackExprParts(E, Parent));
1978}
Ted Kremenek60458782010-11-12 21:34:16 +00001979
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001980void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001981 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001982}
1983
1984bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1985 if (RegionOfInterest.isValid()) {
1986 SourceRange Range = getRawCursorExtent(C);
1987 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1988 return false;
1989 }
1990 return true;
1991}
1992
1993bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1994 while (!WL.empty()) {
1995 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001996 VisitorJob LI = WL.back();
1997 WL.pop_back();
1998
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001999 // Set the Parent field, then back to its old value once we're done.
2000 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2001
2002 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002003 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002004 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002005 if (!D)
2006 continue;
2007
2008 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002009 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002010 return true;
2011
2012 continue;
2013 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002014 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2015 const ExplicitTemplateArgumentList *ArgList =
2016 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2017 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2018 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2019 Arg != ArgEnd; ++Arg) {
2020 if (VisitTemplateArgumentLoc(*Arg))
2021 return true;
2022 }
2023 continue;
2024 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002025 case VisitorJob::TypeLocVisitKind: {
2026 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002027 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002028 return true;
2029 continue;
2030 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002031 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002032 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002033 if (LabelStmt *stmt = LS->getStmt()) {
2034 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2035 TU))) {
2036 return true;
2037 }
2038 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002039 continue;
2040 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00002041 case VisitorJob::NestedNameSpecifierVisitKind: {
2042 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2043 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2044 return true;
2045 continue;
2046 }
2047 case VisitorJob::DeclarationNameInfoVisitKind: {
2048 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2049 ->get()))
2050 return true;
2051 continue;
2052 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002053 case VisitorJob::MemberRefVisitKind: {
2054 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2055 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2056 return true;
2057 continue;
2058 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002059 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002060 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002061 if (!S)
2062 continue;
2063
Ted Kremenekf1107452010-11-12 18:26:56 +00002064 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002065 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002066 if (!IsInRegionOfInterest(Cursor))
2067 continue;
2068 switch (Visitor(Cursor, Parent, ClientData)) {
2069 case CXChildVisit_Break: return true;
2070 case CXChildVisit_Continue: break;
2071 case CXChildVisit_Recurse:
2072 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002073 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002074 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002075 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002076 }
2077 case VisitorJob::MemberExprPartsKind: {
2078 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002079 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002080
2081 // Visit the nested-name-specifier
2082 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2083 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2084 return true;
2085
2086 // Visit the declaration name.
2087 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2088 return true;
2089
2090 // Visit the explicitly-specified template arguments, if any.
2091 if (M->hasExplicitTemplateArgs()) {
2092 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2093 *ArgEnd = Arg + M->getNumTemplateArgs();
2094 Arg != ArgEnd; ++Arg) {
2095 if (VisitTemplateArgumentLoc(*Arg))
2096 return true;
2097 }
2098 }
2099 continue;
2100 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002101 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002102 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002103 // Visit nested-name-specifier, if present.
2104 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2105 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2106 return true;
2107 // Visit declaration name.
2108 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2109 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002110 continue;
2111 }
Ted Kremenek60458782010-11-12 21:34:16 +00002112 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002113 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002114 // Visit the nested-name-specifier.
2115 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2116 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2117 return true;
2118 // Visit the declaration name.
2119 if (VisitDeclarationNameInfo(O->getNameInfo()))
2120 return true;
2121 // Visit the overloaded declaration reference.
2122 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2123 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002124 continue;
2125 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002126 case VisitorJob::SizeOfPackExprPartsKind: {
2127 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2128 NamedDecl *Pack = E->getPack();
2129 if (isa<TemplateTypeParmDecl>(Pack)) {
2130 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2131 E->getPackLoc(), TU)))
2132 return true;
2133
2134 continue;
2135 }
2136
2137 if (isa<TemplateTemplateParmDecl>(Pack)) {
2138 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2139 E->getPackLoc(), TU)))
2140 return true;
2141
2142 continue;
2143 }
2144
2145 // Non-type template parameter packs and function parameter packs are
2146 // treated like DeclRefExpr cursors.
2147 continue;
2148 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002149 }
2150 }
2151 return false;
2152}
2153
Ted Kremenekcdba6592010-11-18 00:42:18 +00002154bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002155 VisitorWorkList *WL = 0;
2156 if (!WorkListFreeList.empty()) {
2157 WL = WorkListFreeList.back();
2158 WL->clear();
2159 WorkListFreeList.pop_back();
2160 }
2161 else {
2162 WL = new VisitorWorkList();
2163 WorkListCache.push_back(WL);
2164 }
2165 EnqueueWorkList(*WL, S);
2166 bool result = RunVisitorWorkList(*WL);
2167 WorkListFreeList.push_back(WL);
2168 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002169}
2170
2171//===----------------------------------------------------------------------===//
2172// Misc. API hooks.
2173//===----------------------------------------------------------------------===//
2174
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002175static llvm::sys::Mutex EnableMultithreadingMutex;
2176static bool EnabledMultithreading;
2177
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002178extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002179CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2180 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002181 // Disable pretty stack trace functionality, which will otherwise be a very
2182 // poor citizen of the world and set up all sorts of signal handlers.
2183 llvm::DisablePrettyStackTrace = true;
2184
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002185 // We use crash recovery to make some of our APIs more reliable, implicitly
2186 // enable it.
2187 llvm::CrashRecoveryContext::Enable();
2188
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002189 // Enable support for multithreading in LLVM.
2190 {
2191 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2192 if (!EnabledMultithreading) {
2193 llvm::llvm_start_multithreaded();
2194 EnabledMultithreading = true;
2195 }
2196 }
2197
Douglas Gregora030b7c2010-01-22 20:35:53 +00002198 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002199 if (excludeDeclarationsFromPCH)
2200 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002201 if (displayDiagnostics)
2202 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002203 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002204}
2205
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002206void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002207 if (CIdx)
2208 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002209}
2210
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002211CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002212 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002213 if (!CIdx)
2214 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002215
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002216 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002217 FileSystemOptions FileSystemOpts;
2218 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002219
Douglas Gregor28019772010-04-05 23:52:57 +00002220 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002221 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002222 CXXIdx->getOnlyLocalDecls(),
2223 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002224 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002225}
2226
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002227unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002228 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002229 CXTranslationUnit_CacheCompletionResults |
2230 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002231}
2232
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002233CXTranslationUnit
2234clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2235 const char *source_filename,
2236 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002237 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002238 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002239 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002240 return clang_parseTranslationUnit(CIdx, source_filename,
2241 command_line_args, num_command_line_args,
2242 unsaved_files, num_unsaved_files,
2243 CXTranslationUnit_DetailedPreprocessingRecord);
2244}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002245
2246struct ParseTranslationUnitInfo {
2247 CXIndex CIdx;
2248 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002249 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002250 int num_command_line_args;
2251 struct CXUnsavedFile *unsaved_files;
2252 unsigned num_unsaved_files;
2253 unsigned options;
2254 CXTranslationUnit result;
2255};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002256static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002257 ParseTranslationUnitInfo *PTUI =
2258 static_cast<ParseTranslationUnitInfo*>(UserData);
2259 CXIndex CIdx = PTUI->CIdx;
2260 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002261 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002262 int num_command_line_args = PTUI->num_command_line_args;
2263 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2264 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2265 unsigned options = PTUI->options;
2266 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002267
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002268 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002269 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002270
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002271 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2272
Douglas Gregor44c181a2010-07-23 00:33:23 +00002273 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002274 bool CompleteTranslationUnit
2275 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002276 bool CacheCodeCompetionResults
2277 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002278 bool CXXPrecompilePreamble
2279 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2280 bool CXXChainedPCH
2281 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002282
Douglas Gregor5352ac02010-01-28 00:27:43 +00002283 // Configure the diagnostics.
2284 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002285 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002286 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2287 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002288
Douglas Gregor4db64a42010-01-23 00:14:00 +00002289 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2290 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002291 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002292 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002293 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002294 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2295 Buffer));
2296 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002297
Douglas Gregorb10daed2010-10-11 16:52:23 +00002298 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002299
Ted Kremenek139ba862009-10-22 00:03:57 +00002300 // The 'source_filename' argument is optional. If the caller does not
2301 // specify it then it is assumed that the source file is specified
2302 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002303 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002304 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002305
2306 // Since the Clang C library is primarily used by batch tools dealing with
2307 // (often very broken) source code, where spell-checking can have a
2308 // significant negative impact on performance (particularly when
2309 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002310 // Only do this if we haven't found a spell-checking-related argument.
2311 bool FoundSpellCheckingArgument = false;
2312 for (int I = 0; I != num_command_line_args; ++I) {
2313 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2314 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2315 FoundSpellCheckingArgument = true;
2316 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002317 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002318 }
2319 if (!FoundSpellCheckingArgument)
2320 Args.push_back("-fno-spell-checking");
2321
2322 Args.insert(Args.end(), command_line_args,
2323 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002324
Douglas Gregor44c181a2010-07-23 00:33:23 +00002325 // Do we need the detailed preprocessing record?
2326 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002327 Args.push_back("-Xclang");
2328 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002329 }
2330
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002331 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002332 llvm::OwningPtr<ASTUnit> Unit(
2333 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2334 Diags,
2335 CXXIdx->getClangResourcesPath(),
2336 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002337 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002338 RemappedFiles.data(),
2339 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002340 PrecompilePreamble,
2341 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002342 CacheCodeCompetionResults,
2343 CXXPrecompilePreamble,
2344 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002345
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002346 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002347 // Make sure to check that 'Unit' is non-NULL.
2348 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2349 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2350 DEnd = Unit->stored_diag_end();
2351 D != DEnd; ++D) {
2352 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2353 CXString Msg = clang_formatDiagnostic(&Diag,
2354 clang_defaultDiagnosticDisplayOptions());
2355 fprintf(stderr, "%s\n", clang_getCString(Msg));
2356 clang_disposeString(Msg);
2357 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002358#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002359 // On Windows, force a flush, since there may be multiple copies of
2360 // stderr and stdout in the file system, all with different buffers
2361 // but writing to the same device.
2362 fflush(stderr);
2363#endif
2364 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002365 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002366
Ted Kremeneka60ed472010-11-16 08:15:36 +00002367 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002368}
2369CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2370 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002371 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002372 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002373 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002374 unsigned num_unsaved_files,
2375 unsigned options) {
2376 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002377 num_command_line_args, unsaved_files,
2378 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002379 llvm::CrashRecoveryContext CRC;
2380
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002381 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002382 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2383 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2384 fprintf(stderr, " 'command_line_args' : [");
2385 for (int i = 0; i != num_command_line_args; ++i) {
2386 if (i)
2387 fprintf(stderr, ", ");
2388 fprintf(stderr, "'%s'", command_line_args[i]);
2389 }
2390 fprintf(stderr, "],\n");
2391 fprintf(stderr, " 'unsaved_files' : [");
2392 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2393 if (i)
2394 fprintf(stderr, ", ");
2395 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2396 unsaved_files[i].Length);
2397 }
2398 fprintf(stderr, "],\n");
2399 fprintf(stderr, " 'options' : %d,\n", options);
2400 fprintf(stderr, "}\n");
2401
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002402 return 0;
2403 }
2404
2405 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002406}
2407
Douglas Gregor19998442010-08-13 15:35:05 +00002408unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2409 return CXSaveTranslationUnit_None;
2410}
2411
2412int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2413 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002414 if (!TU)
2415 return 1;
2416
Ted Kremeneka60ed472010-11-16 08:15:36 +00002417 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002418}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002419
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002420void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002421 if (CTUnit) {
2422 // If the translation unit has been marked as unsafe to free, just discard
2423 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002424 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002425 return;
2426
Ted Kremeneka60ed472010-11-16 08:15:36 +00002427 delete static_cast<ASTUnit *>(CTUnit->TUData);
2428 disposeCXStringPool(CTUnit->StringPool);
2429 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002430 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002431}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002432
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002433unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2434 return CXReparse_None;
2435}
2436
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002437struct ReparseTranslationUnitInfo {
2438 CXTranslationUnit TU;
2439 unsigned num_unsaved_files;
2440 struct CXUnsavedFile *unsaved_files;
2441 unsigned options;
2442 int result;
2443};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002444
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002445static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002446 ReparseTranslationUnitInfo *RTUI =
2447 static_cast<ReparseTranslationUnitInfo*>(UserData);
2448 CXTranslationUnit TU = RTUI->TU;
2449 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2450 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2451 unsigned options = RTUI->options;
2452 (void) options;
2453 RTUI->result = 1;
2454
Douglas Gregorabc563f2010-07-19 21:46:24 +00002455 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002456 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002457
Ted Kremeneka60ed472010-11-16 08:15:36 +00002458 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002459 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002460
2461 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2462 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2463 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2464 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002465 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002466 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2467 Buffer));
2468 }
2469
Douglas Gregor593b0c12010-09-23 18:47:53 +00002470 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2471 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002472}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002473
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002474int clang_reparseTranslationUnit(CXTranslationUnit TU,
2475 unsigned num_unsaved_files,
2476 struct CXUnsavedFile *unsaved_files,
2477 unsigned options) {
2478 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2479 options, 0 };
2480 llvm::CrashRecoveryContext CRC;
2481
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002482 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002483 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002484 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002485 return 1;
2486 }
2487
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002488
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002489 return RTUI.result;
2490}
2491
Douglas Gregordf95a132010-08-09 20:45:32 +00002492
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002493CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002494 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002495 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002496
Ted Kremeneka60ed472010-11-16 08:15:36 +00002497 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002498 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002499}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002500
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002501CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002502 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002503 return Result;
2504}
2505
Ted Kremenekfb480492010-01-13 21:46:36 +00002506} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002507
Ted Kremenekfb480492010-01-13 21:46:36 +00002508//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002509// CXSourceLocation and CXSourceRange Operations.
2510//===----------------------------------------------------------------------===//
2511
Douglas Gregorb9790342010-01-22 21:44:22 +00002512extern "C" {
2513CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002514 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002515 return Result;
2516}
2517
2518unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002519 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2520 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2521 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002522}
2523
2524CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2525 CXFile file,
2526 unsigned line,
2527 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002528 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002529 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002530
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002531 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002532 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002533 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002534 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002535 = CXXUnit->getSourceManager().getLocation(File, line, column);
2536 if (SLoc.isInvalid()) {
2537 if (Logging)
2538 llvm::errs() << "clang_getLocation(\"" << File->getName()
2539 << "\", " << line << ", " << column << ") = invalid\n";
2540 return clang_getNullLocation();
2541 }
2542
2543 if (Logging)
2544 llvm::errs() << "clang_getLocation(\"" << File->getName()
2545 << "\", " << line << ", " << column << ") = "
2546 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002547
2548 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2549}
2550
2551CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2552 CXFile file,
2553 unsigned offset) {
2554 if (!tu || !file)
2555 return clang_getNullLocation();
2556
Ted Kremeneka60ed472010-11-16 08:15:36 +00002557 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002558 SourceLocation Start
2559 = CXXUnit->getSourceManager().getLocation(
2560 static_cast<const FileEntry *>(file),
2561 1, 1);
2562 if (Start.isInvalid()) return clang_getNullLocation();
2563
2564 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2565
2566 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002567
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002568 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002569}
2570
Douglas Gregor5352ac02010-01-28 00:27:43 +00002571CXSourceRange clang_getNullRange() {
2572 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2573 return Result;
2574}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002575
Douglas Gregor5352ac02010-01-28 00:27:43 +00002576CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2577 if (begin.ptr_data[0] != end.ptr_data[0] ||
2578 begin.ptr_data[1] != end.ptr_data[1])
2579 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002580
2581 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002582 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002583 return Result;
2584}
2585
Douglas Gregor46766dc2010-01-26 19:19:08 +00002586void clang_getInstantiationLocation(CXSourceLocation location,
2587 CXFile *file,
2588 unsigned *line,
2589 unsigned *column,
2590 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002591 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2592
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002593 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002594 if (file)
2595 *file = 0;
2596 if (line)
2597 *line = 0;
2598 if (column)
2599 *column = 0;
2600 if (offset)
2601 *offset = 0;
2602 return;
2603 }
2604
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002605 const SourceManager &SM =
2606 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002607 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002608
2609 if (file)
2610 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2611 if (line)
2612 *line = SM.getInstantiationLineNumber(InstLoc);
2613 if (column)
2614 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002615 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002616 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002617}
2618
Douglas Gregora9b06d42010-11-09 06:24:54 +00002619void clang_getSpellingLocation(CXSourceLocation location,
2620 CXFile *file,
2621 unsigned *line,
2622 unsigned *column,
2623 unsigned *offset) {
2624 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2625
2626 if (!location.ptr_data[0] || Loc.isInvalid()) {
2627 if (file)
2628 *file = 0;
2629 if (line)
2630 *line = 0;
2631 if (column)
2632 *column = 0;
2633 if (offset)
2634 *offset = 0;
2635 return;
2636 }
2637
2638 const SourceManager &SM =
2639 *static_cast<const SourceManager*>(location.ptr_data[0]);
2640 SourceLocation SpellLoc = Loc;
2641 if (SpellLoc.isMacroID()) {
2642 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2643 if (SimpleSpellingLoc.isFileID() &&
2644 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2645 SpellLoc = SimpleSpellingLoc;
2646 else
2647 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2648 }
2649
2650 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2651 FileID FID = LocInfo.first;
2652 unsigned FileOffset = LocInfo.second;
2653
2654 if (file)
2655 *file = (void *)SM.getFileEntryForID(FID);
2656 if (line)
2657 *line = SM.getLineNumber(FID, FileOffset);
2658 if (column)
2659 *column = SM.getColumnNumber(FID, FileOffset);
2660 if (offset)
2661 *offset = FileOffset;
2662}
2663
Douglas Gregor1db19de2010-01-19 21:36:55 +00002664CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002665 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002666 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002667 return Result;
2668}
2669
2670CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002671 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002672 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002673 return Result;
2674}
2675
Douglas Gregorb9790342010-01-22 21:44:22 +00002676} // end: extern "C"
2677
Douglas Gregor1db19de2010-01-19 21:36:55 +00002678//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002679// CXFile Operations.
2680//===----------------------------------------------------------------------===//
2681
2682extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002683CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002684 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002685 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002686
Steve Naroff88145032009-10-27 14:35:18 +00002687 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002688 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002689}
2690
2691time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002692 if (!SFile)
2693 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002694
Steve Naroff88145032009-10-27 14:35:18 +00002695 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2696 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002697}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002698
Douglas Gregorb9790342010-01-22 21:44:22 +00002699CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2700 if (!tu)
2701 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002702
Ted Kremeneka60ed472010-11-16 08:15:36 +00002703 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002704
Douglas Gregorb9790342010-01-22 21:44:22 +00002705 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002706 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002707}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002708
Ted Kremenekfb480492010-01-13 21:46:36 +00002709} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002710
Ted Kremenekfb480492010-01-13 21:46:36 +00002711//===----------------------------------------------------------------------===//
2712// CXCursor Operations.
2713//===----------------------------------------------------------------------===//
2714
Ted Kremenekfb480492010-01-13 21:46:36 +00002715static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002716 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2717 return getDeclFromExpr(CE->getSubExpr());
2718
Ted Kremenekfb480492010-01-13 21:46:36 +00002719 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2720 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002721 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2722 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002723 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2724 return ME->getMemberDecl();
2725 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2726 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002727 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002728 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002729
Ted Kremenekfb480492010-01-13 21:46:36 +00002730 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2731 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002732 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2733 if (!CE->isElidable())
2734 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002735 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2736 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002737
Douglas Gregordb1314e2010-10-01 21:11:22 +00002738 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2739 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002740 if (SubstNonTypeTemplateParmPackExpr *NTTP
2741 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2742 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002743 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2744 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2745 isa<ParmVarDecl>(SizeOfPack->getPack()))
2746 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002747
Ted Kremenekfb480492010-01-13 21:46:36 +00002748 return 0;
2749}
2750
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002751static SourceLocation getLocationFromExpr(Expr *E) {
2752 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2753 return /*FIXME:*/Msg->getLeftLoc();
2754 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2755 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002756 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2757 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002758 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2759 return Member->getMemberLoc();
2760 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2761 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002762 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2763 return SizeOfPack->getPackLoc();
2764
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002765 return E->getLocStart();
2766}
2767
Ted Kremenekfb480492010-01-13 21:46:36 +00002768extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002769
2770unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002771 CXCursorVisitor visitor,
2772 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002773 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2774 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002775 return CursorVis.VisitChildren(parent);
2776}
2777
David Chisnall3387c652010-11-03 14:12:26 +00002778#ifndef __has_feature
2779#define __has_feature(x) 0
2780#endif
2781#if __has_feature(blocks)
2782typedef enum CXChildVisitResult
2783 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2784
2785static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2786 CXClientData client_data) {
2787 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2788 return block(cursor, parent);
2789}
2790#else
2791// If we are compiled with a compiler that doesn't have native blocks support,
2792// define and call the block manually, so the
2793typedef struct _CXChildVisitResult
2794{
2795 void *isa;
2796 int flags;
2797 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002798 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2799 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002800} *CXCursorVisitorBlock;
2801
2802static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2803 CXClientData client_data) {
2804 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2805 return block->invoke(block, cursor, parent);
2806}
2807#endif
2808
2809
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002810unsigned clang_visitChildrenWithBlock(CXCursor parent,
2811 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002812 return clang_visitChildren(parent, visitWithBlock, block);
2813}
2814
Douglas Gregor78205d42010-01-20 21:45:58 +00002815static CXString getDeclSpelling(Decl *D) {
2816 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002817 if (!ND) {
2818 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2819 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2820 return createCXString(Property->getIdentifier()->getName());
2821
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002822 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002823 }
2824
Douglas Gregor78205d42010-01-20 21:45:58 +00002825 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002826 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002827
Douglas Gregor78205d42010-01-20 21:45:58 +00002828 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2829 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2830 // and returns different names. NamedDecl returns the class name and
2831 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002832 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002833
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002834 if (isa<UsingDirectiveDecl>(D))
2835 return createCXString("");
2836
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002837 llvm::SmallString<1024> S;
2838 llvm::raw_svector_ostream os(S);
2839 ND->printName(os);
2840
2841 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002842}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002843
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002844CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002845 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002846 return clang_getTranslationUnitSpelling(
2847 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002848
Steve Narofff334b4e2009-09-02 18:26:48 +00002849 if (clang_isReference(C.kind)) {
2850 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002851 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002852 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002853 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002854 }
2855 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002856 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002857 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002858 }
2859 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002860 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002861 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002862 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002863 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002864 case CXCursor_CXXBaseSpecifier: {
2865 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2866 return createCXString(B->getType().getAsString());
2867 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002868 case CXCursor_TypeRef: {
2869 TypeDecl *Type = getCursorTypeRef(C).first;
2870 assert(Type && "Missing type decl");
2871
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002872 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2873 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002874 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002875 case CXCursor_TemplateRef: {
2876 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002877 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002878
2879 return createCXString(Template->getNameAsString());
2880 }
Douglas Gregor69319002010-08-31 23:48:11 +00002881
2882 case CXCursor_NamespaceRef: {
2883 NamedDecl *NS = getCursorNamespaceRef(C).first;
2884 assert(NS && "Missing namespace decl");
2885
2886 return createCXString(NS->getNameAsString());
2887 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002888
Douglas Gregora67e03f2010-09-09 21:42:20 +00002889 case CXCursor_MemberRef: {
2890 FieldDecl *Field = getCursorMemberRef(C).first;
2891 assert(Field && "Missing member decl");
2892
2893 return createCXString(Field->getNameAsString());
2894 }
2895
Douglas Gregor36897b02010-09-10 00:22:18 +00002896 case CXCursor_LabelRef: {
2897 LabelStmt *Label = getCursorLabelRef(C).first;
2898 assert(Label && "Missing label");
2899
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002900 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002901 }
2902
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002903 case CXCursor_OverloadedDeclRef: {
2904 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2905 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2906 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2907 return createCXString(ND->getNameAsString());
2908 return createCXString("");
2909 }
2910 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2911 return createCXString(E->getName().getAsString());
2912 OverloadedTemplateStorage *Ovl
2913 = Storage.get<OverloadedTemplateStorage*>();
2914 if (Ovl->size() == 0)
2915 return createCXString("");
2916 return createCXString((*Ovl->begin())->getNameAsString());
2917 }
2918
Daniel Dunbaracca7252009-11-30 20:42:49 +00002919 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002920 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002921 }
2922 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002923
2924 if (clang_isExpression(C.kind)) {
2925 Decl *D = getDeclFromExpr(getCursorExpr(C));
2926 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002927 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002928 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002929 }
2930
Douglas Gregor36897b02010-09-10 00:22:18 +00002931 if (clang_isStatement(C.kind)) {
2932 Stmt *S = getCursorStmt(C);
2933 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002934 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002935
2936 return createCXString("");
2937 }
2938
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002939 if (C.kind == CXCursor_MacroInstantiation)
2940 return createCXString(getCursorMacroInstantiation(C)->getName()
2941 ->getNameStart());
2942
Douglas Gregor572feb22010-03-18 18:04:21 +00002943 if (C.kind == CXCursor_MacroDefinition)
2944 return createCXString(getCursorMacroDefinition(C)->getName()
2945 ->getNameStart());
2946
Douglas Gregorecdcb882010-10-20 22:00:55 +00002947 if (C.kind == CXCursor_InclusionDirective)
2948 return createCXString(getCursorInclusionDirective(C)->getFileName());
2949
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002950 if (clang_isDeclaration(C.kind))
2951 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002952
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002953 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002954}
2955
Douglas Gregor358559d2010-10-02 22:49:11 +00002956CXString clang_getCursorDisplayName(CXCursor C) {
2957 if (!clang_isDeclaration(C.kind))
2958 return clang_getCursorSpelling(C);
2959
2960 Decl *D = getCursorDecl(C);
2961 if (!D)
2962 return createCXString("");
2963
2964 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2965 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2966 D = FunTmpl->getTemplatedDecl();
2967
2968 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2969 llvm::SmallString<64> Str;
2970 llvm::raw_svector_ostream OS(Str);
2971 OS << Function->getNameAsString();
2972 if (Function->getPrimaryTemplate())
2973 OS << "<>";
2974 OS << "(";
2975 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2976 if (I)
2977 OS << ", ";
2978 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2979 }
2980
2981 if (Function->isVariadic()) {
2982 if (Function->getNumParams())
2983 OS << ", ";
2984 OS << "...";
2985 }
2986 OS << ")";
2987 return createCXString(OS.str());
2988 }
2989
2990 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2991 llvm::SmallString<64> Str;
2992 llvm::raw_svector_ostream OS(Str);
2993 OS << ClassTemplate->getNameAsString();
2994 OS << "<";
2995 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2996 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2997 if (I)
2998 OS << ", ";
2999
3000 NamedDecl *Param = Params->getParam(I);
3001 if (Param->getIdentifier()) {
3002 OS << Param->getIdentifier()->getName();
3003 continue;
3004 }
3005
3006 // There is no parameter name, which makes this tricky. Try to come up
3007 // with something useful that isn't too long.
3008 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3009 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3010 else if (NonTypeTemplateParmDecl *NTTP
3011 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3012 OS << NTTP->getType().getAsString(Policy);
3013 else
3014 OS << "template<...> class";
3015 }
3016
3017 OS << ">";
3018 return createCXString(OS.str());
3019 }
3020
3021 if (ClassTemplateSpecializationDecl *ClassSpec
3022 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3023 // If the type was explicitly written, use that.
3024 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3025 return createCXString(TSInfo->getType().getAsString(Policy));
3026
3027 llvm::SmallString<64> Str;
3028 llvm::raw_svector_ostream OS(Str);
3029 OS << ClassSpec->getNameAsString();
3030 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003031 ClassSpec->getTemplateArgs().data(),
3032 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003033 Policy);
3034 return createCXString(OS.str());
3035 }
3036
3037 return clang_getCursorSpelling(C);
3038}
3039
Ted Kremeneke68fff62010-02-17 00:41:32 +00003040CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003041 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003042 case CXCursor_FunctionDecl:
3043 return createCXString("FunctionDecl");
3044 case CXCursor_TypedefDecl:
3045 return createCXString("TypedefDecl");
3046 case CXCursor_EnumDecl:
3047 return createCXString("EnumDecl");
3048 case CXCursor_EnumConstantDecl:
3049 return createCXString("EnumConstantDecl");
3050 case CXCursor_StructDecl:
3051 return createCXString("StructDecl");
3052 case CXCursor_UnionDecl:
3053 return createCXString("UnionDecl");
3054 case CXCursor_ClassDecl:
3055 return createCXString("ClassDecl");
3056 case CXCursor_FieldDecl:
3057 return createCXString("FieldDecl");
3058 case CXCursor_VarDecl:
3059 return createCXString("VarDecl");
3060 case CXCursor_ParmDecl:
3061 return createCXString("ParmDecl");
3062 case CXCursor_ObjCInterfaceDecl:
3063 return createCXString("ObjCInterfaceDecl");
3064 case CXCursor_ObjCCategoryDecl:
3065 return createCXString("ObjCCategoryDecl");
3066 case CXCursor_ObjCProtocolDecl:
3067 return createCXString("ObjCProtocolDecl");
3068 case CXCursor_ObjCPropertyDecl:
3069 return createCXString("ObjCPropertyDecl");
3070 case CXCursor_ObjCIvarDecl:
3071 return createCXString("ObjCIvarDecl");
3072 case CXCursor_ObjCInstanceMethodDecl:
3073 return createCXString("ObjCInstanceMethodDecl");
3074 case CXCursor_ObjCClassMethodDecl:
3075 return createCXString("ObjCClassMethodDecl");
3076 case CXCursor_ObjCImplementationDecl:
3077 return createCXString("ObjCImplementationDecl");
3078 case CXCursor_ObjCCategoryImplDecl:
3079 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003080 case CXCursor_CXXMethod:
3081 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003082 case CXCursor_UnexposedDecl:
3083 return createCXString("UnexposedDecl");
3084 case CXCursor_ObjCSuperClassRef:
3085 return createCXString("ObjCSuperClassRef");
3086 case CXCursor_ObjCProtocolRef:
3087 return createCXString("ObjCProtocolRef");
3088 case CXCursor_ObjCClassRef:
3089 return createCXString("ObjCClassRef");
3090 case CXCursor_TypeRef:
3091 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003092 case CXCursor_TemplateRef:
3093 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003094 case CXCursor_NamespaceRef:
3095 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003096 case CXCursor_MemberRef:
3097 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003098 case CXCursor_LabelRef:
3099 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003100 case CXCursor_OverloadedDeclRef:
3101 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003102 case CXCursor_UnexposedExpr:
3103 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003104 case CXCursor_BlockExpr:
3105 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003106 case CXCursor_DeclRefExpr:
3107 return createCXString("DeclRefExpr");
3108 case CXCursor_MemberRefExpr:
3109 return createCXString("MemberRefExpr");
3110 case CXCursor_CallExpr:
3111 return createCXString("CallExpr");
3112 case CXCursor_ObjCMessageExpr:
3113 return createCXString("ObjCMessageExpr");
3114 case CXCursor_UnexposedStmt:
3115 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003116 case CXCursor_LabelStmt:
3117 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003118 case CXCursor_InvalidFile:
3119 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003120 case CXCursor_InvalidCode:
3121 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003122 case CXCursor_NoDeclFound:
3123 return createCXString("NoDeclFound");
3124 case CXCursor_NotImplemented:
3125 return createCXString("NotImplemented");
3126 case CXCursor_TranslationUnit:
3127 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003128 case CXCursor_UnexposedAttr:
3129 return createCXString("UnexposedAttr");
3130 case CXCursor_IBActionAttr:
3131 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003132 case CXCursor_IBOutletAttr:
3133 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003134 case CXCursor_IBOutletCollectionAttr:
3135 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003136 case CXCursor_PreprocessingDirective:
3137 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003138 case CXCursor_MacroDefinition:
3139 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003140 case CXCursor_MacroInstantiation:
3141 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003142 case CXCursor_InclusionDirective:
3143 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003144 case CXCursor_Namespace:
3145 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003146 case CXCursor_LinkageSpec:
3147 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003148 case CXCursor_CXXBaseSpecifier:
3149 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003150 case CXCursor_Constructor:
3151 return createCXString("CXXConstructor");
3152 case CXCursor_Destructor:
3153 return createCXString("CXXDestructor");
3154 case CXCursor_ConversionFunction:
3155 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003156 case CXCursor_TemplateTypeParameter:
3157 return createCXString("TemplateTypeParameter");
3158 case CXCursor_NonTypeTemplateParameter:
3159 return createCXString("NonTypeTemplateParameter");
3160 case CXCursor_TemplateTemplateParameter:
3161 return createCXString("TemplateTemplateParameter");
3162 case CXCursor_FunctionTemplate:
3163 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003164 case CXCursor_ClassTemplate:
3165 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003166 case CXCursor_ClassTemplatePartialSpecialization:
3167 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003168 case CXCursor_NamespaceAlias:
3169 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003170 case CXCursor_UsingDirective:
3171 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003172 case CXCursor_UsingDeclaration:
3173 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003174 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003175
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003176 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003177 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003178}
Steve Naroff89922f82009-08-31 00:59:03 +00003179
Ted Kremeneke68fff62010-02-17 00:41:32 +00003180enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3181 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003182 CXClientData client_data) {
3183 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003184
3185 // If our current best cursor is the construction of a temporary object,
3186 // don't replace that cursor with a type reference, because we want
3187 // clang_getCursor() to point at the constructor.
3188 if (clang_isExpression(BestCursor->kind) &&
3189 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3190 cursor.kind == CXCursor_TypeRef)
3191 return CXChildVisit_Recurse;
3192
Douglas Gregor85fe1562010-12-10 07:23:11 +00003193 // Don't override a preprocessing cursor with another preprocessing
3194 // cursor; we want the outermost preprocessing cursor.
3195 if (clang_isPreprocessing(cursor.kind) &&
3196 clang_isPreprocessing(BestCursor->kind))
3197 return CXChildVisit_Recurse;
3198
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003199 *BestCursor = cursor;
3200 return CXChildVisit_Recurse;
3201}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003202
Douglas Gregorb9790342010-01-22 21:44:22 +00003203CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3204 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003205 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003206
Ted Kremeneka60ed472010-11-16 08:15:36 +00003207 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003208 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3209
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003210 // Translate the given source location to make it point at the beginning of
3211 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003212 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003213
3214 // Guard against an invalid SourceLocation, or we may assert in one
3215 // of the following calls.
3216 if (SLoc.isInvalid())
3217 return clang_getNullCursor();
3218
Douglas Gregor40749ee2010-11-03 00:35:38 +00003219 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003220 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3221 CXXUnit->getASTContext().getLangOptions());
3222
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003223 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3224 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003225 // FIXME: Would be great to have a "hint" cursor, then walk from that
3226 // hint cursor upward until we find a cursor whose source range encloses
3227 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003228 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3229 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003230 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003231 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003232 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003233
3234 if (Logging) {
3235 CXFile SearchFile;
3236 unsigned SearchLine, SearchColumn;
3237 CXFile ResultFile;
3238 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003239 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3240 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003241 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3242
3243 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3244 0);
3245 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3246 &ResultColumn, 0);
3247 SearchFileName = clang_getFileName(SearchFile);
3248 ResultFileName = clang_getFileName(ResultFile);
3249 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003250 USR = clang_getCursorUSR(Result);
3251 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003252 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3253 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003254 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3255 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003256 clang_disposeString(SearchFileName);
3257 clang_disposeString(ResultFileName);
3258 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003259 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003260
3261 CXCursor Definition = clang_getCursorDefinition(Result);
3262 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3263 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3264 CXString DefinitionKindSpelling
3265 = clang_getCursorKindSpelling(Definition.kind);
3266 CXFile DefinitionFile;
3267 unsigned DefinitionLine, DefinitionColumn;
3268 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3269 &DefinitionLine, &DefinitionColumn, 0);
3270 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3271 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3272 clang_getCString(DefinitionKindSpelling),
3273 clang_getCString(DefinitionFileName),
3274 DefinitionLine, DefinitionColumn);
3275 clang_disposeString(DefinitionFileName);
3276 clang_disposeString(DefinitionKindSpelling);
3277 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003278 }
3279
Ted Kremeneke68fff62010-02-17 00:41:32 +00003280 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003281}
3282
Ted Kremenek73885552009-11-17 19:28:59 +00003283CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003284 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003285}
3286
3287unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003288 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003289}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003290
Douglas Gregor9ce55842010-11-20 00:09:34 +00003291unsigned clang_hashCursor(CXCursor C) {
3292 unsigned Index = 0;
3293 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3294 Index = 1;
3295
3296 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3297 std::make_pair(C.kind, C.data[Index]));
3298}
3299
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003300unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003301 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3302}
3303
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003304unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003305 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3306}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003307
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003308unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003309 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3310}
3311
Douglas Gregor97b98722010-01-19 23:20:36 +00003312unsigned clang_isExpression(enum CXCursorKind K) {
3313 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3314}
3315
3316unsigned clang_isStatement(enum CXCursorKind K) {
3317 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3318}
3319
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003320unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3321 return K == CXCursor_TranslationUnit;
3322}
3323
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003324unsigned clang_isPreprocessing(enum CXCursorKind K) {
3325 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3326}
3327
Ted Kremenekad6eff62010-03-08 21:17:29 +00003328unsigned clang_isUnexposed(enum CXCursorKind K) {
3329 switch (K) {
3330 case CXCursor_UnexposedDecl:
3331 case CXCursor_UnexposedExpr:
3332 case CXCursor_UnexposedStmt:
3333 case CXCursor_UnexposedAttr:
3334 return true;
3335 default:
3336 return false;
3337 }
3338}
3339
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003340CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003341 return C.kind;
3342}
3343
Douglas Gregor98258af2010-01-18 22:46:11 +00003344CXSourceLocation clang_getCursorLocation(CXCursor C) {
3345 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003346 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003347 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003348 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3349 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003350 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003351 }
3352
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003353 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003354 std::pair<ObjCProtocolDecl *, SourceLocation> P
3355 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003356 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003357 }
3358
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003359 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003360 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3361 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003362 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003363 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003364
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003365 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003366 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003367 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003368 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003369
3370 case CXCursor_TemplateRef: {
3371 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3372 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3373 }
3374
Douglas Gregor69319002010-08-31 23:48:11 +00003375 case CXCursor_NamespaceRef: {
3376 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3377 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3378 }
3379
Douglas Gregora67e03f2010-09-09 21:42:20 +00003380 case CXCursor_MemberRef: {
3381 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3382 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3383 }
3384
Ted Kremenek3064ef92010-08-27 21:34:58 +00003385 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003386 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3387 if (!BaseSpec)
3388 return clang_getNullLocation();
3389
3390 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3391 return cxloc::translateSourceLocation(getCursorContext(C),
3392 TSInfo->getTypeLoc().getBeginLoc());
3393
3394 return cxloc::translateSourceLocation(getCursorContext(C),
3395 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003396 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003397
Douglas Gregor36897b02010-09-10 00:22:18 +00003398 case CXCursor_LabelRef: {
3399 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3400 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3401 }
3402
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003403 case CXCursor_OverloadedDeclRef:
3404 return cxloc::translateSourceLocation(getCursorContext(C),
3405 getCursorOverloadedDeclRef(C).second);
3406
Douglas Gregorf46034a2010-01-18 23:41:10 +00003407 default:
3408 // FIXME: Need a way to enumerate all non-reference cases.
3409 llvm_unreachable("Missed a reference kind");
3410 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003411 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003412
3413 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003414 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003415 getLocationFromExpr(getCursorExpr(C)));
3416
Douglas Gregor36897b02010-09-10 00:22:18 +00003417 if (clang_isStatement(C.kind))
3418 return cxloc::translateSourceLocation(getCursorContext(C),
3419 getCursorStmt(C)->getLocStart());
3420
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003421 if (C.kind == CXCursor_PreprocessingDirective) {
3422 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3423 return cxloc::translateSourceLocation(getCursorContext(C), L);
3424 }
Douglas Gregor48072312010-03-18 15:23:44 +00003425
3426 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003427 SourceLocation L
3428 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003429 return cxloc::translateSourceLocation(getCursorContext(C), L);
3430 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003431
3432 if (C.kind == CXCursor_MacroDefinition) {
3433 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3434 return cxloc::translateSourceLocation(getCursorContext(C), L);
3435 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003436
3437 if (C.kind == CXCursor_InclusionDirective) {
3438 SourceLocation L
3439 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3440 return cxloc::translateSourceLocation(getCursorContext(C), L);
3441 }
3442
Ted Kremenek9a700d22010-05-12 06:16:13 +00003443 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003444 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003445
Douglas Gregorf46034a2010-01-18 23:41:10 +00003446 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003447 SourceLocation Loc = D->getLocation();
3448 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3449 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003450 // FIXME: Multiple variables declared in a single declaration
3451 // currently lack the information needed to correctly determine their
3452 // ranges when accounting for the type-specifier. We use context
3453 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3454 // and if so, whether it is the first decl.
3455 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3456 if (!cxcursor::isFirstInDeclGroup(C))
3457 Loc = VD->getLocation();
3458 }
3459
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003460 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003461}
Douglas Gregora7bde202010-01-19 00:34:46 +00003462
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003463} // end extern "C"
3464
3465static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003466 if (clang_isReference(C.kind)) {
3467 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003468 case CXCursor_ObjCSuperClassRef:
3469 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003470
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003471 case CXCursor_ObjCProtocolRef:
3472 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003473
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003474 case CXCursor_ObjCClassRef:
3475 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003476
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003477 case CXCursor_TypeRef:
3478 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003479
3480 case CXCursor_TemplateRef:
3481 return getCursorTemplateRef(C).second;
3482
Douglas Gregor69319002010-08-31 23:48:11 +00003483 case CXCursor_NamespaceRef:
3484 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003485
3486 case CXCursor_MemberRef:
3487 return getCursorMemberRef(C).second;
3488
Ted Kremenek3064ef92010-08-27 21:34:58 +00003489 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003490 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003491
Douglas Gregor36897b02010-09-10 00:22:18 +00003492 case CXCursor_LabelRef:
3493 return getCursorLabelRef(C).second;
3494
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003495 case CXCursor_OverloadedDeclRef:
3496 return getCursorOverloadedDeclRef(C).second;
3497
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003498 default:
3499 // FIXME: Need a way to enumerate all non-reference cases.
3500 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003501 }
3502 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003503
3504 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003505 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003506
3507 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003508 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003509
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003510 if (C.kind == CXCursor_PreprocessingDirective)
3511 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003512
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003513 if (C.kind == CXCursor_MacroInstantiation)
3514 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003515
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003516 if (C.kind == CXCursor_MacroDefinition)
3517 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003518
3519 if (C.kind == CXCursor_InclusionDirective)
3520 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3521
Ted Kremenek007a7c92010-11-01 23:26:51 +00003522 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3523 Decl *D = cxcursor::getCursorDecl(C);
3524 SourceRange R = D->getSourceRange();
3525 // FIXME: Multiple variables declared in a single declaration
3526 // currently lack the information needed to correctly determine their
3527 // ranges when accounting for the type-specifier. We use context
3528 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3529 // and if so, whether it is the first decl.
3530 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3531 if (!cxcursor::isFirstInDeclGroup(C))
3532 R.setBegin(VD->getLocation());
3533 }
3534 return R;
3535 }
Douglas Gregor66537982010-11-17 17:14:07 +00003536 return SourceRange();
3537}
3538
3539/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3540/// the decl-specifier-seq for declarations.
3541static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3542 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3543 Decl *D = cxcursor::getCursorDecl(C);
3544 SourceRange R = D->getSourceRange();
3545
3546 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3547 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3548 TypeLoc TL = TI->getTypeLoc();
3549 SourceLocation TLoc = TL.getSourceRange().getBegin();
3550 if (TLoc.isValid() && R.getBegin().isValid() &&
3551 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3552 R.setBegin(TLoc);
3553 }
3554
3555 // FIXME: Multiple variables declared in a single declaration
3556 // currently lack the information needed to correctly determine their
3557 // ranges when accounting for the type-specifier. We use context
3558 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3559 // and if so, whether it is the first decl.
3560 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3561 if (!cxcursor::isFirstInDeclGroup(C))
3562 R.setBegin(VD->getLocation());
3563 }
3564 }
3565
3566 return R;
3567 }
3568
3569 return getRawCursorExtent(C);
3570}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003571
3572extern "C" {
3573
3574CXSourceRange clang_getCursorExtent(CXCursor C) {
3575 SourceRange R = getRawCursorExtent(C);
3576 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003577 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003578
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003579 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003580}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003581
3582CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003583 if (clang_isInvalid(C.kind))
3584 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585
Ted Kremeneka60ed472010-11-16 08:15:36 +00003586 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003587 if (clang_isDeclaration(C.kind)) {
3588 Decl *D = getCursorDecl(C);
3589 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003590 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003591 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003592 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003593 if (ObjCForwardProtocolDecl *Protocols
3594 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003595 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003596 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3597 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3598 return MakeCXCursor(Property, tu);
3599
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003600 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003601 }
3602
Douglas Gregor97b98722010-01-19 23:20:36 +00003603 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003604 Expr *E = getCursorExpr(C);
3605 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003606 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003607 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003608
3609 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003610 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003611
Douglas Gregor97b98722010-01-19 23:20:36 +00003612 return clang_getNullCursor();
3613 }
3614
Douglas Gregor36897b02010-09-10 00:22:18 +00003615 if (clang_isStatement(C.kind)) {
3616 Stmt *S = getCursorStmt(C);
3617 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003618 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003619
3620 return clang_getNullCursor();
3621 }
3622
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003623 if (C.kind == CXCursor_MacroInstantiation) {
3624 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003625 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003626 }
3627
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003628 if (!clang_isReference(C.kind))
3629 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003630
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003631 switch (C.kind) {
3632 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003633 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003634
3635 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003636 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003637
3638 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003639 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003640
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003641 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003642 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003643
3644 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003645 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003646
Douglas Gregor69319002010-08-31 23:48:11 +00003647 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003648 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003649
Douglas Gregora67e03f2010-09-09 21:42:20 +00003650 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003651 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003652
Ted Kremenek3064ef92010-08-27 21:34:58 +00003653 case CXCursor_CXXBaseSpecifier: {
3654 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3655 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003656 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003657 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003658
Douglas Gregor36897b02010-09-10 00:22:18 +00003659 case CXCursor_LabelRef:
3660 // FIXME: We end up faking the "parent" declaration here because we
3661 // don't want to make CXCursor larger.
3662 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003663 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3664 .getTranslationUnitDecl(),
3665 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003666
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003667 case CXCursor_OverloadedDeclRef:
3668 return C;
3669
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003670 default:
3671 // We would prefer to enumerate all non-reference cursor kinds here.
3672 llvm_unreachable("Unhandled reference cursor kind");
3673 break;
3674 }
3675 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003676
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003677 return clang_getNullCursor();
3678}
3679
Douglas Gregorb6998662010-01-19 19:34:47 +00003680CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003681 if (clang_isInvalid(C.kind))
3682 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003683
Ted Kremeneka60ed472010-11-16 08:15:36 +00003684 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003685
Douglas Gregorb6998662010-01-19 19:34:47 +00003686 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003687 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003688 C = clang_getCursorReferenced(C);
3689 WasReference = true;
3690 }
3691
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003692 if (C.kind == CXCursor_MacroInstantiation)
3693 return clang_getCursorReferenced(C);
3694
Douglas Gregorb6998662010-01-19 19:34:47 +00003695 if (!clang_isDeclaration(C.kind))
3696 return clang_getNullCursor();
3697
3698 Decl *D = getCursorDecl(C);
3699 if (!D)
3700 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003701
Douglas Gregorb6998662010-01-19 19:34:47 +00003702 switch (D->getKind()) {
3703 // Declaration kinds that don't really separate the notions of
3704 // declaration and definition.
3705 case Decl::Namespace:
3706 case Decl::Typedef:
3707 case Decl::TemplateTypeParm:
3708 case Decl::EnumConstant:
3709 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003710 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003711 case Decl::ObjCIvar:
3712 case Decl::ObjCAtDefsField:
3713 case Decl::ImplicitParam:
3714 case Decl::ParmVar:
3715 case Decl::NonTypeTemplateParm:
3716 case Decl::TemplateTemplateParm:
3717 case Decl::ObjCCategoryImpl:
3718 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003719 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003720 case Decl::LinkageSpec:
3721 case Decl::ObjCPropertyImpl:
3722 case Decl::FileScopeAsm:
3723 case Decl::StaticAssert:
3724 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003725 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003726 return C;
3727
3728 // Declaration kinds that don't make any sense here, but are
3729 // nonetheless harmless.
3730 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003731 break;
3732
3733 // Declaration kinds for which the definition is not resolvable.
3734 case Decl::UnresolvedUsingTypename:
3735 case Decl::UnresolvedUsingValue:
3736 break;
3737
3738 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003739 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003740 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003741
3742 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003743 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003744
3745 case Decl::Enum:
3746 case Decl::Record:
3747 case Decl::CXXRecord:
3748 case Decl::ClassTemplateSpecialization:
3749 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003750 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003751 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003752 return clang_getNullCursor();
3753
3754 case Decl::Function:
3755 case Decl::CXXMethod:
3756 case Decl::CXXConstructor:
3757 case Decl::CXXDestructor:
3758 case Decl::CXXConversion: {
3759 const FunctionDecl *Def = 0;
3760 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003761 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003762 return clang_getNullCursor();
3763 }
3764
3765 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003766 // Ask the variable if it has a definition.
3767 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003768 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003769 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003770 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003771
Douglas Gregorb6998662010-01-19 19:34:47 +00003772 case Decl::FunctionTemplate: {
3773 const FunctionDecl *Def = 0;
3774 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003775 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003776 return clang_getNullCursor();
3777 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003778
Douglas Gregorb6998662010-01-19 19:34:47 +00003779 case Decl::ClassTemplate: {
3780 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003781 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003782 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003783 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003784 return clang_getNullCursor();
3785 }
3786
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003787 case Decl::Using:
3788 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003789 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003790
3791 case Decl::UsingShadow:
3792 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003793 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003794 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003795
3796 case Decl::ObjCMethod: {
3797 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3798 if (Method->isThisDeclarationADefinition())
3799 return C;
3800
3801 // Dig out the method definition in the associated
3802 // @implementation, if we have it.
3803 // FIXME: The ASTs should make finding the definition easier.
3804 if (ObjCInterfaceDecl *Class
3805 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3806 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3807 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3808 Method->isInstanceMethod()))
3809 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003810 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003811
3812 return clang_getNullCursor();
3813 }
3814
3815 case Decl::ObjCCategory:
3816 if (ObjCCategoryImplDecl *Impl
3817 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003818 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003819 return clang_getNullCursor();
3820
3821 case Decl::ObjCProtocol:
3822 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3823 return C;
3824 return clang_getNullCursor();
3825
3826 case Decl::ObjCInterface:
3827 // There are two notions of a "definition" for an Objective-C
3828 // class: the interface and its implementation. When we resolved a
3829 // reference to an Objective-C class, produce the @interface as
3830 // the definition; when we were provided with the interface,
3831 // produce the @implementation as the definition.
3832 if (WasReference) {
3833 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3834 return C;
3835 } else if (ObjCImplementationDecl *Impl
3836 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003837 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003838 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003839
Douglas Gregorb6998662010-01-19 19:34:47 +00003840 case Decl::ObjCProperty:
3841 // FIXME: We don't really know where to find the
3842 // ObjCPropertyImplDecls that implement this property.
3843 return clang_getNullCursor();
3844
3845 case Decl::ObjCCompatibleAlias:
3846 if (ObjCInterfaceDecl *Class
3847 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3848 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003849 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003850
Douglas Gregorb6998662010-01-19 19:34:47 +00003851 return clang_getNullCursor();
3852
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003853 case Decl::ObjCForwardProtocol:
3854 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003855 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003856
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003857 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003858 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003859 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003860
3861 case Decl::Friend:
3862 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003863 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003864 return clang_getNullCursor();
3865
3866 case Decl::FriendTemplate:
3867 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003868 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003869 return clang_getNullCursor();
3870 }
3871
3872 return clang_getNullCursor();
3873}
3874
3875unsigned clang_isCursorDefinition(CXCursor C) {
3876 if (!clang_isDeclaration(C.kind))
3877 return 0;
3878
3879 return clang_getCursorDefinition(C) == C;
3880}
3881
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003882CXCursor clang_getCanonicalCursor(CXCursor C) {
3883 if (!clang_isDeclaration(C.kind))
3884 return C;
3885
3886 if (Decl *D = getCursorDecl(C))
3887 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3888
3889 return C;
3890}
3891
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003892unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003893 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003894 return 0;
3895
3896 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3897 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3898 return E->getNumDecls();
3899
3900 if (OverloadedTemplateStorage *S
3901 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3902 return S->size();
3903
3904 Decl *D = Storage.get<Decl*>();
3905 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003906 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003907 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3908 return Classes->size();
3909 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3910 return Protocols->protocol_size();
3911
3912 return 0;
3913}
3914
3915CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003916 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003917 return clang_getNullCursor();
3918
3919 if (index >= clang_getNumOverloadedDecls(cursor))
3920 return clang_getNullCursor();
3921
Ted Kremeneka60ed472010-11-16 08:15:36 +00003922 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003923 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3924 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003925 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003926
3927 if (OverloadedTemplateStorage *S
3928 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003929 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003930
3931 Decl *D = Storage.get<Decl*>();
3932 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3933 // FIXME: This is, unfortunately, linear time.
3934 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3935 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003936 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003937 }
3938
3939 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003940 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003941
3942 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003943 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003944
3945 return clang_getNullCursor();
3946}
3947
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003948void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003949 const char **startBuf,
3950 const char **endBuf,
3951 unsigned *startLine,
3952 unsigned *startColumn,
3953 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003954 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003955 assert(getCursorDecl(C) && "CXCursor has null decl");
3956 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003957 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3958 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003959
Steve Naroff4ade6d62009-09-23 17:52:52 +00003960 SourceManager &SM = FD->getASTContext().getSourceManager();
3961 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3962 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3963 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3964 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3965 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3966 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3967}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003968
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003969void clang_enableStackTraces(void) {
3970 llvm::sys::PrintStackTraceOnErrorSignal();
3971}
3972
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003973void clang_executeOnThread(void (*fn)(void*), void *user_data,
3974 unsigned stack_size) {
3975 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3976}
3977
Ted Kremenekfb480492010-01-13 21:46:36 +00003978} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003979
Ted Kremenekfb480492010-01-13 21:46:36 +00003980//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003981// Token-based Operations.
3982//===----------------------------------------------------------------------===//
3983
3984/* CXToken layout:
3985 * int_data[0]: a CXTokenKind
3986 * int_data[1]: starting token location
3987 * int_data[2]: token length
3988 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003989 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003990 * otherwise unused.
3991 */
3992extern "C" {
3993
3994CXTokenKind clang_getTokenKind(CXToken CXTok) {
3995 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3996}
3997
3998CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3999 switch (clang_getTokenKind(CXTok)) {
4000 case CXToken_Identifier:
4001 case CXToken_Keyword:
4002 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004003 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4004 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004005
4006 case CXToken_Literal: {
4007 // We have stashed the starting pointer in the ptr_data field. Use it.
4008 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004009 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004010 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004011
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004012 case CXToken_Punctuation:
4013 case CXToken_Comment:
4014 break;
4015 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004016
4017 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004018 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004019 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004020 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004021 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004022
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004023 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4024 std::pair<FileID, unsigned> LocInfo
4025 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004026 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004027 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004028 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4029 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004030 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004031
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004032 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004033}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004034
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004035CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004036 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004037 if (!CXXUnit)
4038 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004039
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004040 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4041 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4042}
4043
4044CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004045 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004046 if (!CXXUnit)
4047 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004048
4049 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004050 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4051}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004052
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004053void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4054 CXToken **Tokens, unsigned *NumTokens) {
4055 if (Tokens)
4056 *Tokens = 0;
4057 if (NumTokens)
4058 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004059
Ted Kremeneka60ed472010-11-16 08:15:36 +00004060 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004061 if (!CXXUnit || !Tokens || !NumTokens)
4062 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004063
Douglas Gregorbdf60622010-03-05 21:16:25 +00004064 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4065
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004066 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004067 if (R.isInvalid())
4068 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004069
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004070 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4071 std::pair<FileID, unsigned> BeginLocInfo
4072 = SourceMgr.getDecomposedLoc(R.getBegin());
4073 std::pair<FileID, unsigned> EndLocInfo
4074 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004075
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004076 // Cannot tokenize across files.
4077 if (BeginLocInfo.first != EndLocInfo.first)
4078 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004079
4080 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004081 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004082 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004083 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004084 if (Invalid)
4085 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004086
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004087 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4088 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004089 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004090 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004091
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004092 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004093 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004094 llvm::SmallVector<CXToken, 32> CXTokens;
4095 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004096 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004097 do {
4098 // Lex the next token
4099 Lex.LexFromRawLexer(Tok);
4100 if (Tok.is(tok::eof))
4101 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004102
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004103 // Initialize the CXToken.
4104 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004105
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004106 // - Common fields
4107 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4108 CXTok.int_data[2] = Tok.getLength();
4109 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004110
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004111 // - Kind-specific fields
4112 if (Tok.isLiteral()) {
4113 CXTok.int_data[0] = CXToken_Literal;
4114 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004115 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004116 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004117 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004118 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004119
David Chisnall096428b2010-10-13 21:44:48 +00004120 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004121 CXTok.int_data[0] = CXToken_Keyword;
4122 }
4123 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004124 CXTok.int_data[0] = Tok.is(tok::identifier)
4125 ? CXToken_Identifier
4126 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004127 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004128 CXTok.ptr_data = II;
4129 } else if (Tok.is(tok::comment)) {
4130 CXTok.int_data[0] = CXToken_Comment;
4131 CXTok.ptr_data = 0;
4132 } else {
4133 CXTok.int_data[0] = CXToken_Punctuation;
4134 CXTok.ptr_data = 0;
4135 }
4136 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004137 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004138 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004139
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004140 if (CXTokens.empty())
4141 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004142
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004143 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4144 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4145 *NumTokens = CXTokens.size();
4146}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004147
Ted Kremenek6db61092010-05-05 00:55:15 +00004148void clang_disposeTokens(CXTranslationUnit TU,
4149 CXToken *Tokens, unsigned NumTokens) {
4150 free(Tokens);
4151}
4152
4153} // end: extern "C"
4154
4155//===----------------------------------------------------------------------===//
4156// Token annotation APIs.
4157//===----------------------------------------------------------------------===//
4158
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004159typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004160static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4161 CXCursor parent,
4162 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004163namespace {
4164class AnnotateTokensWorker {
4165 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004166 CXToken *Tokens;
4167 CXCursor *Cursors;
4168 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004169 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004170 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004171 CursorVisitor AnnotateVis;
4172 SourceManager &SrcMgr;
4173
4174 bool MoreTokens() const { return TokIdx < NumTokens; }
4175 unsigned NextToken() const { return TokIdx; }
4176 void AdvanceToken() { ++TokIdx; }
4177 SourceLocation GetTokenLoc(unsigned tokI) {
4178 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4179 }
4180
Ted Kremenek6db61092010-05-05 00:55:15 +00004181public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004182 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004183 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004184 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004185 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004186 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004187 AnnotateVis(tu,
4188 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004189 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004190 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004191
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004192 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004193 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004194 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004195 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004196 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004197 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004198};
4199}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004200
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004201void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4202 // Walk the AST within the region of interest, annotating tokens
4203 // along the way.
4204 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004205
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004206 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4207 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004208 if (Pos != Annotated.end() &&
4209 (clang_isInvalid(Cursors[I].kind) ||
4210 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004211 Cursors[I] = Pos->second;
4212 }
4213
4214 // Finish up annotating any tokens left.
4215 if (!MoreTokens())
4216 return;
4217
4218 const CXCursor &C = clang_getNullCursor();
4219 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4220 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4221 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004222 }
4223}
4224
Ted Kremenek6db61092010-05-05 00:55:15 +00004225enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004226AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004228 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004229 if (cursorRange.isInvalid())
4230 return CXChildVisit_Recurse;
4231
Douglas Gregor4419b672010-10-21 06:10:04 +00004232 if (clang_isPreprocessing(cursor.kind)) {
4233 // For macro instantiations, just note where the beginning of the macro
4234 // instantiation occurs.
4235 if (cursor.kind == CXCursor_MacroInstantiation) {
4236 Annotated[Loc.int_data] = cursor;
4237 return CXChildVisit_Recurse;
4238 }
4239
Douglas Gregor4419b672010-10-21 06:10:04 +00004240 // Items in the preprocessing record are kept separate from items in
4241 // declarations, so we keep a separate token index.
4242 unsigned SavedTokIdx = TokIdx;
4243 TokIdx = PreprocessingTokIdx;
4244
4245 // Skip tokens up until we catch up to the beginning of the preprocessing
4246 // entry.
4247 while (MoreTokens()) {
4248 const unsigned I = NextToken();
4249 SourceLocation TokLoc = GetTokenLoc(I);
4250 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4251 case RangeBefore:
4252 AdvanceToken();
4253 continue;
4254 case RangeAfter:
4255 case RangeOverlap:
4256 break;
4257 }
4258 break;
4259 }
4260
4261 // Look at all of the tokens within this range.
4262 while (MoreTokens()) {
4263 const unsigned I = NextToken();
4264 SourceLocation TokLoc = GetTokenLoc(I);
4265 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4266 case RangeBefore:
4267 assert(0 && "Infeasible");
4268 case RangeAfter:
4269 break;
4270 case RangeOverlap:
4271 Cursors[I] = cursor;
4272 AdvanceToken();
4273 continue;
4274 }
4275 break;
4276 }
4277
4278 // Save the preprocessing token index; restore the non-preprocessing
4279 // token index.
4280 PreprocessingTokIdx = TokIdx;
4281 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004282 return CXChildVisit_Recurse;
4283 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004284
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285 if (cursorRange.isInvalid())
4286 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004287
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004288 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4289
Ted Kremeneka333c662010-05-12 05:29:33 +00004290 // Adjust the annotated range based specific declarations.
4291 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4292 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004293 Decl *D = cxcursor::getCursorDecl(cursor);
4294 // Don't visit synthesized ObjC methods, since they have no syntatic
4295 // representation in the source.
4296 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4297 if (MD->isSynthesized())
4298 return CXChildVisit_Continue;
4299 }
4300 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004301 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4302 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004303 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004304 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004305 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004306 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004307 }
4308 }
4309 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004310
Ted Kremenek3f404602010-08-14 01:14:06 +00004311 // If the location of the cursor occurs within a macro instantiation, record
4312 // the spelling location of the cursor in our annotation map. We can then
4313 // paper over the token labelings during a post-processing step to try and
4314 // get cursor mappings for tokens that are the *arguments* of a macro
4315 // instantiation.
4316 if (L.isMacroID()) {
4317 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4318 // Only invalidate the old annotation if it isn't part of a preprocessing
4319 // directive. Here we assume that the default construction of CXCursor
4320 // results in CXCursor.kind being an initialized value (i.e., 0). If
4321 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004322
Ted Kremenek3f404602010-08-14 01:14:06 +00004323 CXCursor &oldC = Annotated[rawEncoding];
4324 if (!clang_isPreprocessing(oldC.kind))
4325 oldC = cursor;
4326 }
4327
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004328 const enum CXCursorKind K = clang_getCursorKind(parent);
4329 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004330 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4331 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004332
4333 while (MoreTokens()) {
4334 const unsigned I = NextToken();
4335 SourceLocation TokLoc = GetTokenLoc(I);
4336 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4337 case RangeBefore:
4338 Cursors[I] = updateC;
4339 AdvanceToken();
4340 continue;
4341 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004342 case RangeOverlap:
4343 break;
4344 }
4345 break;
4346 }
4347
4348 // Visit children to get their cursor information.
4349 const unsigned BeforeChildren = NextToken();
4350 VisitChildren(cursor);
4351 const unsigned AfterChildren = NextToken();
4352
4353 // Adjust 'Last' to the last token within the extent of the cursor.
4354 while (MoreTokens()) {
4355 const unsigned I = NextToken();
4356 SourceLocation TokLoc = GetTokenLoc(I);
4357 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4358 case RangeBefore:
4359 assert(0 && "Infeasible");
4360 case RangeAfter:
4361 break;
4362 case RangeOverlap:
4363 Cursors[I] = updateC;
4364 AdvanceToken();
4365 continue;
4366 }
4367 break;
4368 }
4369 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004370
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004371 // Scan the tokens that are at the beginning of the cursor, but are not
4372 // capture by the child cursors.
4373
4374 // For AST elements within macros, rely on a post-annotate pass to
4375 // to correctly annotate the tokens with cursors. Otherwise we can
4376 // get confusing results of having tokens that map to cursors that really
4377 // are expanded by an instantiation.
4378 if (L.isMacroID())
4379 cursor = clang_getNullCursor();
4380
4381 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4382 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4383 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004384
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004385 Cursors[I] = cursor;
4386 }
4387 // Scan the tokens that are at the end of the cursor, but are not captured
4388 // but the child cursors.
4389 for (unsigned I = AfterChildren; I != Last; ++I)
4390 Cursors[I] = cursor;
4391
4392 TokIdx = Last;
4393 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004394}
4395
Ted Kremenek6db61092010-05-05 00:55:15 +00004396static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4397 CXCursor parent,
4398 CXClientData client_data) {
4399 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4400}
4401
Ted Kremenekab979612010-11-11 08:05:23 +00004402// This gets run a separate thread to avoid stack blowout.
4403static void runAnnotateTokensWorker(void *UserData) {
4404 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4405}
4406
Ted Kremenek6db61092010-05-05 00:55:15 +00004407extern "C" {
4408
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004409void clang_annotateTokens(CXTranslationUnit TU,
4410 CXToken *Tokens, unsigned NumTokens,
4411 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004412
4413 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004414 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004415
Douglas Gregor4419b672010-10-21 06:10:04 +00004416 // Any token we don't specifically annotate will have a NULL cursor.
4417 CXCursor C = clang_getNullCursor();
4418 for (unsigned I = 0; I != NumTokens; ++I)
4419 Cursors[I] = C;
4420
Ted Kremeneka60ed472010-11-16 08:15:36 +00004421 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004422 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004423 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004424
Douglas Gregorbdf60622010-03-05 21:16:25 +00004425 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004426
Douglas Gregor0396f462010-03-19 05:22:59 +00004427 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004428 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004429 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4430 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004431 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4432 clang_getTokenLocation(TU,
4433 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004434
Douglas Gregor0396f462010-03-19 05:22:59 +00004435 // A mapping from the source locations found when re-lexing or traversing the
4436 // region of interest to the corresponding cursors.
4437 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004438
4439 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004440 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004441 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4442 std::pair<FileID, unsigned> BeginLocInfo
4443 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4444 std::pair<FileID, unsigned> EndLocInfo
4445 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004446
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004447 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004448 bool Invalid = false;
4449 if (BeginLocInfo.first == EndLocInfo.first &&
4450 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4451 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004452 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4453 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004454 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004455 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004456 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004457
4458 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004459 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004460 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004461 Token Tok;
4462 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004463
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004464 reprocess:
4465 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4466 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004467 // don't see it while preprocessing these tokens later, but keep track
4468 // of all of the token locations inside this preprocessing directive so
4469 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004470 //
4471 // FIXME: Some simple tests here could identify macro definitions and
4472 // #undefs, to provide specific cursor kinds for those.
4473 std::vector<SourceLocation> Locations;
4474 do {
4475 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004476 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004477 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004478
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004479 using namespace cxcursor;
4480 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004481 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4482 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004483 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004484 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4485 Annotated[Locations[I].getRawEncoding()] = Cursor;
4486 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004487
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004488 if (Tok.isAtStartOfLine())
4489 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004490
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004491 continue;
4492 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004493
Douglas Gregor48072312010-03-18 15:23:44 +00004494 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004495 break;
4496 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004497 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004498
Douglas Gregor0396f462010-03-19 05:22:59 +00004499 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004500 // a specific cursor.
4501 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004502 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004503
4504 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004505 // FIXME: We use a ridiculous stack size here because the data-recursion
4506 // algorithm uses a large stack frame than the non-data recursive version,
4507 // and AnnotationTokensWorker currently transforms the data-recursion
4508 // algorithm back into a traditional recursion by explicitly calling
4509 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004510 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004511 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4512 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004513 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4514 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004515}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004516} // end: extern "C"
4517
4518//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004519// Operations for querying linkage of a cursor.
4520//===----------------------------------------------------------------------===//
4521
4522extern "C" {
4523CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004524 if (!clang_isDeclaration(cursor.kind))
4525 return CXLinkage_Invalid;
4526
Ted Kremenek16b42592010-03-03 06:36:57 +00004527 Decl *D = cxcursor::getCursorDecl(cursor);
4528 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4529 switch (ND->getLinkage()) {
4530 case NoLinkage: return CXLinkage_NoLinkage;
4531 case InternalLinkage: return CXLinkage_Internal;
4532 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4533 case ExternalLinkage: return CXLinkage_External;
4534 };
4535
4536 return CXLinkage_Invalid;
4537}
4538} // end: extern "C"
4539
4540//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004541// Operations for querying language of a cursor.
4542//===----------------------------------------------------------------------===//
4543
4544static CXLanguageKind getDeclLanguage(const Decl *D) {
4545 switch (D->getKind()) {
4546 default:
4547 break;
4548 case Decl::ImplicitParam:
4549 case Decl::ObjCAtDefsField:
4550 case Decl::ObjCCategory:
4551 case Decl::ObjCCategoryImpl:
4552 case Decl::ObjCClass:
4553 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004554 case Decl::ObjCForwardProtocol:
4555 case Decl::ObjCImplementation:
4556 case Decl::ObjCInterface:
4557 case Decl::ObjCIvar:
4558 case Decl::ObjCMethod:
4559 case Decl::ObjCProperty:
4560 case Decl::ObjCPropertyImpl:
4561 case Decl::ObjCProtocol:
4562 return CXLanguage_ObjC;
4563 case Decl::CXXConstructor:
4564 case Decl::CXXConversion:
4565 case Decl::CXXDestructor:
4566 case Decl::CXXMethod:
4567 case Decl::CXXRecord:
4568 case Decl::ClassTemplate:
4569 case Decl::ClassTemplatePartialSpecialization:
4570 case Decl::ClassTemplateSpecialization:
4571 case Decl::Friend:
4572 case Decl::FriendTemplate:
4573 case Decl::FunctionTemplate:
4574 case Decl::LinkageSpec:
4575 case Decl::Namespace:
4576 case Decl::NamespaceAlias:
4577 case Decl::NonTypeTemplateParm:
4578 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004579 case Decl::TemplateTemplateParm:
4580 case Decl::TemplateTypeParm:
4581 case Decl::UnresolvedUsingTypename:
4582 case Decl::UnresolvedUsingValue:
4583 case Decl::Using:
4584 case Decl::UsingDirective:
4585 case Decl::UsingShadow:
4586 return CXLanguage_CPlusPlus;
4587 }
4588
4589 return CXLanguage_C;
4590}
4591
4592extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004593
4594enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4595 if (clang_isDeclaration(cursor.kind))
4596 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4597 if (D->hasAttr<UnavailableAttr>() ||
4598 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4599 return CXAvailability_Available;
4600
4601 if (D->hasAttr<DeprecatedAttr>())
4602 return CXAvailability_Deprecated;
4603 }
4604
4605 return CXAvailability_Available;
4606}
4607
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004608CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4609 if (clang_isDeclaration(cursor.kind))
4610 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4611
4612 return CXLanguage_Invalid;
4613}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004614
4615 /// \brief If the given cursor is the "templated" declaration
4616 /// descibing a class or function template, return the class or
4617 /// function template.
4618static Decl *maybeGetTemplateCursor(Decl *D) {
4619 if (!D)
4620 return 0;
4621
4622 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4623 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4624 return FunTmpl;
4625
4626 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4627 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4628 return ClassTmpl;
4629
4630 return D;
4631}
4632
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004633CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4634 if (clang_isDeclaration(cursor.kind)) {
4635 if (Decl *D = getCursorDecl(cursor)) {
4636 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004637 if (!DC)
4638 return clang_getNullCursor();
4639
4640 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4641 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004642 }
4643 }
4644
4645 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4646 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004647 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004648 }
4649
4650 return clang_getNullCursor();
4651}
4652
4653CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4654 if (clang_isDeclaration(cursor.kind)) {
4655 if (Decl *D = getCursorDecl(cursor)) {
4656 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004657 if (!DC)
4658 return clang_getNullCursor();
4659
4660 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4661 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004662 }
4663 }
4664
4665 // FIXME: Note that we can't easily compute the lexical context of a
4666 // statement or expression, so we return nothing.
4667 return clang_getNullCursor();
4668}
4669
Douglas Gregor9f592342010-10-01 20:25:15 +00004670static void CollectOverriddenMethods(DeclContext *Ctx,
4671 ObjCMethodDecl *Method,
4672 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4673 if (!Ctx)
4674 return;
4675
4676 // If we have a class or category implementation, jump straight to the
4677 // interface.
4678 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4679 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4680
4681 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4682 if (!Container)
4683 return;
4684
4685 // Check whether we have a matching method at this level.
4686 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4687 Method->isInstanceMethod()))
4688 if (Method != Overridden) {
4689 // We found an override at this level; there is no need to look
4690 // into other protocols or categories.
4691 Methods.push_back(Overridden);
4692 return;
4693 }
4694
4695 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4696 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4697 PEnd = Protocol->protocol_end();
4698 P != PEnd; ++P)
4699 CollectOverriddenMethods(*P, Method, Methods);
4700 }
4701
4702 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4703 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4704 PEnd = Category->protocol_end();
4705 P != PEnd; ++P)
4706 CollectOverriddenMethods(*P, Method, Methods);
4707 }
4708
4709 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4710 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4711 PEnd = Interface->protocol_end();
4712 P != PEnd; ++P)
4713 CollectOverriddenMethods(*P, Method, Methods);
4714
4715 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4716 Category; Category = Category->getNextClassCategory())
4717 CollectOverriddenMethods(Category, Method, Methods);
4718
4719 // We only look into the superclass if we haven't found anything yet.
4720 if (Methods.empty())
4721 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4722 return CollectOverriddenMethods(Super, Method, Methods);
4723 }
4724}
4725
4726void clang_getOverriddenCursors(CXCursor cursor,
4727 CXCursor **overridden,
4728 unsigned *num_overridden) {
4729 if (overridden)
4730 *overridden = 0;
4731 if (num_overridden)
4732 *num_overridden = 0;
4733 if (!overridden || !num_overridden)
4734 return;
4735
4736 if (!clang_isDeclaration(cursor.kind))
4737 return;
4738
4739 Decl *D = getCursorDecl(cursor);
4740 if (!D)
4741 return;
4742
4743 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004744 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004745 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4746 *num_overridden = CXXMethod->size_overridden_methods();
4747 if (!*num_overridden)
4748 return;
4749
4750 *overridden = new CXCursor [*num_overridden];
4751 unsigned I = 0;
4752 for (CXXMethodDecl::method_iterator
4753 M = CXXMethod->begin_overridden_methods(),
4754 MEnd = CXXMethod->end_overridden_methods();
4755 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004756 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004757 return;
4758 }
4759
4760 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4761 if (!Method)
4762 return;
4763
4764 // Handle Objective-C methods.
4765 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4766 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4767
4768 if (Methods.empty())
4769 return;
4770
4771 *num_overridden = Methods.size();
4772 *overridden = new CXCursor [Methods.size()];
4773 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004774 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004775}
4776
4777void clang_disposeOverriddenCursors(CXCursor *overridden) {
4778 delete [] overridden;
4779}
4780
Douglas Gregorecdcb882010-10-20 22:00:55 +00004781CXFile clang_getIncludedFile(CXCursor cursor) {
4782 if (cursor.kind != CXCursor_InclusionDirective)
4783 return 0;
4784
4785 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4786 return (void *)ID->getFile();
4787}
4788
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004789} // end: extern "C"
4790
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004791
4792//===----------------------------------------------------------------------===//
4793// C++ AST instrospection.
4794//===----------------------------------------------------------------------===//
4795
4796extern "C" {
4797unsigned clang_CXXMethod_isStatic(CXCursor C) {
4798 if (!clang_isDeclaration(C.kind))
4799 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004800
4801 CXXMethodDecl *Method = 0;
4802 Decl *D = cxcursor::getCursorDecl(C);
4803 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4804 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4805 else
4806 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4807 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004808}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004809
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004810} // end: extern "C"
4811
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004812//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004813// Attribute introspection.
4814//===----------------------------------------------------------------------===//
4815
4816extern "C" {
4817CXType clang_getIBOutletCollectionType(CXCursor C) {
4818 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004819 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004820
4821 IBOutletCollectionAttr *A =
4822 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4823
Ted Kremeneka60ed472010-11-16 08:15:36 +00004824 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004825}
4826} // end: extern "C"
4827
4828//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004829// Misc. utility functions.
4830//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004831
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004832/// Default to using an 8 MB stack size on "safety" threads.
4833static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004834
4835namespace clang {
4836
4837bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004838 void (*Fn)(void*), void *UserData,
4839 unsigned Size) {
4840 if (!Size)
4841 Size = GetSafetyThreadStackSize();
4842 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004843 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4844 return CRC.RunSafely(Fn, UserData);
4845}
4846
4847unsigned GetSafetyThreadStackSize() {
4848 return SafetyStackThreadSize;
4849}
4850
4851void SetSafetyThreadStackSize(unsigned Value) {
4852 SafetyStackThreadSize = Value;
4853}
4854
4855}
4856
Ted Kremenek04bb7162010-01-22 22:44:15 +00004857extern "C" {
4858
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004859CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004860 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004861}
4862
4863} // end: extern "C"