blob: 425832596a95a37ece6fe6f449be433dabd3c8c0 [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
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000689 // Visit the nested-name-specifier, if present.
690 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
691 if (VisitNestedNameSpecifierLoc(QualifierLoc))
692 return true;
693
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000694 return false;
695}
696
Douglas Gregora67e03f2010-09-09 21:42:20 +0000697/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000698static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
699 CXXCtorInitializer const * const *X
700 = static_cast<CXXCtorInitializer const * const *>(Xp);
701 CXXCtorInitializer const * const *Y
702 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000703
704 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
705 return -1;
706 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
707 return 1;
708 else
709 return 0;
710}
711
Douglas Gregorb1373d02010-01-20 20:59:29 +0000712bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000713 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
714 // Visit the function declaration's syntactic components in the order
715 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000716 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000717 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
718
719 // If we have a function declared directly (without the use of a typedef),
720 // visit just the return type. Otherwise, just visit the function's type
721 // now.
722 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
723 (!FTL && Visit(TL)))
724 return true;
725
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000726 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000727 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
728 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000729 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000730
731 // Visit the declaration name.
732 if (VisitDeclarationNameInfo(ND->getNameInfo()))
733 return true;
734
735 // FIXME: Visit explicitly-specified template arguments!
736
737 // Visit the function parameters, if we have a function type.
738 if (FTL && VisitFunctionTypeLoc(*FTL, true))
739 return true;
740
741 // FIXME: Attributes?
742 }
743
Douglas Gregora67e03f2010-09-09 21:42:20 +0000744 if (ND->isThisDeclarationADefinition()) {
745 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
746 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000747 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000748 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
749 IEnd = Constructor->init_end();
750 I != IEnd; ++I) {
751 if (!(*I)->isWritten())
752 continue;
753
754 WrittenInits.push_back(*I);
755 }
756
757 // Sort the initializers in source order
758 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000759 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000760
761 // Visit the initializers in source order
762 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000763 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000764 if (Init->isAnyMemberInitializer()) {
765 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000766 Init->getMemberLocation(), TU)))
767 return true;
768 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
769 if (Visit(BaseInfo->getTypeLoc()))
770 return true;
771 }
772
773 // Visit the initializer value.
774 if (Expr *Initializer = Init->getInit())
775 if (Visit(MakeCXCursor(Initializer, ND, TU)))
776 return true;
777 }
778 }
779
780 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
781 return true;
782 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregorb1373d02010-01-20 20:59:29 +0000784 return false;
785}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
788 if (VisitDeclaratorDecl(D))
789 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000790
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000791 if (Expr *BitWidth = D->getBitWidth())
792 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000793
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000794 return false;
795}
796
797bool CursorVisitor::VisitVarDecl(VarDecl *D) {
798 if (VisitDeclaratorDecl(D))
799 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000800
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000801 if (Expr *Init = D->getInit())
802 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000803
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000804 return false;
805}
806
Douglas Gregor84b51d72010-09-01 20:16:53 +0000807bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
808 if (VisitDeclaratorDecl(D))
809 return true;
810
811 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
812 if (Expr *DefArg = D->getDefaultArgument())
813 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
814
815 return false;
816}
817
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000818bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
819 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
820 // before visiting these template parameters.
821 if (VisitTemplateParameters(D->getTemplateParameters()))
822 return true;
823
824 return VisitFunctionDecl(D->getTemplatedDecl());
825}
826
Douglas Gregor39d6f072010-08-31 19:02:00 +0000827bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
828 // FIXME: Visit the "outer" template parameter lists on the TagDecl
829 // before visiting these template parameters.
830 if (VisitTemplateParameters(D->getTemplateParameters()))
831 return true;
832
833 return VisitCXXRecordDecl(D->getTemplatedDecl());
834}
835
Douglas Gregor84b51d72010-09-01 20:16:53 +0000836bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
837 if (VisitTemplateParameters(D->getTemplateParameters()))
838 return true;
839
840 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
841 VisitTemplateArgumentLoc(D->getDefaultArgument()))
842 return true;
843
844 return false;
845}
846
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000847bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000848 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
849 if (Visit(TSInfo->getTypeLoc()))
850 return true;
851
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853 PEnd = ND->param_end();
854 P != PEnd; ++P) {
855 if (Visit(MakeCXCursor(*P, TU)))
856 return true;
857 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000858
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000859 if (ND->isThisDeclarationADefinition() &&
860 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
861 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000862
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000863 return false;
864}
865
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000866namespace {
867 struct ContainerDeclsSort {
868 SourceManager &SM;
869 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
870 bool operator()(Decl *A, Decl *B) {
871 SourceLocation L_A = A->getLocStart();
872 SourceLocation L_B = B->getLocStart();
873 assert(L_A.isValid() && L_B.isValid());
874 return SM.isBeforeInTranslationUnit(L_A, L_B);
875 }
876 };
877}
878
Douglas Gregora59e3902010-01-21 23:27:09 +0000879bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000880 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
881 // an @implementation can lexically contain Decls that are not properly
882 // nested in the AST. When we identify such cases, we need to retrofit
883 // this nesting here.
884 if (!DI_current)
885 return VisitDeclContext(D);
886
887 // Scan the Decls that immediately come after the container
888 // in the current DeclContext. If any fall within the
889 // container's lexical region, stash them into a vector
890 // for later processing.
891 llvm::SmallVector<Decl *, 24> DeclsInContainer;
892 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000893 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000894 if (EndLoc.isValid()) {
895 DeclContext::decl_iterator next = *DI_current;
896 while (++next != DE_current) {
897 Decl *D_next = *next;
898 if (!D_next)
899 break;
900 SourceLocation L = D_next->getLocStart();
901 if (!L.isValid())
902 break;
903 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
904 *DI_current = next;
905 DeclsInContainer.push_back(D_next);
906 continue;
907 }
908 break;
909 }
910 }
911
912 // The common case.
913 if (DeclsInContainer.empty())
914 return VisitDeclContext(D);
915
916 // Get all the Decls in the DeclContext, and sort them with the
917 // additional ones we've collected. Then visit them.
918 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
919 I!=E; ++I) {
920 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000921 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
922 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000923 continue;
924 DeclsInContainer.push_back(subDecl);
925 }
926
927 // Now sort the Decls so that they appear in lexical order.
928 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
929 ContainerDeclsSort(SM));
930
931 // Now visit the decls.
932 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
933 E = DeclsInContainer.end(); I != E; ++I) {
934 CXCursor Cursor = MakeCXCursor(*I, TU);
935 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
936 if (!V.hasValue())
937 continue;
938 if (!V.getValue())
939 return false;
940 if (Visit(Cursor, true))
941 return true;
942 }
943 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000944}
945
Douglas Gregorb1373d02010-01-20 20:59:29 +0000946bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000947 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
948 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000951 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
952 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
953 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000954 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000955 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000956
Douglas Gregora59e3902010-01-21 23:27:09 +0000957 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000958}
959
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000960bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
961 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
962 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
963 E = PID->protocol_end(); I != E; ++I, ++PL)
964 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
965 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000966
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000967 return VisitObjCContainerDecl(PID);
968}
969
Ted Kremenek23173d72010-05-18 21:09:07 +0000970bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000971 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000972 return true;
973
Ted Kremenek23173d72010-05-18 21:09:07 +0000974 // FIXME: This implements a workaround with @property declarations also being
975 // installed in the DeclContext for the @interface. Eventually this code
976 // should be removed.
977 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
978 if (!CDecl || !CDecl->IsClassExtension())
979 return false;
980
981 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
982 if (!ID)
983 return false;
984
985 IdentifierInfo *PropertyId = PD->getIdentifier();
986 ObjCPropertyDecl *prevDecl =
987 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
988
989 if (!prevDecl)
990 return false;
991
992 // Visit synthesized methods since they will be skipped when visiting
993 // the @interface.
994 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
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 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001000 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001001 if (Visit(MakeCXCursor(MD, TU)))
1002 return true;
1003
1004 return false;
1005}
1006
Douglas Gregorb1373d02010-01-20 20:59:29 +00001007bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001008 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009 if (D->getSuperClass() &&
1010 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001011 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001012 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001015 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1016 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1017 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001018 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001019 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001020
Douglas Gregora59e3902010-01-21 23:27:09 +00001021 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001022}
1023
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001024bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1025 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001026}
1027
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001029 // 'ID' could be null when dealing with invalid code.
1030 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1031 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1032 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001034 return VisitObjCImplDecl(D);
1035}
1036
1037bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1038#if 0
1039 // Issue callbacks for super class.
1040 // FIXME: No source location information!
1041 if (D->getSuperClass() &&
1042 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001044 TU)))
1045 return true;
1046#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001048 return VisitObjCImplDecl(D);
1049}
1050
1051bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1052 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1053 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1054 E = D->protocol_end();
1055 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001056 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001057 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001058
1059 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001060}
1061
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1063 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1064 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1065 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001066
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001067 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001068}
1069
Douglas Gregora4ffd852010-11-17 01:03:52 +00001070bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1071 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1072 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1073
1074 return false;
1075}
1076
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001077bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1078 return VisitDeclContext(D);
1079}
1080
Douglas Gregor69319002010-08-31 23:48:11 +00001081bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001082 // Visit nested-name-specifier.
1083 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1084 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1085 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001086
1087 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1088 D->getTargetNameLoc(), TU));
1089}
1090
Douglas Gregor7e242562010-09-01 19:52:22 +00001091bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001092 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001093 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1094 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001095 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001096 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001097
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001098 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1099 return true;
1100
Douglas Gregor7e242562010-09-01 19:52:22 +00001101 return VisitDeclarationNameInfo(D->getNameInfo());
1102}
1103
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001104bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105 // Visit nested-name-specifier.
1106 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1107 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1108 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001109
1110 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1111 D->getIdentLocation(), TU));
1112}
1113
Douglas Gregor7e242562010-09-01 19:52:22 +00001114bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001116 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1117 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001119 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120
Douglas Gregor7e242562010-09-01 19:52:22 +00001121 return VisitDeclarationNameInfo(D->getNameInfo());
1122}
1123
1124bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1125 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001126 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001127 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1128 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001129 return true;
1130
Douglas Gregor7e242562010-09-01 19:52:22 +00001131 return false;
1132}
1133
Douglas Gregor01829d32010-08-31 14:41:23 +00001134bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1135 switch (Name.getName().getNameKind()) {
1136 case clang::DeclarationName::Identifier:
1137 case clang::DeclarationName::CXXLiteralOperatorName:
1138 case clang::DeclarationName::CXXOperatorName:
1139 case clang::DeclarationName::CXXUsingDirective:
1140 return false;
1141
1142 case clang::DeclarationName::CXXConstructorName:
1143 case clang::DeclarationName::CXXDestructorName:
1144 case clang::DeclarationName::CXXConversionFunctionName:
1145 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1146 return Visit(TSInfo->getTypeLoc());
1147 return false;
1148
1149 case clang::DeclarationName::ObjCZeroArgSelector:
1150 case clang::DeclarationName::ObjCOneArgSelector:
1151 case clang::DeclarationName::ObjCMultiArgSelector:
1152 // FIXME: Per-identifier location info?
1153 return false;
1154 }
1155
1156 return false;
1157}
1158
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001159bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1160 SourceRange Range) {
1161 // FIXME: This whole routine is a hack to work around the lack of proper
1162 // source information in nested-name-specifiers (PR5791). Since we do have
1163 // a beginning source location, we can visit the first component of the
1164 // nested-name-specifier, if it's a single-token component.
1165 if (!NNS)
1166 return false;
1167
1168 // Get the first component in the nested-name-specifier.
1169 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1170 NNS = Prefix;
1171
1172 switch (NNS->getKind()) {
1173 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001174 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1175 TU));
1176
Douglas Gregor14aba762011-02-24 02:36:08 +00001177 case NestedNameSpecifier::NamespaceAlias:
1178 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1179 Range.getBegin(), TU));
1180
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001181 case NestedNameSpecifier::TypeSpec: {
1182 // If the type has a form where we know that the beginning of the source
1183 // range matches up with a reference cursor. Visit the appropriate reference
1184 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001185 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001186 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1187 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1188 if (const TagType *Tag = dyn_cast<TagType>(T))
1189 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1190 if (const TemplateSpecializationType *TST
1191 = dyn_cast<TemplateSpecializationType>(T))
1192 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1193 break;
1194 }
1195
1196 case NestedNameSpecifier::TypeSpecWithTemplate:
1197 case NestedNameSpecifier::Global:
1198 case NestedNameSpecifier::Identifier:
1199 break;
1200 }
1201
1202 return false;
1203}
1204
Douglas Gregordc355712011-02-25 00:36:19 +00001205bool
1206CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1207 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1208 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1209 Qualifiers.push_back(Qualifier);
1210
1211 while (!Qualifiers.empty()) {
1212 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1213 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1214 switch (NNS->getKind()) {
1215 case NestedNameSpecifier::Namespace:
1216 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001217 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001218 TU)))
1219 return true;
1220
1221 break;
1222
1223 case NestedNameSpecifier::NamespaceAlias:
1224 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001225 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001226 TU)))
1227 return true;
1228
1229 break;
1230
1231 case NestedNameSpecifier::TypeSpec:
1232 case NestedNameSpecifier::TypeSpecWithTemplate:
1233 if (Visit(Q.getTypeLoc()))
1234 return true;
1235
1236 break;
1237
1238 case NestedNameSpecifier::Global:
1239 case NestedNameSpecifier::Identifier:
1240 break;
1241 }
1242 }
1243
1244 return false;
1245}
1246
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001247bool CursorVisitor::VisitTemplateParameters(
1248 const TemplateParameterList *Params) {
1249 if (!Params)
1250 return false;
1251
1252 for (TemplateParameterList::const_iterator P = Params->begin(),
1253 PEnd = Params->end();
1254 P != PEnd; ++P) {
1255 if (Visit(MakeCXCursor(*P, TU)))
1256 return true;
1257 }
1258
1259 return false;
1260}
1261
Douglas Gregor0b36e612010-08-31 20:37:03 +00001262bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1263 switch (Name.getKind()) {
1264 case TemplateName::Template:
1265 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1266
1267 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001268 // Visit the overloaded template set.
1269 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1270 return true;
1271
Douglas Gregor0b36e612010-08-31 20:37:03 +00001272 return false;
1273
1274 case TemplateName::DependentTemplate:
1275 // FIXME: Visit nested-name-specifier.
1276 return false;
1277
1278 case TemplateName::QualifiedTemplate:
1279 // FIXME: Visit nested-name-specifier.
1280 return Visit(MakeCursorTemplateRef(
1281 Name.getAsQualifiedTemplateName()->getDecl(),
1282 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001283
1284 case TemplateName::SubstTemplateTemplateParmPack:
1285 return Visit(MakeCursorTemplateRef(
1286 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1287 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001288 }
1289
1290 return false;
1291}
1292
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001293bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1294 switch (TAL.getArgument().getKind()) {
1295 case TemplateArgument::Null:
1296 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001297 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298 return false;
1299
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300 case TemplateArgument::Type:
1301 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1302 return Visit(TSInfo->getTypeLoc());
1303 return false;
1304
1305 case TemplateArgument::Declaration:
1306 if (Expr *E = TAL.getSourceDeclExpression())
1307 return Visit(MakeCXCursor(E, StmtParent, TU));
1308 return false;
1309
1310 case TemplateArgument::Expression:
1311 if (Expr *E = TAL.getSourceExpression())
1312 return Visit(MakeCXCursor(E, StmtParent, TU));
1313 return false;
1314
1315 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001316 case TemplateArgument::TemplateExpansion:
1317 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001318 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001319 }
1320
1321 return false;
1322}
1323
Ted Kremeneka0536d82010-05-07 01:04:29 +00001324bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1325 return VisitDeclContext(D);
1326}
1327
Douglas Gregor01829d32010-08-31 14:41:23 +00001328bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1329 return Visit(TL.getUnqualifiedLoc());
1330}
1331
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001332bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001333 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334
1335 // Some builtin types (such as Objective-C's "id", "sel", and
1336 // "Class") have associated declarations. Create cursors for those.
1337 QualType VisitType;
1338 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001339 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001341 case BuiltinType::Char_U:
1342 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001343 case BuiltinType::Char16:
1344 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001345 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001346 case BuiltinType::UInt:
1347 case BuiltinType::ULong:
1348 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001349 case BuiltinType::UInt128:
1350 case BuiltinType::Char_S:
1351 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001352 case BuiltinType::WChar_U:
1353 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001354 case BuiltinType::Short:
1355 case BuiltinType::Int:
1356 case BuiltinType::Long:
1357 case BuiltinType::LongLong:
1358 case BuiltinType::Int128:
1359 case BuiltinType::Float:
1360 case BuiltinType::Double:
1361 case BuiltinType::LongDouble:
1362 case BuiltinType::NullPtr:
1363 case BuiltinType::Overload:
1364 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001365 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001366
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001367 case BuiltinType::ObjCId:
1368 VisitType = Context.getObjCIdType();
1369 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001370
1371 case BuiltinType::ObjCClass:
1372 VisitType = Context.getObjCClassType();
1373 break;
1374
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375 case BuiltinType::ObjCSel:
1376 VisitType = Context.getObjCSelType();
1377 break;
1378 }
1379
1380 if (!VisitType.isNull()) {
1381 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001382 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001383 TU));
1384 }
1385
1386 return false;
1387}
1388
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001389bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1390 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1391}
1392
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1394 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1395}
1396
1397bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1398 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1399}
1400
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001401bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001402 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001403 // no context information with which we can match up the depth/index in the
1404 // type to the appropriate
1405 return false;
1406}
1407
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001408bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1409 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1410 return true;
1411
John McCallc12c5bb2010-05-15 11:32:37 +00001412 return false;
1413}
1414
1415bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1416 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1417 return true;
1418
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001419 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1420 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1421 TU)))
1422 return true;
1423 }
1424
1425 return false;
1426}
1427
1428bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001429 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001430}
1431
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001432bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1433 return Visit(TL.getInnerLoc());
1434}
1435
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001436bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1437 return Visit(TL.getPointeeLoc());
1438}
1439
1440bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1441 return Visit(TL.getPointeeLoc());
1442}
1443
1444bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1445 return Visit(TL.getPointeeLoc());
1446}
1447
1448bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001449 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001450}
1451
1452bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001453 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001454}
1455
Douglas Gregor01829d32010-08-31 14:41:23 +00001456bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1457 bool SkipResultType) {
1458 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001459 return true;
1460
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001461 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001462 if (Decl *D = TL.getArg(I))
1463 if (Visit(MakeCXCursor(D, TU)))
1464 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001465
1466 return false;
1467}
1468
1469bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1470 if (Visit(TL.getElementLoc()))
1471 return true;
1472
1473 if (Expr *Size = TL.getSizeExpr())
1474 return Visit(MakeCXCursor(Size, StmtParent, TU));
1475
1476 return false;
1477}
1478
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001479bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1480 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001481 // Visit the template name.
1482 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1483 TL.getTemplateNameLoc()))
1484 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001485
1486 // Visit the template arguments.
1487 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1488 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1489 return true;
1490
1491 return false;
1492}
1493
Douglas Gregor2332c112010-01-21 20:48:56 +00001494bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1495 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1496}
1497
1498bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1499 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1500 return Visit(TSInfo->getTypeLoc());
1501
1502 return false;
1503}
1504
Douglas Gregor7536dd52010-12-20 02:24:11 +00001505bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1506 return Visit(TL.getPatternLoc());
1507}
1508
Ted Kremenek3064ef92010-08-27 21:34:58 +00001509bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001510 // Visit the nested-name-specifier, if present.
1511 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1512 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1513 return true;
1514
Ted Kremenek3064ef92010-08-27 21:34:58 +00001515 if (D->isDefinition()) {
1516 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1517 E = D->bases_end(); I != E; ++I) {
1518 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1519 return true;
1520 }
1521 }
1522
1523 return VisitTagDecl(D);
1524}
1525
Ted Kremenek09dfa372010-02-18 05:46:33 +00001526bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001527 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1528 i != e; ++i)
1529 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001530 return true;
1531
1532 return false;
1533}
1534
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001535//===----------------------------------------------------------------------===//
1536// Data-recursive visitor methods.
1537//===----------------------------------------------------------------------===//
1538
Ted Kremenek28a71942010-11-13 00:36:47 +00001539namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001540#define DEF_JOB(NAME, DATA, KIND)\
1541class NAME : public VisitorJob {\
1542public:\
1543 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1544 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001545 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001546};
1547
1548DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1549DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001550DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001551DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001552DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1553 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001554DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001555#undef DEF_JOB
1556
1557class DeclVisit : public VisitorJob {
1558public:
1559 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1560 VisitorJob(parent, VisitorJob::DeclVisitKind,
1561 d, isFirst ? (void*) 1 : (void*) 0) {}
1562 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001563 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001564 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001565 Decl *get() const { return static_cast<Decl*>(data[0]); }
1566 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001567};
Ted Kremenek035dc412010-11-13 00:36:50 +00001568class TypeLocVisit : public VisitorJob {
1569public:
1570 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1571 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1572 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1573
1574 static bool classof(const VisitorJob *VJ) {
1575 return VJ->getKind() == TypeLocVisitKind;
1576 }
1577
Ted Kremenek82f3c502010-11-15 22:23:26 +00001578 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001579 QualType T = QualType::getFromOpaquePtr(data[0]);
1580 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001581 }
1582};
1583
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001584class LabelRefVisit : public VisitorJob {
1585public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001586 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1587 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001588 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001589
1590 static bool classof(const VisitorJob *VJ) {
1591 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1592 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001593 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001594 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001595 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001596};
1597class NestedNameSpecifierVisit : public VisitorJob {
1598public:
1599 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1600 CXCursor parent)
1601 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001602 NS, R.getBegin().getPtrEncoding(),
1603 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001604 static bool classof(const VisitorJob *VJ) {
1605 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1606 }
1607 NestedNameSpecifier *get() const {
1608 return static_cast<NestedNameSpecifier*>(data[0]);
1609 }
1610 SourceRange getSourceRange() const {
1611 SourceLocation A =
1612 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1613 SourceLocation B =
1614 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1615 return SourceRange(A, B);
1616 }
1617};
1618class DeclarationNameInfoVisit : public VisitorJob {
1619public:
1620 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1621 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1622 static bool classof(const VisitorJob *VJ) {
1623 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1624 }
1625 DeclarationNameInfo get() const {
1626 Stmt *S = static_cast<Stmt*>(data[0]);
1627 switch (S->getStmtClass()) {
1628 default:
1629 llvm_unreachable("Unhandled Stmt");
1630 case Stmt::CXXDependentScopeMemberExprClass:
1631 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1632 case Stmt::DependentScopeDeclRefExprClass:
1633 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1634 }
1635 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001636};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001637class MemberRefVisit : public VisitorJob {
1638public:
1639 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1640 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001641 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001642 static bool classof(const VisitorJob *VJ) {
1643 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1644 }
1645 FieldDecl *get() const {
1646 return static_cast<FieldDecl*>(data[0]);
1647 }
1648 SourceLocation getLoc() const {
1649 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1650 }
1651};
Ted Kremenek28a71942010-11-13 00:36:47 +00001652class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1653 VisitorWorkList &WL;
1654 CXCursor Parent;
1655public:
1656 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1657 : WL(wl), Parent(parent) {}
1658
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001659 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001660 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001661 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001662 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001663 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001664 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001665 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001666 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001667 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001668 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001669 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001670 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001671 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001672 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001673 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001674 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001675 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001676 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001677 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1678 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001679 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001680 void VisitIfStmt(IfStmt *If);
1681 void VisitInitListExpr(InitListExpr *IE);
1682 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001683 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001684 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001685 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1686 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001687 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001688 void VisitStmt(Stmt *S);
1689 void VisitSwitchStmt(SwitchStmt *S);
1690 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001691 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001692 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001693 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001694 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001695 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001696
Ted Kremenek28a71942010-11-13 00:36:47 +00001697private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001698 void AddDeclarationNameInfo(Stmt *S);
1699 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001700 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001701 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001702 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001703 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void AddTypeLoc(TypeSourceInfo *TI);
1705 void EnqueueChildren(Stmt *S);
1706};
1707} // end anonyous namespace
1708
Ted Kremenekf64d8032010-11-18 00:02:32 +00001709void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1710 // 'S' should always be non-null, since it comes from the
1711 // statement we are visiting.
1712 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1713}
1714void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1715 SourceRange R) {
1716 if (N)
1717 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1718}
Ted Kremenek28a71942010-11-13 00:36:47 +00001719void EnqueueVisitor::AddStmt(Stmt *S) {
1720 if (S)
1721 WL.push_back(StmtVisit(S, Parent));
1722}
Ted Kremenek035dc412010-11-13 00:36:50 +00001723void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001724 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001725 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001726}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001727void EnqueueVisitor::
1728 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1729 if (A)
1730 WL.push_back(ExplicitTemplateArgsVisit(
1731 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1732}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001733void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1734 if (D)
1735 WL.push_back(MemberRefVisit(D, L, Parent));
1736}
Ted Kremenek28a71942010-11-13 00:36:47 +00001737void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1738 if (TI)
1739 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1740 }
1741void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001742 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001743 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001744 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001745 }
1746 if (size == WL.size())
1747 return;
1748 // Now reverse the entries we just added. This will match the DFS
1749 // ordering performed by the worklist.
1750 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1751 std::reverse(I, E);
1752}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001753void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1754 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1755}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001756void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1757 AddDecl(B->getBlockDecl());
1758}
Ted Kremenek28a71942010-11-13 00:36:47 +00001759void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1760 EnqueueChildren(E);
1761 AddTypeLoc(E->getTypeSourceInfo());
1762}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001763void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1764 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1765 E = S->body_rend(); I != E; ++I) {
1766 AddStmt(*I);
1767 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001768}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001769void EnqueueVisitor::
1770VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1771 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1772 AddDeclarationNameInfo(E);
1773 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1774 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1775 if (!E->isImplicitAccess())
1776 AddStmt(E->getBase());
1777}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001778void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1779 // Enqueue the initializer or constructor arguments.
1780 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1781 AddStmt(E->getConstructorArg(I-1));
1782 // Enqueue the array size, if any.
1783 AddStmt(E->getArraySize());
1784 // Enqueue the allocated type.
1785 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1786 // Enqueue the placement arguments.
1787 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1788 AddStmt(E->getPlacementArg(I-1));
1789}
Ted Kremenek28a71942010-11-13 00:36:47 +00001790void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001791 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1792 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001793 AddStmt(CE->getCallee());
1794 AddStmt(CE->getArg(0));
1795}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001796void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1797 // Visit the name of the type being destroyed.
1798 AddTypeLoc(E->getDestroyedTypeInfo());
1799 // Visit the scope type that looks disturbingly like the nested-name-specifier
1800 // but isn't.
1801 AddTypeLoc(E->getScopeTypeInfo());
1802 // Visit the nested-name-specifier.
1803 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1804 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1805 // Visit base expression.
1806 AddStmt(E->getBase());
1807}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001808void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1809 AddTypeLoc(E->getTypeSourceInfo());
1810}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001811void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1812 EnqueueChildren(E);
1813 AddTypeLoc(E->getTypeSourceInfo());
1814}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001815void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1816 EnqueueChildren(E);
1817 if (E->isTypeOperand())
1818 AddTypeLoc(E->getTypeOperandSourceInfo());
1819}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001820
1821void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1822 *E) {
1823 EnqueueChildren(E);
1824 AddTypeLoc(E->getTypeSourceInfo());
1825}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001826void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1827 EnqueueChildren(E);
1828 if (E->isTypeOperand())
1829 AddTypeLoc(E->getTypeOperandSourceInfo());
1830}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001831void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001832 if (DR->hasExplicitTemplateArgs()) {
1833 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1834 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001835 WL.push_back(DeclRefExprParts(DR, Parent));
1836}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001837void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1838 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1839 AddDeclarationNameInfo(E);
1840 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1841 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1842}
Ted Kremenek035dc412010-11-13 00:36:50 +00001843void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1844 unsigned size = WL.size();
1845 bool isFirst = true;
1846 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1847 D != DEnd; ++D) {
1848 AddDecl(*D, isFirst);
1849 isFirst = false;
1850 }
1851 if (size == WL.size())
1852 return;
1853 // Now reverse the entries we just added. This will match the DFS
1854 // ordering performed by the worklist.
1855 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1856 std::reverse(I, E);
1857}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001858void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1859 AddStmt(E->getInit());
1860 typedef DesignatedInitExpr::Designator Designator;
1861 for (DesignatedInitExpr::reverse_designators_iterator
1862 D = E->designators_rbegin(), DEnd = E->designators_rend();
1863 D != DEnd; ++D) {
1864 if (D->isFieldDesignator()) {
1865 if (FieldDecl *Field = D->getField())
1866 AddMemberRef(Field, D->getFieldLoc());
1867 continue;
1868 }
1869 if (D->isArrayDesignator()) {
1870 AddStmt(E->getArrayIndex(*D));
1871 continue;
1872 }
1873 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1874 AddStmt(E->getArrayRangeEnd(*D));
1875 AddStmt(E->getArrayRangeStart(*D));
1876 }
1877}
Ted Kremenek28a71942010-11-13 00:36:47 +00001878void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1879 EnqueueChildren(E);
1880 AddTypeLoc(E->getTypeInfoAsWritten());
1881}
1882void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1883 AddStmt(FS->getBody());
1884 AddStmt(FS->getInc());
1885 AddStmt(FS->getCond());
1886 AddDecl(FS->getConditionVariable());
1887 AddStmt(FS->getInit());
1888}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001889void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1890 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1891}
Ted Kremenek28a71942010-11-13 00:36:47 +00001892void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1893 AddStmt(If->getElse());
1894 AddStmt(If->getThen());
1895 AddStmt(If->getCond());
1896 AddDecl(If->getConditionVariable());
1897}
1898void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1899 // We care about the syntactic form of the initializer list, only.
1900 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1901 IE = Syntactic;
1902 EnqueueChildren(IE);
1903}
1904void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001905 WL.push_back(MemberExprParts(M, Parent));
1906
1907 // If the base of the member access expression is an implicit 'this', don't
1908 // visit it.
1909 // FIXME: If we ever want to show these implicit accesses, this will be
1910 // unfortunate. However, clang_getCursor() relies on this behavior.
1911 if (CXXThisExpr *This
1912 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1913 if (This->isImplicit())
1914 return;
1915
Ted Kremenek28a71942010-11-13 00:36:47 +00001916 AddStmt(M->getBase());
1917}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001918void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1919 AddTypeLoc(E->getEncodedTypeSourceInfo());
1920}
Ted Kremenek28a71942010-11-13 00:36:47 +00001921void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1922 EnqueueChildren(M);
1923 AddTypeLoc(M->getClassReceiverTypeInfo());
1924}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001925void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1926 // Visit the components of the offsetof expression.
1927 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1928 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1929 const OffsetOfNode &Node = E->getComponent(I-1);
1930 switch (Node.getKind()) {
1931 case OffsetOfNode::Array:
1932 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1933 break;
1934 case OffsetOfNode::Field:
1935 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1936 break;
1937 case OffsetOfNode::Identifier:
1938 case OffsetOfNode::Base:
1939 continue;
1940 }
1941 }
1942 // Visit the type into which we're computing the offset.
1943 AddTypeLoc(E->getTypeSourceInfo());
1944}
Ted Kremenek28a71942010-11-13 00:36:47 +00001945void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001946 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001947 WL.push_back(OverloadExprParts(E, Parent));
1948}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001949void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1950 EnqueueChildren(E);
1951 if (E->isArgumentType())
1952 AddTypeLoc(E->getArgumentTypeInfo());
1953}
Ted Kremenek28a71942010-11-13 00:36:47 +00001954void EnqueueVisitor::VisitStmt(Stmt *S) {
1955 EnqueueChildren(S);
1956}
1957void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1958 AddStmt(S->getBody());
1959 AddStmt(S->getCond());
1960 AddDecl(S->getConditionVariable());
1961}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001962
Ted Kremenek28a71942010-11-13 00:36:47 +00001963void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1964 AddStmt(W->getBody());
1965 AddStmt(W->getCond());
1966 AddDecl(W->getConditionVariable());
1967}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001968void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1969 AddTypeLoc(E->getQueriedTypeSourceInfo());
1970}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001971
1972void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00001973 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00001974 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00001975}
1976
Ted Kremenek28a71942010-11-13 00:36:47 +00001977void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1978 VisitOverloadExpr(U);
1979 if (!U->isImplicitAccess())
1980 AddStmt(U->getBase());
1981}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001982void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1983 AddStmt(E->getSubExpr());
1984 AddTypeLoc(E->getWrittenTypeInfo());
1985}
Douglas Gregor94d96292011-01-19 20:34:17 +00001986void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1987 WL.push_back(SizeOfPackExprParts(E, Parent));
1988}
Ted Kremenek60458782010-11-12 21:34:16 +00001989
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001990void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001991 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001992}
1993
1994bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1995 if (RegionOfInterest.isValid()) {
1996 SourceRange Range = getRawCursorExtent(C);
1997 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1998 return false;
1999 }
2000 return true;
2001}
2002
2003bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2004 while (!WL.empty()) {
2005 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002006 VisitorJob LI = WL.back();
2007 WL.pop_back();
2008
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002009 // Set the Parent field, then back to its old value once we're done.
2010 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2011
2012 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002013 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002014 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002015 if (!D)
2016 continue;
2017
2018 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002019 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002020 return true;
2021
2022 continue;
2023 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002024 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2025 const ExplicitTemplateArgumentList *ArgList =
2026 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2027 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2028 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2029 Arg != ArgEnd; ++Arg) {
2030 if (VisitTemplateArgumentLoc(*Arg))
2031 return true;
2032 }
2033 continue;
2034 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002035 case VisitorJob::TypeLocVisitKind: {
2036 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002037 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002038 return true;
2039 continue;
2040 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002041 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002042 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002043 if (LabelStmt *stmt = LS->getStmt()) {
2044 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2045 TU))) {
2046 return true;
2047 }
2048 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002049 continue;
2050 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00002051 case VisitorJob::NestedNameSpecifierVisitKind: {
2052 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2053 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2054 return true;
2055 continue;
2056 }
2057 case VisitorJob::DeclarationNameInfoVisitKind: {
2058 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2059 ->get()))
2060 return true;
2061 continue;
2062 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002063 case VisitorJob::MemberRefVisitKind: {
2064 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2065 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2066 return true;
2067 continue;
2068 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002069 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002070 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002071 if (!S)
2072 continue;
2073
Ted Kremenekf1107452010-11-12 18:26:56 +00002074 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002075 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002076 if (!IsInRegionOfInterest(Cursor))
2077 continue;
2078 switch (Visitor(Cursor, Parent, ClientData)) {
2079 case CXChildVisit_Break: return true;
2080 case CXChildVisit_Continue: break;
2081 case CXChildVisit_Recurse:
2082 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002083 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002084 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002085 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002086 }
2087 case VisitorJob::MemberExprPartsKind: {
2088 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002089 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002090
2091 // Visit the nested-name-specifier
2092 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2093 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2094 return true;
2095
2096 // Visit the declaration name.
2097 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2098 return true;
2099
2100 // Visit the explicitly-specified template arguments, if any.
2101 if (M->hasExplicitTemplateArgs()) {
2102 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2103 *ArgEnd = Arg + M->getNumTemplateArgs();
2104 Arg != ArgEnd; ++Arg) {
2105 if (VisitTemplateArgumentLoc(*Arg))
2106 return true;
2107 }
2108 }
2109 continue;
2110 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002111 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002112 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002113 // Visit nested-name-specifier, if present.
2114 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2115 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2116 return true;
2117 // Visit declaration name.
2118 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2119 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002120 continue;
2121 }
Ted Kremenek60458782010-11-12 21:34:16 +00002122 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002123 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002124 // Visit the nested-name-specifier.
2125 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2126 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2127 return true;
2128 // Visit the declaration name.
2129 if (VisitDeclarationNameInfo(O->getNameInfo()))
2130 return true;
2131 // Visit the overloaded declaration reference.
2132 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2133 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002134 continue;
2135 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002136 case VisitorJob::SizeOfPackExprPartsKind: {
2137 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2138 NamedDecl *Pack = E->getPack();
2139 if (isa<TemplateTypeParmDecl>(Pack)) {
2140 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2141 E->getPackLoc(), TU)))
2142 return true;
2143
2144 continue;
2145 }
2146
2147 if (isa<TemplateTemplateParmDecl>(Pack)) {
2148 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2149 E->getPackLoc(), TU)))
2150 return true;
2151
2152 continue;
2153 }
2154
2155 // Non-type template parameter packs and function parameter packs are
2156 // treated like DeclRefExpr cursors.
2157 continue;
2158 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002159 }
2160 }
2161 return false;
2162}
2163
Ted Kremenekcdba6592010-11-18 00:42:18 +00002164bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002165 VisitorWorkList *WL = 0;
2166 if (!WorkListFreeList.empty()) {
2167 WL = WorkListFreeList.back();
2168 WL->clear();
2169 WorkListFreeList.pop_back();
2170 }
2171 else {
2172 WL = new VisitorWorkList();
2173 WorkListCache.push_back(WL);
2174 }
2175 EnqueueWorkList(*WL, S);
2176 bool result = RunVisitorWorkList(*WL);
2177 WorkListFreeList.push_back(WL);
2178 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002179}
2180
2181//===----------------------------------------------------------------------===//
2182// Misc. API hooks.
2183//===----------------------------------------------------------------------===//
2184
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002185static llvm::sys::Mutex EnableMultithreadingMutex;
2186static bool EnabledMultithreading;
2187
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002188extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002189CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2190 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002191 // Disable pretty stack trace functionality, which will otherwise be a very
2192 // poor citizen of the world and set up all sorts of signal handlers.
2193 llvm::DisablePrettyStackTrace = true;
2194
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002195 // We use crash recovery to make some of our APIs more reliable, implicitly
2196 // enable it.
2197 llvm::CrashRecoveryContext::Enable();
2198
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002199 // Enable support for multithreading in LLVM.
2200 {
2201 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2202 if (!EnabledMultithreading) {
2203 llvm::llvm_start_multithreaded();
2204 EnabledMultithreading = true;
2205 }
2206 }
2207
Douglas Gregora030b7c2010-01-22 20:35:53 +00002208 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002209 if (excludeDeclarationsFromPCH)
2210 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002211 if (displayDiagnostics)
2212 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002213 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002214}
2215
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002216void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002217 if (CIdx)
2218 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002219}
2220
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002221CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002222 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002223 if (!CIdx)
2224 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002225
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002226 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002227 FileSystemOptions FileSystemOpts;
2228 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002229
Douglas Gregor28019772010-04-05 23:52:57 +00002230 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002231 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002232 CXXIdx->getOnlyLocalDecls(),
2233 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002234 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002235}
2236
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002237unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002238 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002239 CXTranslationUnit_CacheCompletionResults |
2240 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002241}
2242
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002243CXTranslationUnit
2244clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2245 const char *source_filename,
2246 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002247 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002248 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002249 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002250 return clang_parseTranslationUnit(CIdx, source_filename,
2251 command_line_args, num_command_line_args,
2252 unsaved_files, num_unsaved_files,
2253 CXTranslationUnit_DetailedPreprocessingRecord);
2254}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002255
2256struct ParseTranslationUnitInfo {
2257 CXIndex CIdx;
2258 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002259 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002260 int num_command_line_args;
2261 struct CXUnsavedFile *unsaved_files;
2262 unsigned num_unsaved_files;
2263 unsigned options;
2264 CXTranslationUnit result;
2265};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002266static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002267 ParseTranslationUnitInfo *PTUI =
2268 static_cast<ParseTranslationUnitInfo*>(UserData);
2269 CXIndex CIdx = PTUI->CIdx;
2270 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002271 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002272 int num_command_line_args = PTUI->num_command_line_args;
2273 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2274 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2275 unsigned options = PTUI->options;
2276 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002277
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002278 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002279 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002280
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002281 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2282
Douglas Gregor44c181a2010-07-23 00:33:23 +00002283 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002284 bool CompleteTranslationUnit
2285 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002286 bool CacheCodeCompetionResults
2287 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002288 bool CXXPrecompilePreamble
2289 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2290 bool CXXChainedPCH
2291 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002292
Douglas Gregor5352ac02010-01-28 00:27:43 +00002293 // Configure the diagnostics.
2294 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002295 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002296 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2297 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002298
Douglas Gregor4db64a42010-01-23 00:14:00 +00002299 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2300 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002301 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002302 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002303 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002304 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2305 Buffer));
2306 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002307
Douglas Gregorb10daed2010-10-11 16:52:23 +00002308 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002309
Ted Kremenek139ba862009-10-22 00:03:57 +00002310 // The 'source_filename' argument is optional. If the caller does not
2311 // specify it then it is assumed that the source file is specified
2312 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002313 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002314 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002315
2316 // Since the Clang C library is primarily used by batch tools dealing with
2317 // (often very broken) source code, where spell-checking can have a
2318 // significant negative impact on performance (particularly when
2319 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002320 // Only do this if we haven't found a spell-checking-related argument.
2321 bool FoundSpellCheckingArgument = false;
2322 for (int I = 0; I != num_command_line_args; ++I) {
2323 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2324 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2325 FoundSpellCheckingArgument = true;
2326 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002327 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002328 }
2329 if (!FoundSpellCheckingArgument)
2330 Args.push_back("-fno-spell-checking");
2331
2332 Args.insert(Args.end(), command_line_args,
2333 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002334
Douglas Gregor44c181a2010-07-23 00:33:23 +00002335 // Do we need the detailed preprocessing record?
2336 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002337 Args.push_back("-Xclang");
2338 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002339 }
2340
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002341 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002342 llvm::OwningPtr<ASTUnit> Unit(
2343 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2344 Diags,
2345 CXXIdx->getClangResourcesPath(),
2346 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002347 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002348 RemappedFiles.data(),
2349 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002350 PrecompilePreamble,
2351 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002352 CacheCodeCompetionResults,
2353 CXXPrecompilePreamble,
2354 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002355
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002356 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002357 // Make sure to check that 'Unit' is non-NULL.
2358 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2359 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2360 DEnd = Unit->stored_diag_end();
2361 D != DEnd; ++D) {
2362 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2363 CXString Msg = clang_formatDiagnostic(&Diag,
2364 clang_defaultDiagnosticDisplayOptions());
2365 fprintf(stderr, "%s\n", clang_getCString(Msg));
2366 clang_disposeString(Msg);
2367 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002368#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002369 // On Windows, force a flush, since there may be multiple copies of
2370 // stderr and stdout in the file system, all with different buffers
2371 // but writing to the same device.
2372 fflush(stderr);
2373#endif
2374 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002375 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002376
Ted Kremeneka60ed472010-11-16 08:15:36 +00002377 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002378}
2379CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2380 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002381 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002382 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002383 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002384 unsigned num_unsaved_files,
2385 unsigned options) {
2386 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002387 num_command_line_args, unsaved_files,
2388 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002389 llvm::CrashRecoveryContext CRC;
2390
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002391 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002392 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2393 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2394 fprintf(stderr, " 'command_line_args' : [");
2395 for (int i = 0; i != num_command_line_args; ++i) {
2396 if (i)
2397 fprintf(stderr, ", ");
2398 fprintf(stderr, "'%s'", command_line_args[i]);
2399 }
2400 fprintf(stderr, "],\n");
2401 fprintf(stderr, " 'unsaved_files' : [");
2402 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2403 if (i)
2404 fprintf(stderr, ", ");
2405 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2406 unsaved_files[i].Length);
2407 }
2408 fprintf(stderr, "],\n");
2409 fprintf(stderr, " 'options' : %d,\n", options);
2410 fprintf(stderr, "}\n");
2411
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002412 return 0;
2413 }
2414
2415 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002416}
2417
Douglas Gregor19998442010-08-13 15:35:05 +00002418unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2419 return CXSaveTranslationUnit_None;
2420}
2421
2422int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2423 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002424 if (!TU)
2425 return 1;
2426
Ted Kremeneka60ed472010-11-16 08:15:36 +00002427 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002428}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002429
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002430void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002431 if (CTUnit) {
2432 // If the translation unit has been marked as unsafe to free, just discard
2433 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002434 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002435 return;
2436
Ted Kremeneka60ed472010-11-16 08:15:36 +00002437 delete static_cast<ASTUnit *>(CTUnit->TUData);
2438 disposeCXStringPool(CTUnit->StringPool);
2439 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002440 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002441}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002442
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002443unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2444 return CXReparse_None;
2445}
2446
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002447struct ReparseTranslationUnitInfo {
2448 CXTranslationUnit TU;
2449 unsigned num_unsaved_files;
2450 struct CXUnsavedFile *unsaved_files;
2451 unsigned options;
2452 int result;
2453};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002454
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002455static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002456 ReparseTranslationUnitInfo *RTUI =
2457 static_cast<ReparseTranslationUnitInfo*>(UserData);
2458 CXTranslationUnit TU = RTUI->TU;
2459 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2460 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2461 unsigned options = RTUI->options;
2462 (void) options;
2463 RTUI->result = 1;
2464
Douglas Gregorabc563f2010-07-19 21:46:24 +00002465 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002466 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002467
Ted Kremeneka60ed472010-11-16 08:15:36 +00002468 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002469 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002470
2471 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2472 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2473 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2474 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002475 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002476 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2477 Buffer));
2478 }
2479
Douglas Gregor593b0c12010-09-23 18:47:53 +00002480 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2481 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002482}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002483
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002484int clang_reparseTranslationUnit(CXTranslationUnit TU,
2485 unsigned num_unsaved_files,
2486 struct CXUnsavedFile *unsaved_files,
2487 unsigned options) {
2488 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2489 options, 0 };
2490 llvm::CrashRecoveryContext CRC;
2491
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002492 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002493 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002494 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002495 return 1;
2496 }
2497
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002498
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002499 return RTUI.result;
2500}
2501
Douglas Gregordf95a132010-08-09 20:45:32 +00002502
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002503CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002504 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002505 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002506
Ted Kremeneka60ed472010-11-16 08:15:36 +00002507 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002508 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002509}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002510
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002511CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002512 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002513 return Result;
2514}
2515
Ted Kremenekfb480492010-01-13 21:46:36 +00002516} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002517
Ted Kremenekfb480492010-01-13 21:46:36 +00002518//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002519// CXSourceLocation and CXSourceRange Operations.
2520//===----------------------------------------------------------------------===//
2521
Douglas Gregorb9790342010-01-22 21:44:22 +00002522extern "C" {
2523CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002524 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002525 return Result;
2526}
2527
2528unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002529 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2530 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2531 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002532}
2533
2534CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2535 CXFile file,
2536 unsigned line,
2537 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002538 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002539 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002540
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002541 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002542 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002543 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002544 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002545 = CXXUnit->getSourceManager().getLocation(File, line, column);
2546 if (SLoc.isInvalid()) {
2547 if (Logging)
2548 llvm::errs() << "clang_getLocation(\"" << File->getName()
2549 << "\", " << line << ", " << column << ") = invalid\n";
2550 return clang_getNullLocation();
2551 }
2552
2553 if (Logging)
2554 llvm::errs() << "clang_getLocation(\"" << File->getName()
2555 << "\", " << line << ", " << column << ") = "
2556 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002557
2558 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2559}
2560
2561CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2562 CXFile file,
2563 unsigned offset) {
2564 if (!tu || !file)
2565 return clang_getNullLocation();
2566
Ted Kremeneka60ed472010-11-16 08:15:36 +00002567 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002568 SourceLocation Start
2569 = CXXUnit->getSourceManager().getLocation(
2570 static_cast<const FileEntry *>(file),
2571 1, 1);
2572 if (Start.isInvalid()) return clang_getNullLocation();
2573
2574 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2575
2576 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002577
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002578 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002579}
2580
Douglas Gregor5352ac02010-01-28 00:27:43 +00002581CXSourceRange clang_getNullRange() {
2582 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2583 return Result;
2584}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002585
Douglas Gregor5352ac02010-01-28 00:27:43 +00002586CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2587 if (begin.ptr_data[0] != end.ptr_data[0] ||
2588 begin.ptr_data[1] != end.ptr_data[1])
2589 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590
2591 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002592 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002593 return Result;
2594}
2595
Douglas Gregor46766dc2010-01-26 19:19:08 +00002596void clang_getInstantiationLocation(CXSourceLocation location,
2597 CXFile *file,
2598 unsigned *line,
2599 unsigned *column,
2600 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002601 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2602
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002603 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002604 if (file)
2605 *file = 0;
2606 if (line)
2607 *line = 0;
2608 if (column)
2609 *column = 0;
2610 if (offset)
2611 *offset = 0;
2612 return;
2613 }
2614
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002615 const SourceManager &SM =
2616 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002617 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002618
2619 if (file)
2620 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2621 if (line)
2622 *line = SM.getInstantiationLineNumber(InstLoc);
2623 if (column)
2624 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002625 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002626 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002627}
2628
Douglas Gregora9b06d42010-11-09 06:24:54 +00002629void clang_getSpellingLocation(CXSourceLocation location,
2630 CXFile *file,
2631 unsigned *line,
2632 unsigned *column,
2633 unsigned *offset) {
2634 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2635
2636 if (!location.ptr_data[0] || Loc.isInvalid()) {
2637 if (file)
2638 *file = 0;
2639 if (line)
2640 *line = 0;
2641 if (column)
2642 *column = 0;
2643 if (offset)
2644 *offset = 0;
2645 return;
2646 }
2647
2648 const SourceManager &SM =
2649 *static_cast<const SourceManager*>(location.ptr_data[0]);
2650 SourceLocation SpellLoc = Loc;
2651 if (SpellLoc.isMacroID()) {
2652 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2653 if (SimpleSpellingLoc.isFileID() &&
2654 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2655 SpellLoc = SimpleSpellingLoc;
2656 else
2657 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2658 }
2659
2660 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2661 FileID FID = LocInfo.first;
2662 unsigned FileOffset = LocInfo.second;
2663
2664 if (file)
2665 *file = (void *)SM.getFileEntryForID(FID);
2666 if (line)
2667 *line = SM.getLineNumber(FID, FileOffset);
2668 if (column)
2669 *column = SM.getColumnNumber(FID, FileOffset);
2670 if (offset)
2671 *offset = FileOffset;
2672}
2673
Douglas Gregor1db19de2010-01-19 21:36:55 +00002674CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002675 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002676 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002677 return Result;
2678}
2679
2680CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002681 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002682 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002683 return Result;
2684}
2685
Douglas Gregorb9790342010-01-22 21:44:22 +00002686} // end: extern "C"
2687
Douglas Gregor1db19de2010-01-19 21:36:55 +00002688//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002689// CXFile Operations.
2690//===----------------------------------------------------------------------===//
2691
2692extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002693CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002694 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002695 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002696
Steve Naroff88145032009-10-27 14:35:18 +00002697 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002698 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002699}
2700
2701time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002702 if (!SFile)
2703 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002704
Steve Naroff88145032009-10-27 14:35:18 +00002705 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2706 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002707}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002708
Douglas Gregorb9790342010-01-22 21:44:22 +00002709CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2710 if (!tu)
2711 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002712
Ted Kremeneka60ed472010-11-16 08:15:36 +00002713 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002714
Douglas Gregorb9790342010-01-22 21:44:22 +00002715 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002716 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002717}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002718
Ted Kremenekfb480492010-01-13 21:46:36 +00002719} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002720
Ted Kremenekfb480492010-01-13 21:46:36 +00002721//===----------------------------------------------------------------------===//
2722// CXCursor Operations.
2723//===----------------------------------------------------------------------===//
2724
Ted Kremenekfb480492010-01-13 21:46:36 +00002725static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002726 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2727 return getDeclFromExpr(CE->getSubExpr());
2728
Ted Kremenekfb480492010-01-13 21:46:36 +00002729 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2730 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002731 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2732 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002733 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2734 return ME->getMemberDecl();
2735 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2736 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002737 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002738 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002739
Ted Kremenekfb480492010-01-13 21:46:36 +00002740 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2741 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002742 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2743 if (!CE->isElidable())
2744 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002745 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2746 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002747
Douglas Gregordb1314e2010-10-01 21:11:22 +00002748 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2749 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002750 if (SubstNonTypeTemplateParmPackExpr *NTTP
2751 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2752 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002753 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2754 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2755 isa<ParmVarDecl>(SizeOfPack->getPack()))
2756 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002757
Ted Kremenekfb480492010-01-13 21:46:36 +00002758 return 0;
2759}
2760
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002761static SourceLocation getLocationFromExpr(Expr *E) {
2762 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2763 return /*FIXME:*/Msg->getLeftLoc();
2764 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2765 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002766 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2767 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002768 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2769 return Member->getMemberLoc();
2770 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2771 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002772 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2773 return SizeOfPack->getPackLoc();
2774
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002775 return E->getLocStart();
2776}
2777
Ted Kremenekfb480492010-01-13 21:46:36 +00002778extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002779
2780unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002781 CXCursorVisitor visitor,
2782 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002783 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2784 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002785 return CursorVis.VisitChildren(parent);
2786}
2787
David Chisnall3387c652010-11-03 14:12:26 +00002788#ifndef __has_feature
2789#define __has_feature(x) 0
2790#endif
2791#if __has_feature(blocks)
2792typedef enum CXChildVisitResult
2793 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2794
2795static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2796 CXClientData client_data) {
2797 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2798 return block(cursor, parent);
2799}
2800#else
2801// If we are compiled with a compiler that doesn't have native blocks support,
2802// define and call the block manually, so the
2803typedef struct _CXChildVisitResult
2804{
2805 void *isa;
2806 int flags;
2807 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002808 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2809 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002810} *CXCursorVisitorBlock;
2811
2812static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2813 CXClientData client_data) {
2814 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2815 return block->invoke(block, cursor, parent);
2816}
2817#endif
2818
2819
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002820unsigned clang_visitChildrenWithBlock(CXCursor parent,
2821 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002822 return clang_visitChildren(parent, visitWithBlock, block);
2823}
2824
Douglas Gregor78205d42010-01-20 21:45:58 +00002825static CXString getDeclSpelling(Decl *D) {
2826 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002827 if (!ND) {
2828 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2829 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2830 return createCXString(Property->getIdentifier()->getName());
2831
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002832 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002833 }
2834
Douglas Gregor78205d42010-01-20 21:45:58 +00002835 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002836 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002837
Douglas Gregor78205d42010-01-20 21:45:58 +00002838 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2839 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2840 // and returns different names. NamedDecl returns the class name and
2841 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002842 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002843
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002844 if (isa<UsingDirectiveDecl>(D))
2845 return createCXString("");
2846
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002847 llvm::SmallString<1024> S;
2848 llvm::raw_svector_ostream os(S);
2849 ND->printName(os);
2850
2851 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002852}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002853
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002854CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002855 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002856 return clang_getTranslationUnitSpelling(
2857 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002858
Steve Narofff334b4e2009-09-02 18:26:48 +00002859 if (clang_isReference(C.kind)) {
2860 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002861 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002862 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002863 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002864 }
2865 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002866 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002867 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002868 }
2869 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002870 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002871 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002872 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002873 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002874 case CXCursor_CXXBaseSpecifier: {
2875 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2876 return createCXString(B->getType().getAsString());
2877 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002878 case CXCursor_TypeRef: {
2879 TypeDecl *Type = getCursorTypeRef(C).first;
2880 assert(Type && "Missing type decl");
2881
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002882 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2883 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002884 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002885 case CXCursor_TemplateRef: {
2886 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002887 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002888
2889 return createCXString(Template->getNameAsString());
2890 }
Douglas Gregor69319002010-08-31 23:48:11 +00002891
2892 case CXCursor_NamespaceRef: {
2893 NamedDecl *NS = getCursorNamespaceRef(C).first;
2894 assert(NS && "Missing namespace decl");
2895
2896 return createCXString(NS->getNameAsString());
2897 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002898
Douglas Gregora67e03f2010-09-09 21:42:20 +00002899 case CXCursor_MemberRef: {
2900 FieldDecl *Field = getCursorMemberRef(C).first;
2901 assert(Field && "Missing member decl");
2902
2903 return createCXString(Field->getNameAsString());
2904 }
2905
Douglas Gregor36897b02010-09-10 00:22:18 +00002906 case CXCursor_LabelRef: {
2907 LabelStmt *Label = getCursorLabelRef(C).first;
2908 assert(Label && "Missing label");
2909
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002910 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002911 }
2912
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002913 case CXCursor_OverloadedDeclRef: {
2914 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2915 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2916 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2917 return createCXString(ND->getNameAsString());
2918 return createCXString("");
2919 }
2920 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2921 return createCXString(E->getName().getAsString());
2922 OverloadedTemplateStorage *Ovl
2923 = Storage.get<OverloadedTemplateStorage*>();
2924 if (Ovl->size() == 0)
2925 return createCXString("");
2926 return createCXString((*Ovl->begin())->getNameAsString());
2927 }
2928
Daniel Dunbaracca7252009-11-30 20:42:49 +00002929 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002930 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002931 }
2932 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002933
2934 if (clang_isExpression(C.kind)) {
2935 Decl *D = getDeclFromExpr(getCursorExpr(C));
2936 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002937 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002938 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002939 }
2940
Douglas Gregor36897b02010-09-10 00:22:18 +00002941 if (clang_isStatement(C.kind)) {
2942 Stmt *S = getCursorStmt(C);
2943 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002944 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002945
2946 return createCXString("");
2947 }
2948
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002949 if (C.kind == CXCursor_MacroInstantiation)
2950 return createCXString(getCursorMacroInstantiation(C)->getName()
2951 ->getNameStart());
2952
Douglas Gregor572feb22010-03-18 18:04:21 +00002953 if (C.kind == CXCursor_MacroDefinition)
2954 return createCXString(getCursorMacroDefinition(C)->getName()
2955 ->getNameStart());
2956
Douglas Gregorecdcb882010-10-20 22:00:55 +00002957 if (C.kind == CXCursor_InclusionDirective)
2958 return createCXString(getCursorInclusionDirective(C)->getFileName());
2959
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002960 if (clang_isDeclaration(C.kind))
2961 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002962
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002963 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002964}
2965
Douglas Gregor358559d2010-10-02 22:49:11 +00002966CXString clang_getCursorDisplayName(CXCursor C) {
2967 if (!clang_isDeclaration(C.kind))
2968 return clang_getCursorSpelling(C);
2969
2970 Decl *D = getCursorDecl(C);
2971 if (!D)
2972 return createCXString("");
2973
2974 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2975 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2976 D = FunTmpl->getTemplatedDecl();
2977
2978 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2979 llvm::SmallString<64> Str;
2980 llvm::raw_svector_ostream OS(Str);
2981 OS << Function->getNameAsString();
2982 if (Function->getPrimaryTemplate())
2983 OS << "<>";
2984 OS << "(";
2985 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2986 if (I)
2987 OS << ", ";
2988 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2989 }
2990
2991 if (Function->isVariadic()) {
2992 if (Function->getNumParams())
2993 OS << ", ";
2994 OS << "...";
2995 }
2996 OS << ")";
2997 return createCXString(OS.str());
2998 }
2999
3000 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3001 llvm::SmallString<64> Str;
3002 llvm::raw_svector_ostream OS(Str);
3003 OS << ClassTemplate->getNameAsString();
3004 OS << "<";
3005 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3006 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3007 if (I)
3008 OS << ", ";
3009
3010 NamedDecl *Param = Params->getParam(I);
3011 if (Param->getIdentifier()) {
3012 OS << Param->getIdentifier()->getName();
3013 continue;
3014 }
3015
3016 // There is no parameter name, which makes this tricky. Try to come up
3017 // with something useful that isn't too long.
3018 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3019 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3020 else if (NonTypeTemplateParmDecl *NTTP
3021 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3022 OS << NTTP->getType().getAsString(Policy);
3023 else
3024 OS << "template<...> class";
3025 }
3026
3027 OS << ">";
3028 return createCXString(OS.str());
3029 }
3030
3031 if (ClassTemplateSpecializationDecl *ClassSpec
3032 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3033 // If the type was explicitly written, use that.
3034 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3035 return createCXString(TSInfo->getType().getAsString(Policy));
3036
3037 llvm::SmallString<64> Str;
3038 llvm::raw_svector_ostream OS(Str);
3039 OS << ClassSpec->getNameAsString();
3040 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003041 ClassSpec->getTemplateArgs().data(),
3042 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003043 Policy);
3044 return createCXString(OS.str());
3045 }
3046
3047 return clang_getCursorSpelling(C);
3048}
3049
Ted Kremeneke68fff62010-02-17 00:41:32 +00003050CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003051 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003052 case CXCursor_FunctionDecl:
3053 return createCXString("FunctionDecl");
3054 case CXCursor_TypedefDecl:
3055 return createCXString("TypedefDecl");
3056 case CXCursor_EnumDecl:
3057 return createCXString("EnumDecl");
3058 case CXCursor_EnumConstantDecl:
3059 return createCXString("EnumConstantDecl");
3060 case CXCursor_StructDecl:
3061 return createCXString("StructDecl");
3062 case CXCursor_UnionDecl:
3063 return createCXString("UnionDecl");
3064 case CXCursor_ClassDecl:
3065 return createCXString("ClassDecl");
3066 case CXCursor_FieldDecl:
3067 return createCXString("FieldDecl");
3068 case CXCursor_VarDecl:
3069 return createCXString("VarDecl");
3070 case CXCursor_ParmDecl:
3071 return createCXString("ParmDecl");
3072 case CXCursor_ObjCInterfaceDecl:
3073 return createCXString("ObjCInterfaceDecl");
3074 case CXCursor_ObjCCategoryDecl:
3075 return createCXString("ObjCCategoryDecl");
3076 case CXCursor_ObjCProtocolDecl:
3077 return createCXString("ObjCProtocolDecl");
3078 case CXCursor_ObjCPropertyDecl:
3079 return createCXString("ObjCPropertyDecl");
3080 case CXCursor_ObjCIvarDecl:
3081 return createCXString("ObjCIvarDecl");
3082 case CXCursor_ObjCInstanceMethodDecl:
3083 return createCXString("ObjCInstanceMethodDecl");
3084 case CXCursor_ObjCClassMethodDecl:
3085 return createCXString("ObjCClassMethodDecl");
3086 case CXCursor_ObjCImplementationDecl:
3087 return createCXString("ObjCImplementationDecl");
3088 case CXCursor_ObjCCategoryImplDecl:
3089 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003090 case CXCursor_CXXMethod:
3091 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003092 case CXCursor_UnexposedDecl:
3093 return createCXString("UnexposedDecl");
3094 case CXCursor_ObjCSuperClassRef:
3095 return createCXString("ObjCSuperClassRef");
3096 case CXCursor_ObjCProtocolRef:
3097 return createCXString("ObjCProtocolRef");
3098 case CXCursor_ObjCClassRef:
3099 return createCXString("ObjCClassRef");
3100 case CXCursor_TypeRef:
3101 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003102 case CXCursor_TemplateRef:
3103 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003104 case CXCursor_NamespaceRef:
3105 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003106 case CXCursor_MemberRef:
3107 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003108 case CXCursor_LabelRef:
3109 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003110 case CXCursor_OverloadedDeclRef:
3111 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003112 case CXCursor_UnexposedExpr:
3113 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003114 case CXCursor_BlockExpr:
3115 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003116 case CXCursor_DeclRefExpr:
3117 return createCXString("DeclRefExpr");
3118 case CXCursor_MemberRefExpr:
3119 return createCXString("MemberRefExpr");
3120 case CXCursor_CallExpr:
3121 return createCXString("CallExpr");
3122 case CXCursor_ObjCMessageExpr:
3123 return createCXString("ObjCMessageExpr");
3124 case CXCursor_UnexposedStmt:
3125 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003126 case CXCursor_LabelStmt:
3127 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003128 case CXCursor_InvalidFile:
3129 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003130 case CXCursor_InvalidCode:
3131 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003132 case CXCursor_NoDeclFound:
3133 return createCXString("NoDeclFound");
3134 case CXCursor_NotImplemented:
3135 return createCXString("NotImplemented");
3136 case CXCursor_TranslationUnit:
3137 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003138 case CXCursor_UnexposedAttr:
3139 return createCXString("UnexposedAttr");
3140 case CXCursor_IBActionAttr:
3141 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003142 case CXCursor_IBOutletAttr:
3143 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003144 case CXCursor_IBOutletCollectionAttr:
3145 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003146 case CXCursor_PreprocessingDirective:
3147 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003148 case CXCursor_MacroDefinition:
3149 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003150 case CXCursor_MacroInstantiation:
3151 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003152 case CXCursor_InclusionDirective:
3153 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003154 case CXCursor_Namespace:
3155 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003156 case CXCursor_LinkageSpec:
3157 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003158 case CXCursor_CXXBaseSpecifier:
3159 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003160 case CXCursor_Constructor:
3161 return createCXString("CXXConstructor");
3162 case CXCursor_Destructor:
3163 return createCXString("CXXDestructor");
3164 case CXCursor_ConversionFunction:
3165 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003166 case CXCursor_TemplateTypeParameter:
3167 return createCXString("TemplateTypeParameter");
3168 case CXCursor_NonTypeTemplateParameter:
3169 return createCXString("NonTypeTemplateParameter");
3170 case CXCursor_TemplateTemplateParameter:
3171 return createCXString("TemplateTemplateParameter");
3172 case CXCursor_FunctionTemplate:
3173 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003174 case CXCursor_ClassTemplate:
3175 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003176 case CXCursor_ClassTemplatePartialSpecialization:
3177 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003178 case CXCursor_NamespaceAlias:
3179 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003180 case CXCursor_UsingDirective:
3181 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003182 case CXCursor_UsingDeclaration:
3183 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003184 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003185
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003186 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003187 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003188}
Steve Naroff89922f82009-08-31 00:59:03 +00003189
Ted Kremeneke68fff62010-02-17 00:41:32 +00003190enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3191 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003192 CXClientData client_data) {
3193 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003194
3195 // If our current best cursor is the construction of a temporary object,
3196 // don't replace that cursor with a type reference, because we want
3197 // clang_getCursor() to point at the constructor.
3198 if (clang_isExpression(BestCursor->kind) &&
3199 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3200 cursor.kind == CXCursor_TypeRef)
3201 return CXChildVisit_Recurse;
3202
Douglas Gregor85fe1562010-12-10 07:23:11 +00003203 // Don't override a preprocessing cursor with another preprocessing
3204 // cursor; we want the outermost preprocessing cursor.
3205 if (clang_isPreprocessing(cursor.kind) &&
3206 clang_isPreprocessing(BestCursor->kind))
3207 return CXChildVisit_Recurse;
3208
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003209 *BestCursor = cursor;
3210 return CXChildVisit_Recurse;
3211}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003212
Douglas Gregorb9790342010-01-22 21:44:22 +00003213CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3214 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003215 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003216
Ted Kremeneka60ed472010-11-16 08:15:36 +00003217 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003218 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3219
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003220 // Translate the given source location to make it point at the beginning of
3221 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003222 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003223
3224 // Guard against an invalid SourceLocation, or we may assert in one
3225 // of the following calls.
3226 if (SLoc.isInvalid())
3227 return clang_getNullCursor();
3228
Douglas Gregor40749ee2010-11-03 00:35:38 +00003229 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003230 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3231 CXXUnit->getASTContext().getLangOptions());
3232
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003233 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3234 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003235 // FIXME: Would be great to have a "hint" cursor, then walk from that
3236 // hint cursor upward until we find a cursor whose source range encloses
3237 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003238 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3239 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003240 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003241 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003242 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003243
3244 if (Logging) {
3245 CXFile SearchFile;
3246 unsigned SearchLine, SearchColumn;
3247 CXFile ResultFile;
3248 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003249 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3250 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003251 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3252
3253 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3254 0);
3255 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3256 &ResultColumn, 0);
3257 SearchFileName = clang_getFileName(SearchFile);
3258 ResultFileName = clang_getFileName(ResultFile);
3259 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003260 USR = clang_getCursorUSR(Result);
3261 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003262 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3263 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003264 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3265 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003266 clang_disposeString(SearchFileName);
3267 clang_disposeString(ResultFileName);
3268 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003269 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003270
3271 CXCursor Definition = clang_getCursorDefinition(Result);
3272 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3273 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3274 CXString DefinitionKindSpelling
3275 = clang_getCursorKindSpelling(Definition.kind);
3276 CXFile DefinitionFile;
3277 unsigned DefinitionLine, DefinitionColumn;
3278 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3279 &DefinitionLine, &DefinitionColumn, 0);
3280 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3281 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3282 clang_getCString(DefinitionKindSpelling),
3283 clang_getCString(DefinitionFileName),
3284 DefinitionLine, DefinitionColumn);
3285 clang_disposeString(DefinitionFileName);
3286 clang_disposeString(DefinitionKindSpelling);
3287 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003288 }
3289
Ted Kremeneke68fff62010-02-17 00:41:32 +00003290 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003291}
3292
Ted Kremenek73885552009-11-17 19:28:59 +00003293CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003294 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003295}
3296
3297unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003298 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003299}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003300
Douglas Gregor9ce55842010-11-20 00:09:34 +00003301unsigned clang_hashCursor(CXCursor C) {
3302 unsigned Index = 0;
3303 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3304 Index = 1;
3305
3306 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3307 std::make_pair(C.kind, C.data[Index]));
3308}
3309
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003310unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003311 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3312}
3313
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003314unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003315 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3316}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003317
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003318unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003319 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3320}
3321
Douglas Gregor97b98722010-01-19 23:20:36 +00003322unsigned clang_isExpression(enum CXCursorKind K) {
3323 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3324}
3325
3326unsigned clang_isStatement(enum CXCursorKind K) {
3327 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3328}
3329
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003330unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3331 return K == CXCursor_TranslationUnit;
3332}
3333
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003334unsigned clang_isPreprocessing(enum CXCursorKind K) {
3335 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3336}
3337
Ted Kremenekad6eff62010-03-08 21:17:29 +00003338unsigned clang_isUnexposed(enum CXCursorKind K) {
3339 switch (K) {
3340 case CXCursor_UnexposedDecl:
3341 case CXCursor_UnexposedExpr:
3342 case CXCursor_UnexposedStmt:
3343 case CXCursor_UnexposedAttr:
3344 return true;
3345 default:
3346 return false;
3347 }
3348}
3349
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003350CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003351 return C.kind;
3352}
3353
Douglas Gregor98258af2010-01-18 22:46:11 +00003354CXSourceLocation clang_getCursorLocation(CXCursor C) {
3355 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003356 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003357 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003358 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3359 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003360 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003361 }
3362
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003363 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003364 std::pair<ObjCProtocolDecl *, SourceLocation> P
3365 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003366 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003367 }
3368
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003369 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003370 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3371 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003372 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003373 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003374
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003375 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003376 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003377 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003378 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003379
3380 case CXCursor_TemplateRef: {
3381 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3382 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3383 }
3384
Douglas Gregor69319002010-08-31 23:48:11 +00003385 case CXCursor_NamespaceRef: {
3386 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3387 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3388 }
3389
Douglas Gregora67e03f2010-09-09 21:42:20 +00003390 case CXCursor_MemberRef: {
3391 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3392 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3393 }
3394
Ted Kremenek3064ef92010-08-27 21:34:58 +00003395 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003396 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3397 if (!BaseSpec)
3398 return clang_getNullLocation();
3399
3400 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3401 return cxloc::translateSourceLocation(getCursorContext(C),
3402 TSInfo->getTypeLoc().getBeginLoc());
3403
3404 return cxloc::translateSourceLocation(getCursorContext(C),
3405 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003406 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003407
Douglas Gregor36897b02010-09-10 00:22:18 +00003408 case CXCursor_LabelRef: {
3409 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3410 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3411 }
3412
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003413 case CXCursor_OverloadedDeclRef:
3414 return cxloc::translateSourceLocation(getCursorContext(C),
3415 getCursorOverloadedDeclRef(C).second);
3416
Douglas Gregorf46034a2010-01-18 23:41:10 +00003417 default:
3418 // FIXME: Need a way to enumerate all non-reference cases.
3419 llvm_unreachable("Missed a reference kind");
3420 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003421 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003422
3423 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003424 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003425 getLocationFromExpr(getCursorExpr(C)));
3426
Douglas Gregor36897b02010-09-10 00:22:18 +00003427 if (clang_isStatement(C.kind))
3428 return cxloc::translateSourceLocation(getCursorContext(C),
3429 getCursorStmt(C)->getLocStart());
3430
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003431 if (C.kind == CXCursor_PreprocessingDirective) {
3432 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3433 return cxloc::translateSourceLocation(getCursorContext(C), L);
3434 }
Douglas Gregor48072312010-03-18 15:23:44 +00003435
3436 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003437 SourceLocation L
3438 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003439 return cxloc::translateSourceLocation(getCursorContext(C), L);
3440 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003441
3442 if (C.kind == CXCursor_MacroDefinition) {
3443 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3444 return cxloc::translateSourceLocation(getCursorContext(C), L);
3445 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003446
3447 if (C.kind == CXCursor_InclusionDirective) {
3448 SourceLocation L
3449 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3450 return cxloc::translateSourceLocation(getCursorContext(C), L);
3451 }
3452
Ted Kremenek9a700d22010-05-12 06:16:13 +00003453 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003454 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003455
Douglas Gregorf46034a2010-01-18 23:41:10 +00003456 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003457 SourceLocation Loc = D->getLocation();
3458 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3459 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003460 // FIXME: Multiple variables declared in a single declaration
3461 // currently lack the information needed to correctly determine their
3462 // ranges when accounting for the type-specifier. We use context
3463 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3464 // and if so, whether it is the first decl.
3465 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3466 if (!cxcursor::isFirstInDeclGroup(C))
3467 Loc = VD->getLocation();
3468 }
3469
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003470 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003471}
Douglas Gregora7bde202010-01-19 00:34:46 +00003472
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003473} // end extern "C"
3474
3475static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003476 if (clang_isReference(C.kind)) {
3477 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003478 case CXCursor_ObjCSuperClassRef:
3479 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003480
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003481 case CXCursor_ObjCProtocolRef:
3482 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003483
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003484 case CXCursor_ObjCClassRef:
3485 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003486
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003487 case CXCursor_TypeRef:
3488 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003489
3490 case CXCursor_TemplateRef:
3491 return getCursorTemplateRef(C).second;
3492
Douglas Gregor69319002010-08-31 23:48:11 +00003493 case CXCursor_NamespaceRef:
3494 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003495
3496 case CXCursor_MemberRef:
3497 return getCursorMemberRef(C).second;
3498
Ted Kremenek3064ef92010-08-27 21:34:58 +00003499 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003500 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003501
Douglas Gregor36897b02010-09-10 00:22:18 +00003502 case CXCursor_LabelRef:
3503 return getCursorLabelRef(C).second;
3504
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003505 case CXCursor_OverloadedDeclRef:
3506 return getCursorOverloadedDeclRef(C).second;
3507
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003508 default:
3509 // FIXME: Need a way to enumerate all non-reference cases.
3510 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003511 }
3512 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003513
3514 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003515 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003516
3517 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003518 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003519
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003520 if (C.kind == CXCursor_PreprocessingDirective)
3521 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003522
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003523 if (C.kind == CXCursor_MacroInstantiation)
3524 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003525
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003526 if (C.kind == CXCursor_MacroDefinition)
3527 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003528
3529 if (C.kind == CXCursor_InclusionDirective)
3530 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3531
Ted Kremenek007a7c92010-11-01 23:26:51 +00003532 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3533 Decl *D = cxcursor::getCursorDecl(C);
3534 SourceRange R = D->getSourceRange();
3535 // FIXME: Multiple variables declared in a single declaration
3536 // currently lack the information needed to correctly determine their
3537 // ranges when accounting for the type-specifier. We use context
3538 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3539 // and if so, whether it is the first decl.
3540 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3541 if (!cxcursor::isFirstInDeclGroup(C))
3542 R.setBegin(VD->getLocation());
3543 }
3544 return R;
3545 }
Douglas Gregor66537982010-11-17 17:14:07 +00003546 return SourceRange();
3547}
3548
3549/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3550/// the decl-specifier-seq for declarations.
3551static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3552 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3553 Decl *D = cxcursor::getCursorDecl(C);
3554 SourceRange R = D->getSourceRange();
3555
3556 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3557 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3558 TypeLoc TL = TI->getTypeLoc();
3559 SourceLocation TLoc = TL.getSourceRange().getBegin();
3560 if (TLoc.isValid() && R.getBegin().isValid() &&
3561 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3562 R.setBegin(TLoc);
3563 }
3564
3565 // FIXME: Multiple variables declared in a single declaration
3566 // currently lack the information needed to correctly determine their
3567 // ranges when accounting for the type-specifier. We use context
3568 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3569 // and if so, whether it is the first decl.
3570 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3571 if (!cxcursor::isFirstInDeclGroup(C))
3572 R.setBegin(VD->getLocation());
3573 }
3574 }
3575
3576 return R;
3577 }
3578
3579 return getRawCursorExtent(C);
3580}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003581
3582extern "C" {
3583
3584CXSourceRange clang_getCursorExtent(CXCursor C) {
3585 SourceRange R = getRawCursorExtent(C);
3586 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003587 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003588
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003589 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003590}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003591
3592CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003593 if (clang_isInvalid(C.kind))
3594 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003595
Ted Kremeneka60ed472010-11-16 08:15:36 +00003596 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003597 if (clang_isDeclaration(C.kind)) {
3598 Decl *D = getCursorDecl(C);
3599 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003600 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003601 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003602 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003603 if (ObjCForwardProtocolDecl *Protocols
3604 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003605 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003606 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3607 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3608 return MakeCXCursor(Property, tu);
3609
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003610 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003611 }
3612
Douglas Gregor97b98722010-01-19 23:20:36 +00003613 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003614 Expr *E = getCursorExpr(C);
3615 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003616 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003617 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003618
3619 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003620 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003621
Douglas Gregor97b98722010-01-19 23:20:36 +00003622 return clang_getNullCursor();
3623 }
3624
Douglas Gregor36897b02010-09-10 00:22:18 +00003625 if (clang_isStatement(C.kind)) {
3626 Stmt *S = getCursorStmt(C);
3627 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003628 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003629
3630 return clang_getNullCursor();
3631 }
3632
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003633 if (C.kind == CXCursor_MacroInstantiation) {
3634 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003635 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003636 }
3637
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003638 if (!clang_isReference(C.kind))
3639 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003640
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003641 switch (C.kind) {
3642 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003643 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003644
3645 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003646 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003647
3648 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003649 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003650
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003651 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003652 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003653
3654 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003655 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003656
Douglas Gregor69319002010-08-31 23:48:11 +00003657 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003658 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003659
Douglas Gregora67e03f2010-09-09 21:42:20 +00003660 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003661 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003662
Ted Kremenek3064ef92010-08-27 21:34:58 +00003663 case CXCursor_CXXBaseSpecifier: {
3664 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3665 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003666 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003667 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003668
Douglas Gregor36897b02010-09-10 00:22:18 +00003669 case CXCursor_LabelRef:
3670 // FIXME: We end up faking the "parent" declaration here because we
3671 // don't want to make CXCursor larger.
3672 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003673 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3674 .getTranslationUnitDecl(),
3675 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003676
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003677 case CXCursor_OverloadedDeclRef:
3678 return C;
3679
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003680 default:
3681 // We would prefer to enumerate all non-reference cursor kinds here.
3682 llvm_unreachable("Unhandled reference cursor kind");
3683 break;
3684 }
3685 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003686
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003687 return clang_getNullCursor();
3688}
3689
Douglas Gregorb6998662010-01-19 19:34:47 +00003690CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003691 if (clang_isInvalid(C.kind))
3692 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003693
Ted Kremeneka60ed472010-11-16 08:15:36 +00003694 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003695
Douglas Gregorb6998662010-01-19 19:34:47 +00003696 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003697 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003698 C = clang_getCursorReferenced(C);
3699 WasReference = true;
3700 }
3701
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003702 if (C.kind == CXCursor_MacroInstantiation)
3703 return clang_getCursorReferenced(C);
3704
Douglas Gregorb6998662010-01-19 19:34:47 +00003705 if (!clang_isDeclaration(C.kind))
3706 return clang_getNullCursor();
3707
3708 Decl *D = getCursorDecl(C);
3709 if (!D)
3710 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003711
Douglas Gregorb6998662010-01-19 19:34:47 +00003712 switch (D->getKind()) {
3713 // Declaration kinds that don't really separate the notions of
3714 // declaration and definition.
3715 case Decl::Namespace:
3716 case Decl::Typedef:
3717 case Decl::TemplateTypeParm:
3718 case Decl::EnumConstant:
3719 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003720 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003721 case Decl::ObjCIvar:
3722 case Decl::ObjCAtDefsField:
3723 case Decl::ImplicitParam:
3724 case Decl::ParmVar:
3725 case Decl::NonTypeTemplateParm:
3726 case Decl::TemplateTemplateParm:
3727 case Decl::ObjCCategoryImpl:
3728 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003729 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003730 case Decl::LinkageSpec:
3731 case Decl::ObjCPropertyImpl:
3732 case Decl::FileScopeAsm:
3733 case Decl::StaticAssert:
3734 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003735 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003736 return C;
3737
3738 // Declaration kinds that don't make any sense here, but are
3739 // nonetheless harmless.
3740 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003741 break;
3742
3743 // Declaration kinds for which the definition is not resolvable.
3744 case Decl::UnresolvedUsingTypename:
3745 case Decl::UnresolvedUsingValue:
3746 break;
3747
3748 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003749 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003750 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003751
3752 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003753 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003754
3755 case Decl::Enum:
3756 case Decl::Record:
3757 case Decl::CXXRecord:
3758 case Decl::ClassTemplateSpecialization:
3759 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003760 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003761 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003762 return clang_getNullCursor();
3763
3764 case Decl::Function:
3765 case Decl::CXXMethod:
3766 case Decl::CXXConstructor:
3767 case Decl::CXXDestructor:
3768 case Decl::CXXConversion: {
3769 const FunctionDecl *Def = 0;
3770 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003771 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003772 return clang_getNullCursor();
3773 }
3774
3775 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003776 // Ask the variable if it has a definition.
3777 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003778 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003779 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003780 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003781
Douglas Gregorb6998662010-01-19 19:34:47 +00003782 case Decl::FunctionTemplate: {
3783 const FunctionDecl *Def = 0;
3784 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003785 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003786 return clang_getNullCursor();
3787 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003788
Douglas Gregorb6998662010-01-19 19:34:47 +00003789 case Decl::ClassTemplate: {
3790 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003791 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003792 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003793 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003794 return clang_getNullCursor();
3795 }
3796
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003797 case Decl::Using:
3798 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003799 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003800
3801 case Decl::UsingShadow:
3802 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003803 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003804 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003805
3806 case Decl::ObjCMethod: {
3807 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3808 if (Method->isThisDeclarationADefinition())
3809 return C;
3810
3811 // Dig out the method definition in the associated
3812 // @implementation, if we have it.
3813 // FIXME: The ASTs should make finding the definition easier.
3814 if (ObjCInterfaceDecl *Class
3815 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3816 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3817 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3818 Method->isInstanceMethod()))
3819 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003820 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003821
3822 return clang_getNullCursor();
3823 }
3824
3825 case Decl::ObjCCategory:
3826 if (ObjCCategoryImplDecl *Impl
3827 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003828 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003829 return clang_getNullCursor();
3830
3831 case Decl::ObjCProtocol:
3832 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3833 return C;
3834 return clang_getNullCursor();
3835
3836 case Decl::ObjCInterface:
3837 // There are two notions of a "definition" for an Objective-C
3838 // class: the interface and its implementation. When we resolved a
3839 // reference to an Objective-C class, produce the @interface as
3840 // the definition; when we were provided with the interface,
3841 // produce the @implementation as the definition.
3842 if (WasReference) {
3843 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3844 return C;
3845 } else if (ObjCImplementationDecl *Impl
3846 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003847 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003848 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003849
Douglas Gregorb6998662010-01-19 19:34:47 +00003850 case Decl::ObjCProperty:
3851 // FIXME: We don't really know where to find the
3852 // ObjCPropertyImplDecls that implement this property.
3853 return clang_getNullCursor();
3854
3855 case Decl::ObjCCompatibleAlias:
3856 if (ObjCInterfaceDecl *Class
3857 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3858 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003859 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003860
Douglas Gregorb6998662010-01-19 19:34:47 +00003861 return clang_getNullCursor();
3862
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003863 case Decl::ObjCForwardProtocol:
3864 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003865 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003866
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003867 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003868 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003869 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003870
3871 case Decl::Friend:
3872 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003873 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003874 return clang_getNullCursor();
3875
3876 case Decl::FriendTemplate:
3877 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003878 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003879 return clang_getNullCursor();
3880 }
3881
3882 return clang_getNullCursor();
3883}
3884
3885unsigned clang_isCursorDefinition(CXCursor C) {
3886 if (!clang_isDeclaration(C.kind))
3887 return 0;
3888
3889 return clang_getCursorDefinition(C) == C;
3890}
3891
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003892CXCursor clang_getCanonicalCursor(CXCursor C) {
3893 if (!clang_isDeclaration(C.kind))
3894 return C;
3895
3896 if (Decl *D = getCursorDecl(C))
3897 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3898
3899 return C;
3900}
3901
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003902unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003903 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003904 return 0;
3905
3906 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3907 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3908 return E->getNumDecls();
3909
3910 if (OverloadedTemplateStorage *S
3911 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3912 return S->size();
3913
3914 Decl *D = Storage.get<Decl*>();
3915 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003916 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003917 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3918 return Classes->size();
3919 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3920 return Protocols->protocol_size();
3921
3922 return 0;
3923}
3924
3925CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003926 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003927 return clang_getNullCursor();
3928
3929 if (index >= clang_getNumOverloadedDecls(cursor))
3930 return clang_getNullCursor();
3931
Ted Kremeneka60ed472010-11-16 08:15:36 +00003932 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003933 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3934 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003935 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003936
3937 if (OverloadedTemplateStorage *S
3938 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003939 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003940
3941 Decl *D = Storage.get<Decl*>();
3942 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3943 // FIXME: This is, unfortunately, linear time.
3944 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3945 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003946 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003947 }
3948
3949 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003950 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003951
3952 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003953 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003954
3955 return clang_getNullCursor();
3956}
3957
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003958void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003959 const char **startBuf,
3960 const char **endBuf,
3961 unsigned *startLine,
3962 unsigned *startColumn,
3963 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003964 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003965 assert(getCursorDecl(C) && "CXCursor has null decl");
3966 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003967 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3968 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003969
Steve Naroff4ade6d62009-09-23 17:52:52 +00003970 SourceManager &SM = FD->getASTContext().getSourceManager();
3971 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3972 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3973 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3974 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3975 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3976 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3977}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003978
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003979void clang_enableStackTraces(void) {
3980 llvm::sys::PrintStackTraceOnErrorSignal();
3981}
3982
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003983void clang_executeOnThread(void (*fn)(void*), void *user_data,
3984 unsigned stack_size) {
3985 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3986}
3987
Ted Kremenekfb480492010-01-13 21:46:36 +00003988} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003989
Ted Kremenekfb480492010-01-13 21:46:36 +00003990//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003991// Token-based Operations.
3992//===----------------------------------------------------------------------===//
3993
3994/* CXToken layout:
3995 * int_data[0]: a CXTokenKind
3996 * int_data[1]: starting token location
3997 * int_data[2]: token length
3998 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003999 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004000 * otherwise unused.
4001 */
4002extern "C" {
4003
4004CXTokenKind clang_getTokenKind(CXToken CXTok) {
4005 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4006}
4007
4008CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4009 switch (clang_getTokenKind(CXTok)) {
4010 case CXToken_Identifier:
4011 case CXToken_Keyword:
4012 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004013 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4014 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004015
4016 case CXToken_Literal: {
4017 // We have stashed the starting pointer in the ptr_data field. Use it.
4018 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004019 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004020 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004021
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004022 case CXToken_Punctuation:
4023 case CXToken_Comment:
4024 break;
4025 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004026
4027 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004028 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004029 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004030 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004031 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004032
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004033 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4034 std::pair<FileID, unsigned> LocInfo
4035 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004036 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004037 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004038 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4039 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004040 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004041
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004042 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004043}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004044
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004045CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004046 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004047 if (!CXXUnit)
4048 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004049
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004050 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4051 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4052}
4053
4054CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004055 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004056 if (!CXXUnit)
4057 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004058
4059 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004060 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4061}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004062
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004063void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4064 CXToken **Tokens, unsigned *NumTokens) {
4065 if (Tokens)
4066 *Tokens = 0;
4067 if (NumTokens)
4068 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004069
Ted Kremeneka60ed472010-11-16 08:15:36 +00004070 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004071 if (!CXXUnit || !Tokens || !NumTokens)
4072 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004073
Douglas Gregorbdf60622010-03-05 21:16:25 +00004074 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4075
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004076 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004077 if (R.isInvalid())
4078 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004079
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004080 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4081 std::pair<FileID, unsigned> BeginLocInfo
4082 = SourceMgr.getDecomposedLoc(R.getBegin());
4083 std::pair<FileID, unsigned> EndLocInfo
4084 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004085
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004086 // Cannot tokenize across files.
4087 if (BeginLocInfo.first != EndLocInfo.first)
4088 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004089
4090 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004091 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004092 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004093 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004094 if (Invalid)
4095 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004096
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004097 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4098 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004099 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004100 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004101
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004102 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004103 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004104 llvm::SmallVector<CXToken, 32> CXTokens;
4105 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004106 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004107 do {
4108 // Lex the next token
4109 Lex.LexFromRawLexer(Tok);
4110 if (Tok.is(tok::eof))
4111 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004112
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004113 // Initialize the CXToken.
4114 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004115
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004116 // - Common fields
4117 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4118 CXTok.int_data[2] = Tok.getLength();
4119 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004120
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004121 // - Kind-specific fields
4122 if (Tok.isLiteral()) {
4123 CXTok.int_data[0] = CXToken_Literal;
4124 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004125 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004126 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004127 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004128 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004129
David Chisnall096428b2010-10-13 21:44:48 +00004130 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004131 CXTok.int_data[0] = CXToken_Keyword;
4132 }
4133 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004134 CXTok.int_data[0] = Tok.is(tok::identifier)
4135 ? CXToken_Identifier
4136 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004137 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004138 CXTok.ptr_data = II;
4139 } else if (Tok.is(tok::comment)) {
4140 CXTok.int_data[0] = CXToken_Comment;
4141 CXTok.ptr_data = 0;
4142 } else {
4143 CXTok.int_data[0] = CXToken_Punctuation;
4144 CXTok.ptr_data = 0;
4145 }
4146 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004147 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004148 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004149
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004150 if (CXTokens.empty())
4151 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004152
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004153 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4154 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4155 *NumTokens = CXTokens.size();
4156}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004157
Ted Kremenek6db61092010-05-05 00:55:15 +00004158void clang_disposeTokens(CXTranslationUnit TU,
4159 CXToken *Tokens, unsigned NumTokens) {
4160 free(Tokens);
4161}
4162
4163} // end: extern "C"
4164
4165//===----------------------------------------------------------------------===//
4166// Token annotation APIs.
4167//===----------------------------------------------------------------------===//
4168
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004169typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004170static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4171 CXCursor parent,
4172 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004173namespace {
4174class AnnotateTokensWorker {
4175 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004176 CXToken *Tokens;
4177 CXCursor *Cursors;
4178 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004179 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004180 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004181 CursorVisitor AnnotateVis;
4182 SourceManager &SrcMgr;
4183
4184 bool MoreTokens() const { return TokIdx < NumTokens; }
4185 unsigned NextToken() const { return TokIdx; }
4186 void AdvanceToken() { ++TokIdx; }
4187 SourceLocation GetTokenLoc(unsigned tokI) {
4188 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4189 }
4190
Ted Kremenek6db61092010-05-05 00:55:15 +00004191public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004192 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004193 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004194 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004195 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004196 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004197 AnnotateVis(tu,
4198 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004199 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004200 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004201
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004202 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004203 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004204 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004205 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004206 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004207 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004208};
4209}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004210
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004211void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4212 // Walk the AST within the region of interest, annotating tokens
4213 // along the way.
4214 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004215
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004216 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4217 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004218 if (Pos != Annotated.end() &&
4219 (clang_isInvalid(Cursors[I].kind) ||
4220 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004221 Cursors[I] = Pos->second;
4222 }
4223
4224 // Finish up annotating any tokens left.
4225 if (!MoreTokens())
4226 return;
4227
4228 const CXCursor &C = clang_getNullCursor();
4229 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4230 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4231 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004232 }
4233}
4234
Ted Kremenek6db61092010-05-05 00:55:15 +00004235enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004236AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004237 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004238 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004239 if (cursorRange.isInvalid())
4240 return CXChildVisit_Recurse;
4241
Douglas Gregor4419b672010-10-21 06:10:04 +00004242 if (clang_isPreprocessing(cursor.kind)) {
4243 // For macro instantiations, just note where the beginning of the macro
4244 // instantiation occurs.
4245 if (cursor.kind == CXCursor_MacroInstantiation) {
4246 Annotated[Loc.int_data] = cursor;
4247 return CXChildVisit_Recurse;
4248 }
4249
Douglas Gregor4419b672010-10-21 06:10:04 +00004250 // Items in the preprocessing record are kept separate from items in
4251 // declarations, so we keep a separate token index.
4252 unsigned SavedTokIdx = TokIdx;
4253 TokIdx = PreprocessingTokIdx;
4254
4255 // Skip tokens up until we catch up to the beginning of the preprocessing
4256 // entry.
4257 while (MoreTokens()) {
4258 const unsigned I = NextToken();
4259 SourceLocation TokLoc = GetTokenLoc(I);
4260 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4261 case RangeBefore:
4262 AdvanceToken();
4263 continue;
4264 case RangeAfter:
4265 case RangeOverlap:
4266 break;
4267 }
4268 break;
4269 }
4270
4271 // Look at all of the tokens within this range.
4272 while (MoreTokens()) {
4273 const unsigned I = NextToken();
4274 SourceLocation TokLoc = GetTokenLoc(I);
4275 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4276 case RangeBefore:
4277 assert(0 && "Infeasible");
4278 case RangeAfter:
4279 break;
4280 case RangeOverlap:
4281 Cursors[I] = cursor;
4282 AdvanceToken();
4283 continue;
4284 }
4285 break;
4286 }
4287
4288 // Save the preprocessing token index; restore the non-preprocessing
4289 // token index.
4290 PreprocessingTokIdx = TokIdx;
4291 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004292 return CXChildVisit_Recurse;
4293 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004294
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004295 if (cursorRange.isInvalid())
4296 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004297
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004298 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4299
Ted Kremeneka333c662010-05-12 05:29:33 +00004300 // Adjust the annotated range based specific declarations.
4301 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4302 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004303 Decl *D = cxcursor::getCursorDecl(cursor);
4304 // Don't visit synthesized ObjC methods, since they have no syntatic
4305 // representation in the source.
4306 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4307 if (MD->isSynthesized())
4308 return CXChildVisit_Continue;
4309 }
4310 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004311 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4312 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004313 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004314 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004315 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004316 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004317 }
4318 }
4319 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004320
Ted Kremenek3f404602010-08-14 01:14:06 +00004321 // If the location of the cursor occurs within a macro instantiation, record
4322 // the spelling location of the cursor in our annotation map. We can then
4323 // paper over the token labelings during a post-processing step to try and
4324 // get cursor mappings for tokens that are the *arguments* of a macro
4325 // instantiation.
4326 if (L.isMacroID()) {
4327 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4328 // Only invalidate the old annotation if it isn't part of a preprocessing
4329 // directive. Here we assume that the default construction of CXCursor
4330 // results in CXCursor.kind being an initialized value (i.e., 0). If
4331 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004332
Ted Kremenek3f404602010-08-14 01:14:06 +00004333 CXCursor &oldC = Annotated[rawEncoding];
4334 if (!clang_isPreprocessing(oldC.kind))
4335 oldC = cursor;
4336 }
4337
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004338 const enum CXCursorKind K = clang_getCursorKind(parent);
4339 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004340 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4341 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004342
4343 while (MoreTokens()) {
4344 const unsigned I = NextToken();
4345 SourceLocation TokLoc = GetTokenLoc(I);
4346 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4347 case RangeBefore:
4348 Cursors[I] = updateC;
4349 AdvanceToken();
4350 continue;
4351 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004352 case RangeOverlap:
4353 break;
4354 }
4355 break;
4356 }
4357
4358 // Visit children to get their cursor information.
4359 const unsigned BeforeChildren = NextToken();
4360 VisitChildren(cursor);
4361 const unsigned AfterChildren = NextToken();
4362
4363 // Adjust 'Last' to the last token within the extent of the cursor.
4364 while (MoreTokens()) {
4365 const unsigned I = NextToken();
4366 SourceLocation TokLoc = GetTokenLoc(I);
4367 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4368 case RangeBefore:
4369 assert(0 && "Infeasible");
4370 case RangeAfter:
4371 break;
4372 case RangeOverlap:
4373 Cursors[I] = updateC;
4374 AdvanceToken();
4375 continue;
4376 }
4377 break;
4378 }
4379 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004380
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004381 // Scan the tokens that are at the beginning of the cursor, but are not
4382 // capture by the child cursors.
4383
4384 // For AST elements within macros, rely on a post-annotate pass to
4385 // to correctly annotate the tokens with cursors. Otherwise we can
4386 // get confusing results of having tokens that map to cursors that really
4387 // are expanded by an instantiation.
4388 if (L.isMacroID())
4389 cursor = clang_getNullCursor();
4390
4391 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4392 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4393 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004394
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004395 Cursors[I] = cursor;
4396 }
4397 // Scan the tokens that are at the end of the cursor, but are not captured
4398 // but the child cursors.
4399 for (unsigned I = AfterChildren; I != Last; ++I)
4400 Cursors[I] = cursor;
4401
4402 TokIdx = Last;
4403 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004404}
4405
Ted Kremenek6db61092010-05-05 00:55:15 +00004406static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4407 CXCursor parent,
4408 CXClientData client_data) {
4409 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4410}
4411
Ted Kremenekab979612010-11-11 08:05:23 +00004412// This gets run a separate thread to avoid stack blowout.
4413static void runAnnotateTokensWorker(void *UserData) {
4414 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4415}
4416
Ted Kremenek6db61092010-05-05 00:55:15 +00004417extern "C" {
4418
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004419void clang_annotateTokens(CXTranslationUnit TU,
4420 CXToken *Tokens, unsigned NumTokens,
4421 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004422
4423 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004424 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004425
Douglas Gregor4419b672010-10-21 06:10:04 +00004426 // Any token we don't specifically annotate will have a NULL cursor.
4427 CXCursor C = clang_getNullCursor();
4428 for (unsigned I = 0; I != NumTokens; ++I)
4429 Cursors[I] = C;
4430
Ted Kremeneka60ed472010-11-16 08:15:36 +00004431 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004432 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004433 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004434
Douglas Gregorbdf60622010-03-05 21:16:25 +00004435 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004436
Douglas Gregor0396f462010-03-19 05:22:59 +00004437 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004438 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004439 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4440 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004441 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4442 clang_getTokenLocation(TU,
4443 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004444
Douglas Gregor0396f462010-03-19 05:22:59 +00004445 // A mapping from the source locations found when re-lexing or traversing the
4446 // region of interest to the corresponding cursors.
4447 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004448
4449 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004450 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004451 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4452 std::pair<FileID, unsigned> BeginLocInfo
4453 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4454 std::pair<FileID, unsigned> EndLocInfo
4455 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004456
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004457 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004458 bool Invalid = false;
4459 if (BeginLocInfo.first == EndLocInfo.first &&
4460 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4461 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004462 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4463 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004464 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004465 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004466 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004467
4468 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004469 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004470 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004471 Token Tok;
4472 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004473
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004474 reprocess:
4475 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4476 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004477 // don't see it while preprocessing these tokens later, but keep track
4478 // of all of the token locations inside this preprocessing directive so
4479 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004480 //
4481 // FIXME: Some simple tests here could identify macro definitions and
4482 // #undefs, to provide specific cursor kinds for those.
4483 std::vector<SourceLocation> Locations;
4484 do {
4485 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004486 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004487 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004488
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004489 using namespace cxcursor;
4490 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004491 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4492 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004493 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004494 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4495 Annotated[Locations[I].getRawEncoding()] = Cursor;
4496 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004497
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004498 if (Tok.isAtStartOfLine())
4499 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004500
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004501 continue;
4502 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004503
Douglas Gregor48072312010-03-18 15:23:44 +00004504 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004505 break;
4506 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004507 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004508
Douglas Gregor0396f462010-03-19 05:22:59 +00004509 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004510 // a specific cursor.
4511 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004512 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004513
4514 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004515 // FIXME: We use a ridiculous stack size here because the data-recursion
4516 // algorithm uses a large stack frame than the non-data recursive version,
4517 // and AnnotationTokensWorker currently transforms the data-recursion
4518 // algorithm back into a traditional recursion by explicitly calling
4519 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004520 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004521 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4522 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004523 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4524 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004525}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004526} // end: extern "C"
4527
4528//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004529// Operations for querying linkage of a cursor.
4530//===----------------------------------------------------------------------===//
4531
4532extern "C" {
4533CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004534 if (!clang_isDeclaration(cursor.kind))
4535 return CXLinkage_Invalid;
4536
Ted Kremenek16b42592010-03-03 06:36:57 +00004537 Decl *D = cxcursor::getCursorDecl(cursor);
4538 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4539 switch (ND->getLinkage()) {
4540 case NoLinkage: return CXLinkage_NoLinkage;
4541 case InternalLinkage: return CXLinkage_Internal;
4542 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4543 case ExternalLinkage: return CXLinkage_External;
4544 };
4545
4546 return CXLinkage_Invalid;
4547}
4548} // end: extern "C"
4549
4550//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004551// Operations for querying language of a cursor.
4552//===----------------------------------------------------------------------===//
4553
4554static CXLanguageKind getDeclLanguage(const Decl *D) {
4555 switch (D->getKind()) {
4556 default:
4557 break;
4558 case Decl::ImplicitParam:
4559 case Decl::ObjCAtDefsField:
4560 case Decl::ObjCCategory:
4561 case Decl::ObjCCategoryImpl:
4562 case Decl::ObjCClass:
4563 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004564 case Decl::ObjCForwardProtocol:
4565 case Decl::ObjCImplementation:
4566 case Decl::ObjCInterface:
4567 case Decl::ObjCIvar:
4568 case Decl::ObjCMethod:
4569 case Decl::ObjCProperty:
4570 case Decl::ObjCPropertyImpl:
4571 case Decl::ObjCProtocol:
4572 return CXLanguage_ObjC;
4573 case Decl::CXXConstructor:
4574 case Decl::CXXConversion:
4575 case Decl::CXXDestructor:
4576 case Decl::CXXMethod:
4577 case Decl::CXXRecord:
4578 case Decl::ClassTemplate:
4579 case Decl::ClassTemplatePartialSpecialization:
4580 case Decl::ClassTemplateSpecialization:
4581 case Decl::Friend:
4582 case Decl::FriendTemplate:
4583 case Decl::FunctionTemplate:
4584 case Decl::LinkageSpec:
4585 case Decl::Namespace:
4586 case Decl::NamespaceAlias:
4587 case Decl::NonTypeTemplateParm:
4588 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004589 case Decl::TemplateTemplateParm:
4590 case Decl::TemplateTypeParm:
4591 case Decl::UnresolvedUsingTypename:
4592 case Decl::UnresolvedUsingValue:
4593 case Decl::Using:
4594 case Decl::UsingDirective:
4595 case Decl::UsingShadow:
4596 return CXLanguage_CPlusPlus;
4597 }
4598
4599 return CXLanguage_C;
4600}
4601
4602extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004603
4604enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4605 if (clang_isDeclaration(cursor.kind))
4606 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4607 if (D->hasAttr<UnavailableAttr>() ||
4608 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4609 return CXAvailability_Available;
4610
4611 if (D->hasAttr<DeprecatedAttr>())
4612 return CXAvailability_Deprecated;
4613 }
4614
4615 return CXAvailability_Available;
4616}
4617
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004618CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4619 if (clang_isDeclaration(cursor.kind))
4620 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4621
4622 return CXLanguage_Invalid;
4623}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004624
4625 /// \brief If the given cursor is the "templated" declaration
4626 /// descibing a class or function template, return the class or
4627 /// function template.
4628static Decl *maybeGetTemplateCursor(Decl *D) {
4629 if (!D)
4630 return 0;
4631
4632 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4633 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4634 return FunTmpl;
4635
4636 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4637 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4638 return ClassTmpl;
4639
4640 return D;
4641}
4642
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004643CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4644 if (clang_isDeclaration(cursor.kind)) {
4645 if (Decl *D = getCursorDecl(cursor)) {
4646 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004647 if (!DC)
4648 return clang_getNullCursor();
4649
4650 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4651 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004652 }
4653 }
4654
4655 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4656 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004657 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004658 }
4659
4660 return clang_getNullCursor();
4661}
4662
4663CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4664 if (clang_isDeclaration(cursor.kind)) {
4665 if (Decl *D = getCursorDecl(cursor)) {
4666 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004667 if (!DC)
4668 return clang_getNullCursor();
4669
4670 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4671 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004672 }
4673 }
4674
4675 // FIXME: Note that we can't easily compute the lexical context of a
4676 // statement or expression, so we return nothing.
4677 return clang_getNullCursor();
4678}
4679
Douglas Gregor9f592342010-10-01 20:25:15 +00004680static void CollectOverriddenMethods(DeclContext *Ctx,
4681 ObjCMethodDecl *Method,
4682 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4683 if (!Ctx)
4684 return;
4685
4686 // If we have a class or category implementation, jump straight to the
4687 // interface.
4688 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4689 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4690
4691 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4692 if (!Container)
4693 return;
4694
4695 // Check whether we have a matching method at this level.
4696 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4697 Method->isInstanceMethod()))
4698 if (Method != Overridden) {
4699 // We found an override at this level; there is no need to look
4700 // into other protocols or categories.
4701 Methods.push_back(Overridden);
4702 return;
4703 }
4704
4705 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4706 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4707 PEnd = Protocol->protocol_end();
4708 P != PEnd; ++P)
4709 CollectOverriddenMethods(*P, Method, Methods);
4710 }
4711
4712 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4713 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4714 PEnd = Category->protocol_end();
4715 P != PEnd; ++P)
4716 CollectOverriddenMethods(*P, Method, Methods);
4717 }
4718
4719 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4720 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4721 PEnd = Interface->protocol_end();
4722 P != PEnd; ++P)
4723 CollectOverriddenMethods(*P, Method, Methods);
4724
4725 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4726 Category; Category = Category->getNextClassCategory())
4727 CollectOverriddenMethods(Category, Method, Methods);
4728
4729 // We only look into the superclass if we haven't found anything yet.
4730 if (Methods.empty())
4731 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4732 return CollectOverriddenMethods(Super, Method, Methods);
4733 }
4734}
4735
4736void clang_getOverriddenCursors(CXCursor cursor,
4737 CXCursor **overridden,
4738 unsigned *num_overridden) {
4739 if (overridden)
4740 *overridden = 0;
4741 if (num_overridden)
4742 *num_overridden = 0;
4743 if (!overridden || !num_overridden)
4744 return;
4745
4746 if (!clang_isDeclaration(cursor.kind))
4747 return;
4748
4749 Decl *D = getCursorDecl(cursor);
4750 if (!D)
4751 return;
4752
4753 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004754 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004755 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4756 *num_overridden = CXXMethod->size_overridden_methods();
4757 if (!*num_overridden)
4758 return;
4759
4760 *overridden = new CXCursor [*num_overridden];
4761 unsigned I = 0;
4762 for (CXXMethodDecl::method_iterator
4763 M = CXXMethod->begin_overridden_methods(),
4764 MEnd = CXXMethod->end_overridden_methods();
4765 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004766 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004767 return;
4768 }
4769
4770 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4771 if (!Method)
4772 return;
4773
4774 // Handle Objective-C methods.
4775 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4776 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4777
4778 if (Methods.empty())
4779 return;
4780
4781 *num_overridden = Methods.size();
4782 *overridden = new CXCursor [Methods.size()];
4783 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004784 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004785}
4786
4787void clang_disposeOverriddenCursors(CXCursor *overridden) {
4788 delete [] overridden;
4789}
4790
Douglas Gregorecdcb882010-10-20 22:00:55 +00004791CXFile clang_getIncludedFile(CXCursor cursor) {
4792 if (cursor.kind != CXCursor_InclusionDirective)
4793 return 0;
4794
4795 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4796 return (void *)ID->getFile();
4797}
4798
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004799} // end: extern "C"
4800
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004801
4802//===----------------------------------------------------------------------===//
4803// C++ AST instrospection.
4804//===----------------------------------------------------------------------===//
4805
4806extern "C" {
4807unsigned clang_CXXMethod_isStatic(CXCursor C) {
4808 if (!clang_isDeclaration(C.kind))
4809 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004810
4811 CXXMethodDecl *Method = 0;
4812 Decl *D = cxcursor::getCursorDecl(C);
4813 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4814 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4815 else
4816 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4817 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004818}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004819
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004820} // end: extern "C"
4821
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004822//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004823// Attribute introspection.
4824//===----------------------------------------------------------------------===//
4825
4826extern "C" {
4827CXType clang_getIBOutletCollectionType(CXCursor C) {
4828 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004829 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004830
4831 IBOutletCollectionAttr *A =
4832 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4833
Ted Kremeneka60ed472010-11-16 08:15:36 +00004834 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004835}
4836} // end: extern "C"
4837
4838//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004839// Misc. utility functions.
4840//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004841
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004842/// Default to using an 8 MB stack size on "safety" threads.
4843static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004844
4845namespace clang {
4846
4847bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004848 void (*Fn)(void*), void *UserData,
4849 unsigned Size) {
4850 if (!Size)
4851 Size = GetSafetyThreadStackSize();
4852 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004853 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4854 return CRC.RunSafely(Fn, UserData);
4855}
4856
4857unsigned GetSafetyThreadStackSize() {
4858 return SafetyStackThreadSize;
4859}
4860
4861void SetSafetyThreadStackSize(unsigned Value) {
4862 SafetyStackThreadSize = Value;
4863}
4864
4865}
4866
Ted Kremenek04bb7162010-01-22 22:44:15 +00004867extern "C" {
4868
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004869CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004870 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004871}
4872
4873} // end: extern "C"