blob: f4e355707cab429ffb296da6f4e51fc4a6f094fd [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 Kremeneked122732010-11-16 01:56:27 +000017#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000018#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000019#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000020#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000021
Ted Kremenek04bb7162010-01-22 22:44:15 +000022#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000023
Steve Naroff50398192009-08-28 15:28:48 +000024#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000026#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000027#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000030#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000031#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000032#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000033#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000034#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000035#include "llvm/ADT/Optional.h"
36#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000037#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000038#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000039#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000041#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000042#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000043#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000044#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000045#include "llvm/System/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000046#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000047
Steve Naroff50398192009-08-28 15:28:48 +000048using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000049using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000050using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000051
Ted Kremeneka60ed472010-11-16 08:15:36 +000052static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
53 if (!TU)
54 return 0;
55 CXTranslationUnit D = new CXTranslationUnitImpl();
56 D->TUData = TU;
57 D->StringPool = createCXStringPool();
58 return D;
59}
60
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061/// \brief The result of comparing two source ranges.
62enum RangeComparisonResult {
63 /// \brief Either the ranges overlap or one of the ranges is invalid.
64 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066 /// \brief The first range ends before the second range starts.
67 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000068
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 /// \brief The first range starts after the second range ends.
70 RangeAfter
71};
72
Ted Kremenekf0e23e82010-02-17 00:41:40 +000073/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075static RangeComparisonResult RangeCompare(SourceManager &SM,
76 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 SourceRange R2) {
78 assert(R1.isValid() && "First range is invalid?");
79 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000083 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000084 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000085 return RangeAfter;
86 return RangeOverlap;
87}
88
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089/// \brief Determine if a source location falls within, before, or after a
90/// a given source range.
91static RangeComparisonResult LocationCompare(SourceManager &SM,
92 SourceLocation L, SourceRange R) {
93 assert(R.isValid() && "First range is invalid?");
94 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000095 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000096 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
98 return RangeBefore;
99 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
100 return RangeAfter;
101 return RangeOverlap;
102}
103
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000104/// \brief Translate a Clang source range into a CIndex source range.
105///
106/// Clang internally represents ranges where the end location points to the
107/// start of the token at the end. However, for external clients it is more
108/// useful to have a CXSourceRange be a proper half-open interval. This routine
109/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000110CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000112 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000113 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000114 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000115 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000116 if (EndLoc.isValid() && EndLoc.isMacroID())
117 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000118 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000119 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000120 EndLoc = EndLoc.getFileLocWithOffset(Length);
121 }
122
123 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
124 R.getBegin().getRawEncoding(),
125 EndLoc.getRawEncoding() };
126 return Result;
127}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000128
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000130// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000131//===----------------------------------------------------------------------===//
132
Steve Naroff89922f82009-08-31 00:59:03 +0000133namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000134
135class VisitorJob {
136public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000137 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000138 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000139 DeclRefExprPartsKind, LabelRefVisitKind,
140 ExplicitTemplateArgsVisitKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000141protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000142 void *dataA;
143 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000144 CXCursor parent;
145 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000146 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
147 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000148public:
149 Kind getKind() const { return K; }
150 const CXCursor &getParent() const { return parent; }
151 static bool classof(VisitorJob *VJ) { return true; }
152};
153
154typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
155
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000157class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000158 public TypeLocVisitor<CursorVisitor, bool>,
159 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000160{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000162 CXTranslationUnit TU;
163 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000167
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 /// \brief The declaration that serves at the parent of any statement or
169 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000170 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000171
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000176 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000178 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
179 // to the visitor. Declarations with a PCH level greater than this value will
180 // be suppressed.
181 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182
183 /// \brief When valid, a source range to which the cursor should restrict
184 /// its search.
185 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000186
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000187 // FIXME: Eventually remove. This part of a hack to support proper
188 // iteration over all Decls contained lexically within an ObjC container.
189 DeclContext::decl_iterator *DI_current;
190 DeclContext::decl_iterator DE_current;
191
Ted Kremenekd1ded662010-11-15 23:31:32 +0000192 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
193 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
194 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
195
Douglas Gregorb1373d02010-01-20 20:59:29 +0000196 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000197 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000198 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
200 /// \brief Determine whether this particular source range comes before, comes
201 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000202 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000203 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000204 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
205
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000206 class SetParentRAII {
207 CXCursor &Parent;
208 Decl *&StmtParent;
209 CXCursor OldParent;
210
211 public:
212 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
213 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
214 {
215 Parent = NewParent;
216 if (clang_isDeclaration(Parent.kind))
217 StmtParent = getCursorDecl(Parent);
218 }
219
220 ~SetParentRAII() {
221 Parent = OldParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225 };
226
Steve Naroff89922f82009-08-31 00:59:03 +0000227public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000228 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
229 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000230 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000231 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000232 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
233 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000234 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
235 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000236 {
237 Parent.kind = CXCursor_NoDeclFound;
238 Parent.data[0] = 0;
239 Parent.data[1] = 0;
240 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000241 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000243
Ted Kremenekd1ded662010-11-15 23:31:32 +0000244 ~CursorVisitor() {
245 // Free the pre-allocated worklists for data-recursion.
246 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
247 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
248 delete *I;
249 }
250 }
251
Ted Kremeneka60ed472010-11-16 08:15:36 +0000252 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
253 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000254
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000255 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000256
257 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
258 getPreprocessedEntities();
259
Douglas Gregorb1373d02010-01-20 20:59:29 +0000260 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000261
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000262 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000263 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000264 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000265 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000266 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000267 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000268 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
269 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000270 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000271 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000272 bool VisitClassTemplatePartialSpecializationDecl(
273 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000274 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitEnumConstantDecl(EnumConstantDecl *D);
276 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
277 bool VisitFunctionDecl(FunctionDecl *ND);
278 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000279 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000280 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000281 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000282 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000283 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000284 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
285 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
286 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
287 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000288 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
290 bool VisitObjCImplDecl(ObjCImplDecl *D);
291 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
292 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000293 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
294 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
295 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000296 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000297 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000298 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000299 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000300 bool VisitUsingDecl(UsingDecl *D);
301 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
302 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000303
Douglas Gregor01829d32010-08-31 14:41:23 +0000304 // Name visitor
305 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000306 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000307
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000308 // Template visitors
309 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000310 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000311 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
312
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000313 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000314 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000315 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000316 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000317 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
318 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000319 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000320 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000321 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
323 bool VisitPointerTypeLoc(PointerTypeLoc TL);
324 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
325 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
326 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
327 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000328 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000329 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000330 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000331 // FIXME: Implement visitors here when the unimplemented TypeLocs get
332 // implemented
333 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
334 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000335
Douglas Gregora59e3902010-01-21 23:27:09 +0000336 // Statement visitors
337 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000338
Douglas Gregor336fd812010-01-23 00:40:08 +0000339 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000340 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000341 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000342 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000343 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000344 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000345 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000346 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000347
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000348 // Data-recursive visitor functions.
349 bool IsInRegionOfInterest(CXCursor C);
350 bool RunVisitorWorkList(VisitorWorkList &WL);
351 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Benjamin Kramere645c722010-11-16 15:45:46 +0000352 LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000353};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000354
Ted Kremenekab188932010-01-05 19:32:54 +0000355} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000357static SourceRange getRawCursorExtent(CXCursor C);
358
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000360 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361}
362
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \brief Visit the given cursor and, if requested by the visitor,
364/// its children.
365///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366/// \param Cursor the cursor to visit.
367///
368/// \param CheckRegionOfInterest if true, then the caller already checked that
369/// this cursor is within the region of interest.
370///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \returns true if the visitation should be aborted, false if it
372/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000373bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 if (clang_isInvalid(Cursor.kind))
375 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000376
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 if (clang_isDeclaration(Cursor.kind)) {
378 Decl *D = getCursorDecl(Cursor);
379 assert(D && "Invalid declaration cursor");
380 if (D->getPCHLevel() > MaxPCHLevel)
381 return false;
382
383 if (D->isImplicit())
384 return false;
385 }
386
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387 // If we have a range of interest, and this cursor doesn't intersect with it,
388 // we're done.
389 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000390 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000391 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392 return false;
393 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000394
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 switch (Visitor(Cursor, Parent, ClientData)) {
396 case CXChildVisit_Break:
397 return true;
398
399 case CXChildVisit_Continue:
400 return false;
401
402 case CXChildVisit_Recurse:
403 return VisitChildren(Cursor);
404 }
405
Douglas Gregorfd643772010-01-25 16:45:46 +0000406 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407}
408
Douglas Gregor788f5a12010-03-20 00:41:21 +0000409std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
410CursorVisitor::getPreprocessedEntities() {
411 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000412 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000413
414 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000415 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000416
417 // There is no region of interest; we have to walk everything.
418 if (RegionOfInterest.isInvalid())
419 return std::make_pair(PPRec.begin(OnlyLocalDecls),
420 PPRec.end(OnlyLocalDecls));
421
422 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000423 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000424 std::pair<FileID, unsigned> Begin
425 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
426 std::pair<FileID, unsigned> End
427 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
428
429 // The region of interest spans files; we have to walk everything.
430 if (Begin.first != End.first)
431 return std::make_pair(PPRec.begin(OnlyLocalDecls),
432 PPRec.end(OnlyLocalDecls));
433
434 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000435 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000436 if (ByFileMap.empty()) {
437 // Build the mapping from files to sets of preprocessed entities.
438 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
439 EEnd = PPRec.end(OnlyLocalDecls);
440 E != EEnd; ++E) {
441 std::pair<FileID, unsigned> P
442 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
443 ByFileMap[P.first].push_back(*E);
444 }
445 }
446
447 return std::make_pair(ByFileMap[Begin.first].begin(),
448 ByFileMap[Begin.first].end());
449}
450
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000452///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453/// \returns true if the visitation should be aborted, false if it
454/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000456 if (clang_isReference(Cursor.kind)) {
457 // By definition, references have no children.
458 return false;
459 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460
461 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000462 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000463 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464
Douglas Gregorb1373d02010-01-20 20:59:29 +0000465 if (clang_isDeclaration(Cursor.kind)) {
466 Decl *D = getCursorDecl(Cursor);
467 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000468 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
Douglas Gregora59e3902010-01-21 23:27:09 +0000471 if (clang_isStatement(Cursor.kind))
472 return Visit(getCursorStmt(Cursor));
473 if (clang_isExpression(Cursor.kind))
474 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000475
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000477 CXTranslationUnit tu = getCursorTU(Cursor);
478 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000479 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
480 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000481 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
482 TLEnd = CXXUnit->top_level_end();
483 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000484 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000485 return true;
486 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000487 } else if (VisitDeclContext(
488 CXXUnit->getASTContext().getTranslationUnitDecl()))
489 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000490
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000492 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 // FIXME: Once we have the ability to deserialize a preprocessing record,
494 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000495 PreprocessingRecord::iterator E, EEnd;
496 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000498 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000499 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000500
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 continue;
502 }
503
504 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000505 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000506 return true;
507
508 continue;
509 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000510
511 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000512 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000513 return true;
514
515 continue;
516 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 }
518 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000519 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000521
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 return false;
524}
525
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000526bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000527 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
528 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000529
Ted Kremenek664cffd2010-07-22 11:30:19 +0000530 if (Stmt *Body = B->getBody())
531 return Visit(MakeCXCursor(Body, StmtParent, TU));
532
533 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000534}
535
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000536llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
537 if (RegionOfInterest.isValid()) {
538 SourceRange Range = getRawCursorExtent(Cursor);
539 if (Range.isInvalid())
540 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000541
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000542 switch (CompareRegionOfInterest(Range)) {
543 case RangeBefore:
544 // This declaration comes before the region of interest; skip it.
545 return llvm::Optional<bool>();
546
547 case RangeAfter:
548 // This declaration comes after the region of interest; we're done.
549 return false;
550
551 case RangeOverlap:
552 // This declaration overlaps the region of interest; visit it.
553 break;
554 }
555 }
556 return true;
557}
558
559bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
560 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
561
562 // FIXME: Eventually remove. This part of a hack to support proper
563 // iteration over all Decls contained lexically within an ObjC container.
564 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
565 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
566
567 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000568 Decl *D = *I;
569 if (D->getLexicalDeclContext() != DC)
570 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000571 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000572 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
573 if (!V.hasValue())
574 continue;
575 if (!V.getValue())
576 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000577 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000578 return true;
579 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000580 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000581}
582
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000583bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
584 llvm_unreachable("Translation units are visited directly by Visit()");
585 return false;
586}
587
588bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
589 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
590 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000591
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000592 return false;
593}
594
595bool CursorVisitor::VisitTagDecl(TagDecl *D) {
596 return VisitDeclContext(D);
597}
598
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000599bool CursorVisitor::VisitClassTemplateSpecializationDecl(
600 ClassTemplateSpecializationDecl *D) {
601 bool ShouldVisitBody = false;
602 switch (D->getSpecializationKind()) {
603 case TSK_Undeclared:
604 case TSK_ImplicitInstantiation:
605 // Nothing to visit
606 return false;
607
608 case TSK_ExplicitInstantiationDeclaration:
609 case TSK_ExplicitInstantiationDefinition:
610 break;
611
612 case TSK_ExplicitSpecialization:
613 ShouldVisitBody = true;
614 break;
615 }
616
617 // Visit the template arguments used in the specialization.
618 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
619 TypeLoc TL = SpecType->getTypeLoc();
620 if (TemplateSpecializationTypeLoc *TSTLoc
621 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
622 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
623 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
624 return true;
625 }
626 }
627
628 if (ShouldVisitBody && VisitCXXRecordDecl(D))
629 return true;
630
631 return false;
632}
633
Douglas Gregor74dbe642010-08-31 19:31:58 +0000634bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
635 ClassTemplatePartialSpecializationDecl *D) {
636 // FIXME: Visit the "outer" template parameter lists on the TagDecl
637 // before visiting these template parameters.
638 if (VisitTemplateParameters(D->getTemplateParameters()))
639 return true;
640
641 // Visit the partial specialization arguments.
642 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
643 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
644 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
645 return true;
646
647 return VisitCXXRecordDecl(D);
648}
649
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000650bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000651 // Visit the default argument.
652 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
653 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
654 if (Visit(DefArg->getTypeLoc()))
655 return true;
656
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000657 return false;
658}
659
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000660bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
661 if (Expr *Init = D->getInitExpr())
662 return Visit(MakeCXCursor(Init, StmtParent, TU));
663 return false;
664}
665
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000666bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
667 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
668 if (Visit(TSInfo->getTypeLoc()))
669 return true;
670
671 return false;
672}
673
Douglas Gregora67e03f2010-09-09 21:42:20 +0000674/// \brief Compare two base or member initializers based on their source order.
675static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
676 CXXBaseOrMemberInitializer const * const *X
677 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
678 CXXBaseOrMemberInitializer const * const *Y
679 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
680
681 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
682 return -1;
683 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
684 return 1;
685 else
686 return 0;
687}
688
Douglas Gregorb1373d02010-01-20 20:59:29 +0000689bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000690 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
691 // Visit the function declaration's syntactic components in the order
692 // written. This requires a bit of work.
693 TypeLoc TL = TSInfo->getTypeLoc();
694 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
695
696 // If we have a function declared directly (without the use of a typedef),
697 // visit just the return type. Otherwise, just visit the function's type
698 // now.
699 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
700 (!FTL && Visit(TL)))
701 return true;
702
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000703 // Visit the nested-name-specifier, if present.
704 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
705 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
706 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000707
708 // Visit the declaration name.
709 if (VisitDeclarationNameInfo(ND->getNameInfo()))
710 return true;
711
712 // FIXME: Visit explicitly-specified template arguments!
713
714 // Visit the function parameters, if we have a function type.
715 if (FTL && VisitFunctionTypeLoc(*FTL, true))
716 return true;
717
718 // FIXME: Attributes?
719 }
720
Douglas Gregora67e03f2010-09-09 21:42:20 +0000721 if (ND->isThisDeclarationADefinition()) {
722 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
723 // Find the initializers that were written in the source.
724 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
725 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
726 IEnd = Constructor->init_end();
727 I != IEnd; ++I) {
728 if (!(*I)->isWritten())
729 continue;
730
731 WrittenInits.push_back(*I);
732 }
733
734 // Sort the initializers in source order
735 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
736 &CompareCXXBaseOrMemberInitializers);
737
738 // Visit the initializers in source order
739 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
740 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
741 if (Init->isMemberInitializer()) {
742 if (Visit(MakeCursorMemberRef(Init->getMember(),
743 Init->getMemberLocation(), TU)))
744 return true;
745 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
746 if (Visit(BaseInfo->getTypeLoc()))
747 return true;
748 }
749
750 // Visit the initializer value.
751 if (Expr *Initializer = Init->getInit())
752 if (Visit(MakeCXCursor(Initializer, ND, TU)))
753 return true;
754 }
755 }
756
757 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
758 return true;
759 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000760
Douglas Gregorb1373d02010-01-20 20:59:29 +0000761 return false;
762}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000763
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000764bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
765 if (VisitDeclaratorDecl(D))
766 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000767
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000768 if (Expr *BitWidth = D->getBitWidth())
769 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000770
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000771 return false;
772}
773
774bool CursorVisitor::VisitVarDecl(VarDecl *D) {
775 if (VisitDeclaratorDecl(D))
776 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000778 if (Expr *Init = D->getInit())
779 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781 return false;
782}
783
Douglas Gregor84b51d72010-09-01 20:16:53 +0000784bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
785 if (VisitDeclaratorDecl(D))
786 return true;
787
788 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
789 if (Expr *DefArg = D->getDefaultArgument())
790 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
791
792 return false;
793}
794
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000795bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
796 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
797 // before visiting these template parameters.
798 if (VisitTemplateParameters(D->getTemplateParameters()))
799 return true;
800
801 return VisitFunctionDecl(D->getTemplatedDecl());
802}
803
Douglas Gregor39d6f072010-08-31 19:02:00 +0000804bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
805 // FIXME: Visit the "outer" template parameter lists on the TagDecl
806 // before visiting these template parameters.
807 if (VisitTemplateParameters(D->getTemplateParameters()))
808 return true;
809
810 return VisitCXXRecordDecl(D->getTemplatedDecl());
811}
812
Douglas Gregor84b51d72010-09-01 20:16:53 +0000813bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
814 if (VisitTemplateParameters(D->getTemplateParameters()))
815 return true;
816
817 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
818 VisitTemplateArgumentLoc(D->getDefaultArgument()))
819 return true;
820
821 return false;
822}
823
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000824bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000825 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
826 if (Visit(TSInfo->getTypeLoc()))
827 return true;
828
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000829 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000830 PEnd = ND->param_end();
831 P != PEnd; ++P) {
832 if (Visit(MakeCXCursor(*P, TU)))
833 return true;
834 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000835
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836 if (ND->isThisDeclarationADefinition() &&
837 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
838 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 return false;
841}
842
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000843namespace {
844 struct ContainerDeclsSort {
845 SourceManager &SM;
846 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
847 bool operator()(Decl *A, Decl *B) {
848 SourceLocation L_A = A->getLocStart();
849 SourceLocation L_B = B->getLocStart();
850 assert(L_A.isValid() && L_B.isValid());
851 return SM.isBeforeInTranslationUnit(L_A, L_B);
852 }
853 };
854}
855
Douglas Gregora59e3902010-01-21 23:27:09 +0000856bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000857 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
858 // an @implementation can lexically contain Decls that are not properly
859 // nested in the AST. When we identify such cases, we need to retrofit
860 // this nesting here.
861 if (!DI_current)
862 return VisitDeclContext(D);
863
864 // Scan the Decls that immediately come after the container
865 // in the current DeclContext. If any fall within the
866 // container's lexical region, stash them into a vector
867 // for later processing.
868 llvm::SmallVector<Decl *, 24> DeclsInContainer;
869 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000870 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000871 if (EndLoc.isValid()) {
872 DeclContext::decl_iterator next = *DI_current;
873 while (++next != DE_current) {
874 Decl *D_next = *next;
875 if (!D_next)
876 break;
877 SourceLocation L = D_next->getLocStart();
878 if (!L.isValid())
879 break;
880 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
881 *DI_current = next;
882 DeclsInContainer.push_back(D_next);
883 continue;
884 }
885 break;
886 }
887 }
888
889 // The common case.
890 if (DeclsInContainer.empty())
891 return VisitDeclContext(D);
892
893 // Get all the Decls in the DeclContext, and sort them with the
894 // additional ones we've collected. Then visit them.
895 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
896 I!=E; ++I) {
897 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000898 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
899 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000900 continue;
901 DeclsInContainer.push_back(subDecl);
902 }
903
904 // Now sort the Decls so that they appear in lexical order.
905 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
906 ContainerDeclsSort(SM));
907
908 // Now visit the decls.
909 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
910 E = DeclsInContainer.end(); I != E; ++I) {
911 CXCursor Cursor = MakeCXCursor(*I, TU);
912 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
913 if (!V.hasValue())
914 continue;
915 if (!V.getValue())
916 return false;
917 if (Visit(Cursor, true))
918 return true;
919 }
920 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000921}
922
Douglas Gregorb1373d02010-01-20 20:59:29 +0000923bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000924 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
925 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000926 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000927
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000928 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
929 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
930 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000931 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000932 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000933
Douglas Gregora59e3902010-01-21 23:27:09 +0000934 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000935}
936
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000937bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
938 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
939 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
940 E = PID->protocol_end(); I != E; ++I, ++PL)
941 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
942 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000943
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000944 return VisitObjCContainerDecl(PID);
945}
946
Ted Kremenek23173d72010-05-18 21:09:07 +0000947bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000948 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000949 return true;
950
Ted Kremenek23173d72010-05-18 21:09:07 +0000951 // FIXME: This implements a workaround with @property declarations also being
952 // installed in the DeclContext for the @interface. Eventually this code
953 // should be removed.
954 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
955 if (!CDecl || !CDecl->IsClassExtension())
956 return false;
957
958 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
959 if (!ID)
960 return false;
961
962 IdentifierInfo *PropertyId = PD->getIdentifier();
963 ObjCPropertyDecl *prevDecl =
964 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
965
966 if (!prevDecl)
967 return false;
968
969 // Visit synthesized methods since they will be skipped when visiting
970 // the @interface.
971 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000972 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000973 if (Visit(MakeCXCursor(MD, TU)))
974 return true;
975
976 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000977 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000978 if (Visit(MakeCXCursor(MD, TU)))
979 return true;
980
981 return false;
982}
983
Douglas Gregorb1373d02010-01-20 20:59:29 +0000984bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000985 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000986 if (D->getSuperClass() &&
987 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000988 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000989 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000990 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000991
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000992 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
993 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
994 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000995 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000996 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000997
Douglas Gregora59e3902010-01-21 23:27:09 +0000998 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000999}
1000
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001001bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1002 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001003}
1004
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001005bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001006 // 'ID' could be null when dealing with invalid code.
1007 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1008 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1009 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001010
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001011 return VisitObjCImplDecl(D);
1012}
1013
1014bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1015#if 0
1016 // Issue callbacks for super class.
1017 // FIXME: No source location information!
1018 if (D->getSuperClass() &&
1019 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001020 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001021 TU)))
1022 return true;
1023#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001025 return VisitObjCImplDecl(D);
1026}
1027
1028bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1029 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1030 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1031 E = D->protocol_end();
1032 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001033 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001034 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001035
1036 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001037}
1038
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001039bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1040 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1041 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1042 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001044 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001045}
1046
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001047bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1048 return VisitDeclContext(D);
1049}
1050
Douglas Gregor69319002010-08-31 23:48:11 +00001051bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001052 // Visit nested-name-specifier.
1053 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1054 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1055 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001056
1057 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1058 D->getTargetNameLoc(), TU));
1059}
1060
Douglas Gregor7e242562010-09-01 19:52:22 +00001061bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001062 // Visit nested-name-specifier.
1063 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1064 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1065 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001066
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001067 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1068 return true;
1069
Douglas Gregor7e242562010-09-01 19:52:22 +00001070 return VisitDeclarationNameInfo(D->getNameInfo());
1071}
1072
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001073bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001074 // Visit nested-name-specifier.
1075 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1076 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1077 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001078
1079 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1080 D->getIdentLocation(), TU));
1081}
1082
Douglas Gregor7e242562010-09-01 19:52:22 +00001083bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001084 // Visit nested-name-specifier.
1085 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1086 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1087 return true;
1088
Douglas Gregor7e242562010-09-01 19:52:22 +00001089 return VisitDeclarationNameInfo(D->getNameInfo());
1090}
1091
1092bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1093 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001094 // Visit nested-name-specifier.
1095 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1096 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1097 return true;
1098
Douglas Gregor7e242562010-09-01 19:52:22 +00001099 return false;
1100}
1101
Douglas Gregor01829d32010-08-31 14:41:23 +00001102bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1103 switch (Name.getName().getNameKind()) {
1104 case clang::DeclarationName::Identifier:
1105 case clang::DeclarationName::CXXLiteralOperatorName:
1106 case clang::DeclarationName::CXXOperatorName:
1107 case clang::DeclarationName::CXXUsingDirective:
1108 return false;
1109
1110 case clang::DeclarationName::CXXConstructorName:
1111 case clang::DeclarationName::CXXDestructorName:
1112 case clang::DeclarationName::CXXConversionFunctionName:
1113 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1114 return Visit(TSInfo->getTypeLoc());
1115 return false;
1116
1117 case clang::DeclarationName::ObjCZeroArgSelector:
1118 case clang::DeclarationName::ObjCOneArgSelector:
1119 case clang::DeclarationName::ObjCMultiArgSelector:
1120 // FIXME: Per-identifier location info?
1121 return false;
1122 }
1123
1124 return false;
1125}
1126
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001127bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1128 SourceRange Range) {
1129 // FIXME: This whole routine is a hack to work around the lack of proper
1130 // source information in nested-name-specifiers (PR5791). Since we do have
1131 // a beginning source location, we can visit the first component of the
1132 // nested-name-specifier, if it's a single-token component.
1133 if (!NNS)
1134 return false;
1135
1136 // Get the first component in the nested-name-specifier.
1137 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1138 NNS = Prefix;
1139
1140 switch (NNS->getKind()) {
1141 case NestedNameSpecifier::Namespace:
1142 // FIXME: The token at this source location might actually have been a
1143 // namespace alias, but we don't model that. Lame!
1144 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1145 TU));
1146
1147 case NestedNameSpecifier::TypeSpec: {
1148 // If the type has a form where we know that the beginning of the source
1149 // range matches up with a reference cursor. Visit the appropriate reference
1150 // cursor.
1151 Type *T = NNS->getAsType();
1152 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1153 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1154 if (const TagType *Tag = dyn_cast<TagType>(T))
1155 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1156 if (const TemplateSpecializationType *TST
1157 = dyn_cast<TemplateSpecializationType>(T))
1158 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1159 break;
1160 }
1161
1162 case NestedNameSpecifier::TypeSpecWithTemplate:
1163 case NestedNameSpecifier::Global:
1164 case NestedNameSpecifier::Identifier:
1165 break;
1166 }
1167
1168 return false;
1169}
1170
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001171bool CursorVisitor::VisitTemplateParameters(
1172 const TemplateParameterList *Params) {
1173 if (!Params)
1174 return false;
1175
1176 for (TemplateParameterList::const_iterator P = Params->begin(),
1177 PEnd = Params->end();
1178 P != PEnd; ++P) {
1179 if (Visit(MakeCXCursor(*P, TU)))
1180 return true;
1181 }
1182
1183 return false;
1184}
1185
Douglas Gregor0b36e612010-08-31 20:37:03 +00001186bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1187 switch (Name.getKind()) {
1188 case TemplateName::Template:
1189 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1190
1191 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001192 // Visit the overloaded template set.
1193 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1194 return true;
1195
Douglas Gregor0b36e612010-08-31 20:37:03 +00001196 return false;
1197
1198 case TemplateName::DependentTemplate:
1199 // FIXME: Visit nested-name-specifier.
1200 return false;
1201
1202 case TemplateName::QualifiedTemplate:
1203 // FIXME: Visit nested-name-specifier.
1204 return Visit(MakeCursorTemplateRef(
1205 Name.getAsQualifiedTemplateName()->getDecl(),
1206 Loc, TU));
1207 }
1208
1209 return false;
1210}
1211
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001212bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1213 switch (TAL.getArgument().getKind()) {
1214 case TemplateArgument::Null:
1215 case TemplateArgument::Integral:
1216 return false;
1217
1218 case TemplateArgument::Pack:
1219 // FIXME: Implement when variadic templates come along.
1220 return false;
1221
1222 case TemplateArgument::Type:
1223 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1224 return Visit(TSInfo->getTypeLoc());
1225 return false;
1226
1227 case TemplateArgument::Declaration:
1228 if (Expr *E = TAL.getSourceDeclExpression())
1229 return Visit(MakeCXCursor(E, StmtParent, TU));
1230 return false;
1231
1232 case TemplateArgument::Expression:
1233 if (Expr *E = TAL.getSourceExpression())
1234 return Visit(MakeCXCursor(E, StmtParent, TU));
1235 return false;
1236
1237 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001238 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1239 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001240 }
1241
1242 return false;
1243}
1244
Ted Kremeneka0536d82010-05-07 01:04:29 +00001245bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1246 return VisitDeclContext(D);
1247}
1248
Douglas Gregor01829d32010-08-31 14:41:23 +00001249bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1250 return Visit(TL.getUnqualifiedLoc());
1251}
1252
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001253bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001254 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001255
1256 // Some builtin types (such as Objective-C's "id", "sel", and
1257 // "Class") have associated declarations. Create cursors for those.
1258 QualType VisitType;
1259 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001260 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001261 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001262 case BuiltinType::Char_U:
1263 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001264 case BuiltinType::Char16:
1265 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001266 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267 case BuiltinType::UInt:
1268 case BuiltinType::ULong:
1269 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001270 case BuiltinType::UInt128:
1271 case BuiltinType::Char_S:
1272 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001274 case BuiltinType::Short:
1275 case BuiltinType::Int:
1276 case BuiltinType::Long:
1277 case BuiltinType::LongLong:
1278 case BuiltinType::Int128:
1279 case BuiltinType::Float:
1280 case BuiltinType::Double:
1281 case BuiltinType::LongDouble:
1282 case BuiltinType::NullPtr:
1283 case BuiltinType::Overload:
1284 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001285 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001286
1287 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001288 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001289
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001290 case BuiltinType::ObjCId:
1291 VisitType = Context.getObjCIdType();
1292 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001293
1294 case BuiltinType::ObjCClass:
1295 VisitType = Context.getObjCClassType();
1296 break;
1297
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001298 case BuiltinType::ObjCSel:
1299 VisitType = Context.getObjCSelType();
1300 break;
1301 }
1302
1303 if (!VisitType.isNull()) {
1304 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001305 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001306 TU));
1307 }
1308
1309 return false;
1310}
1311
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001312bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1313 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1314}
1315
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001316bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1317 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1318}
1319
1320bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1321 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1322}
1323
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001324bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001325 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001326 // no context information with which we can match up the depth/index in the
1327 // type to the appropriate
1328 return false;
1329}
1330
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1332 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1333 return true;
1334
John McCallc12c5bb2010-05-15 11:32:37 +00001335 return false;
1336}
1337
1338bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1339 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1340 return true;
1341
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001342 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1343 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1344 TU)))
1345 return true;
1346 }
1347
1348 return false;
1349}
1350
1351bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001352 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001353}
1354
1355bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1356 return Visit(TL.getPointeeLoc());
1357}
1358
1359bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1360 return Visit(TL.getPointeeLoc());
1361}
1362
1363bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1364 return Visit(TL.getPointeeLoc());
1365}
1366
1367bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001368 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001369}
1370
1371bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001372 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001373}
1374
Douglas Gregor01829d32010-08-31 14:41:23 +00001375bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1376 bool SkipResultType) {
1377 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378 return true;
1379
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001381 if (Decl *D = TL.getArg(I))
1382 if (Visit(MakeCXCursor(D, TU)))
1383 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384
1385 return false;
1386}
1387
1388bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1389 if (Visit(TL.getElementLoc()))
1390 return true;
1391
1392 if (Expr *Size = TL.getSizeExpr())
1393 return Visit(MakeCXCursor(Size, StmtParent, TU));
1394
1395 return false;
1396}
1397
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001398bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1399 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001400 // Visit the template name.
1401 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1402 TL.getTemplateNameLoc()))
1403 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001404
1405 // Visit the template arguments.
1406 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1407 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1408 return true;
1409
1410 return false;
1411}
1412
Douglas Gregor2332c112010-01-21 20:48:56 +00001413bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1414 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1415}
1416
1417bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1418 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1419 return Visit(TSInfo->getTypeLoc());
1420
1421 return false;
1422}
1423
Douglas Gregora59e3902010-01-21 23:27:09 +00001424bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001425 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001426}
1427
Ted Kremenek3064ef92010-08-27 21:34:58 +00001428bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1429 if (D->isDefinition()) {
1430 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1431 E = D->bases_end(); I != E; ++I) {
1432 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1433 return true;
1434 }
1435 }
1436
1437 return VisitTagDecl(D);
1438}
1439
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001440bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001441 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001442 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1443 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001444
1445 // Visit the components of the offsetof expression.
1446 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1447 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1448 const OffsetOfNode &Node = E->getComponent(I);
1449 switch (Node.getKind()) {
1450 case OffsetOfNode::Array:
1451 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1452 StmtParent, TU)))
1453 return true;
1454 break;
1455
1456 case OffsetOfNode::Field:
1457 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1458 TU)))
1459 return true;
1460 break;
1461
1462 case OffsetOfNode::Identifier:
1463 case OffsetOfNode::Base:
1464 continue;
1465 }
1466 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001467
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001468 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001469}
1470
Douglas Gregor336fd812010-01-23 00:40:08 +00001471bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1472 if (E->isArgumentType()) {
1473 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1474 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001475
Douglas Gregor336fd812010-01-23 00:40:08 +00001476 return false;
1477 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001478
Douglas Gregor336fd812010-01-23 00:40:08 +00001479 return VisitExpr(E);
1480}
1481
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001482bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1483 // Visit the designators.
1484 typedef DesignatedInitExpr::Designator Designator;
1485 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1486 DEnd = E->designators_end();
1487 D != DEnd; ++D) {
1488 if (D->isFieldDesignator()) {
1489 if (FieldDecl *Field = D->getField())
1490 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1491 return true;
1492
1493 continue;
1494 }
1495
1496 if (D->isArrayDesignator()) {
1497 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1498 return true;
1499
1500 continue;
1501 }
1502
1503 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1504 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1505 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1506 return true;
1507 }
1508
1509 // Visit the initializer value itself.
1510 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1511}
1512
Douglas Gregorab6677e2010-09-08 00:15:04 +00001513bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1514 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1515 return Visit(TSInfo->getTypeLoc());
1516
1517 return false;
1518}
1519
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001520bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1521 // Visit base expression.
1522 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1523 return true;
1524
1525 // Visit the nested-name-specifier.
1526 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1527 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1528 return true;
1529
1530 // Visit the scope type that looks disturbingly like the nested-name-specifier
1531 // but isn't.
1532 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1533 if (Visit(TSInfo->getTypeLoc()))
1534 return true;
1535
1536 // Visit the name of the type being destroyed.
1537 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1538 if (Visit(TSInfo->getTypeLoc()))
1539 return true;
1540
1541 return false;
1542}
1543
Douglas Gregorbfebed22010-09-03 17:24:10 +00001544bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1545 DependentScopeDeclRefExpr *E) {
1546 // Visit the nested-name-specifier.
1547 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1548 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1549 return true;
1550
1551 // Visit the declaration name.
1552 if (VisitDeclarationNameInfo(E->getNameInfo()))
1553 return true;
1554
1555 // Visit the explicitly-specified template arguments.
1556 if (const ExplicitTemplateArgumentList *ArgList
1557 = E->getOptionalExplicitTemplateArgs()) {
1558 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1559 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1560 Arg != ArgEnd; ++Arg) {
1561 if (VisitTemplateArgumentLoc(*Arg))
1562 return true;
1563 }
1564 }
1565
1566 return false;
1567}
1568
Douglas Gregor25d63622010-09-03 17:35:34 +00001569bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1570 CXXDependentScopeMemberExpr *E) {
1571 // Visit the base expression, if there is one.
1572 if (!E->isImplicitAccess() &&
1573 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1574 return true;
1575
1576 // Visit the nested-name-specifier.
1577 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1578 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1579 return true;
1580
1581 // Visit the declaration name.
1582 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1583 return true;
1584
1585 // Visit the explicitly-specified template arguments.
1586 if (const ExplicitTemplateArgumentList *ArgList
1587 = E->getOptionalExplicitTemplateArgs()) {
1588 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1589 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1590 Arg != ArgEnd; ++Arg) {
1591 if (VisitTemplateArgumentLoc(*Arg))
1592 return true;
1593 }
1594 }
1595
1596 return false;
1597}
1598
Ted Kremenek09dfa372010-02-18 05:46:33 +00001599bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001600 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1601 i != e; ++i)
1602 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001603 return true;
1604
1605 return false;
1606}
1607
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001608//===----------------------------------------------------------------------===//
1609// Data-recursive visitor methods.
1610//===----------------------------------------------------------------------===//
1611
Ted Kremenek28a71942010-11-13 00:36:47 +00001612namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001613#define DEF_JOB(NAME, DATA, KIND)\
1614class NAME : public VisitorJob {\
1615public:\
1616 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1617 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1618 DATA *get() const { return static_cast<DATA*>(dataA); }\
1619};
1620
1621DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1622DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001623DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001624DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001625DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1626 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001627#undef DEF_JOB
1628
1629class DeclVisit : public VisitorJob {
1630public:
1631 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1632 VisitorJob(parent, VisitorJob::DeclVisitKind,
1633 d, isFirst ? (void*) 1 : (void*) 0) {}
1634 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001635 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001636 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001637 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001638 bool isFirst() const { return dataB ? true : false; }
1639};
Ted Kremenek035dc412010-11-13 00:36:50 +00001640class TypeLocVisit : public VisitorJob {
1641public:
1642 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1643 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1644 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1645
1646 static bool classof(const VisitorJob *VJ) {
1647 return VJ->getKind() == TypeLocVisitKind;
1648 }
1649
Ted Kremenek82f3c502010-11-15 22:23:26 +00001650 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001651 QualType T = QualType::getFromOpaquePtr(dataA);
1652 return TypeLoc(T, dataB);
1653 }
1654};
1655
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001656class LabelRefVisit : public VisitorJob {
1657public:
1658 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1659 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1660 (void*) labelLoc.getRawEncoding()) {}
1661
1662 static bool classof(const VisitorJob *VJ) {
1663 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1664 }
1665 LabelStmt *get() const { return static_cast<LabelStmt*>(dataA); }
1666 SourceLocation getLoc() const {
1667 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) dataB); }
1668};
1669
Ted Kremenek28a71942010-11-13 00:36:47 +00001670class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1671 VisitorWorkList &WL;
1672 CXCursor Parent;
1673public:
1674 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1675 : WL(wl), Parent(parent) {}
1676
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001677 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001678 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001679 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001680 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001681 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1682 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001683 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001684 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001685 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001686 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001687 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001688 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001689 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001690 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1691 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001692 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001693 void VisitIfStmt(IfStmt *If);
1694 void VisitInitListExpr(InitListExpr *IE);
1695 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001696 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001697 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1698 void VisitOverloadExpr(OverloadExpr *E);
1699 void VisitStmt(Stmt *S);
1700 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001701 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001702 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001703 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001705 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001706
1707private:
Ted Kremenek60608ec2010-11-17 00:50:47 +00001708 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenek28a71942010-11-13 00:36:47 +00001709 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001710 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001711 void AddTypeLoc(TypeSourceInfo *TI);
1712 void EnqueueChildren(Stmt *S);
1713};
1714} // end anonyous namespace
1715
1716void EnqueueVisitor::AddStmt(Stmt *S) {
1717 if (S)
1718 WL.push_back(StmtVisit(S, Parent));
1719}
Ted Kremenek035dc412010-11-13 00:36:50 +00001720void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001721 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001722 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001723}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001724void EnqueueVisitor::
1725 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1726 if (A)
1727 WL.push_back(ExplicitTemplateArgsVisit(
1728 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1729}
Ted Kremenek28a71942010-11-13 00:36:47 +00001730void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1731 if (TI)
1732 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1733 }
1734void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001735 unsigned size = WL.size();
1736 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1737 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001738 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001739 }
1740 if (size == WL.size())
1741 return;
1742 // Now reverse the entries we just added. This will match the DFS
1743 // ordering performed by the worklist.
1744 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1745 std::reverse(I, E);
1746}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001747void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1748 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1749}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001750void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1751 AddDecl(B->getBlockDecl());
1752}
Ted Kremenek28a71942010-11-13 00:36:47 +00001753void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1754 EnqueueChildren(E);
1755 AddTypeLoc(E->getTypeSourceInfo());
1756}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001757void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1758 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1759 E = S->body_rend(); I != E; ++I) {
1760 AddStmt(*I);
1761 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001762}
1763void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1764 // Enqueue the initializer or constructor arguments.
1765 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1766 AddStmt(E->getConstructorArg(I-1));
1767 // Enqueue the array size, if any.
1768 AddStmt(E->getArraySize());
1769 // Enqueue the allocated type.
1770 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1771 // Enqueue the placement arguments.
1772 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1773 AddStmt(E->getPlacementArg(I-1));
1774}
Ted Kremenek28a71942010-11-13 00:36:47 +00001775void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001776 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1777 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001778 AddStmt(CE->getCallee());
1779 AddStmt(CE->getArg(0));
1780}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001781void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1782 EnqueueChildren(E);
1783 AddTypeLoc(E->getTypeSourceInfo());
1784}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001785void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1786 EnqueueChildren(E);
1787 if (E->isTypeOperand())
1788 AddTypeLoc(E->getTypeOperandSourceInfo());
1789}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001790
1791void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1792 *E) {
1793 EnqueueChildren(E);
1794 AddTypeLoc(E->getTypeSourceInfo());
1795}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001796void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1797 EnqueueChildren(E);
1798 if (E->isTypeOperand())
1799 AddTypeLoc(E->getTypeOperandSourceInfo());
1800}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001801void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001802 if (DR->hasExplicitTemplateArgs()) {
1803 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1804 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001805 WL.push_back(DeclRefExprParts(DR, Parent));
1806}
Ted Kremenek035dc412010-11-13 00:36:50 +00001807void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1808 unsigned size = WL.size();
1809 bool isFirst = true;
1810 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1811 D != DEnd; ++D) {
1812 AddDecl(*D, isFirst);
1813 isFirst = false;
1814 }
1815 if (size == WL.size())
1816 return;
1817 // Now reverse the entries we just added. This will match the DFS
1818 // ordering performed by the worklist.
1819 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1820 std::reverse(I, E);
1821}
Ted Kremenek28a71942010-11-13 00:36:47 +00001822void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1823 EnqueueChildren(E);
1824 AddTypeLoc(E->getTypeInfoAsWritten());
1825}
1826void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1827 AddStmt(FS->getBody());
1828 AddStmt(FS->getInc());
1829 AddStmt(FS->getCond());
1830 AddDecl(FS->getConditionVariable());
1831 AddStmt(FS->getInit());
1832}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001833void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1834 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1835}
Ted Kremenek28a71942010-11-13 00:36:47 +00001836void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1837 AddStmt(If->getElse());
1838 AddStmt(If->getThen());
1839 AddStmt(If->getCond());
1840 AddDecl(If->getConditionVariable());
1841}
1842void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1843 // We care about the syntactic form of the initializer list, only.
1844 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1845 IE = Syntactic;
1846 EnqueueChildren(IE);
1847}
1848void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1849 WL.push_back(MemberExprParts(M, Parent));
1850 AddStmt(M->getBase());
1851}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001852void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1853 AddTypeLoc(E->getEncodedTypeSourceInfo());
1854}
Ted Kremenek28a71942010-11-13 00:36:47 +00001855void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1856 EnqueueChildren(M);
1857 AddTypeLoc(M->getClassReceiverTypeInfo());
1858}
1859void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001860 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001861 WL.push_back(OverloadExprParts(E, Parent));
1862}
Ted Kremenek28a71942010-11-13 00:36:47 +00001863void EnqueueVisitor::VisitStmt(Stmt *S) {
1864 EnqueueChildren(S);
1865}
1866void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1867 AddStmt(S->getBody());
1868 AddStmt(S->getCond());
1869 AddDecl(S->getConditionVariable());
1870}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001871void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1872 AddTypeLoc(E->getArgTInfo2());
1873 AddTypeLoc(E->getArgTInfo1());
1874}
1875
Ted Kremenek28a71942010-11-13 00:36:47 +00001876void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1877 AddStmt(W->getBody());
1878 AddStmt(W->getCond());
1879 AddDecl(W->getConditionVariable());
1880}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001881void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1882 AddTypeLoc(E->getQueriedTypeSourceInfo());
1883}
Ted Kremenek28a71942010-11-13 00:36:47 +00001884void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1885 VisitOverloadExpr(U);
1886 if (!U->isImplicitAccess())
1887 AddStmt(U->getBase());
1888}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001889void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1890 AddStmt(E->getSubExpr());
1891 AddTypeLoc(E->getWrittenTypeInfo());
1892}
Ted Kremenek60458782010-11-12 21:34:16 +00001893
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001894void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001895 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001896}
1897
1898bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1899 if (RegionOfInterest.isValid()) {
1900 SourceRange Range = getRawCursorExtent(C);
1901 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1902 return false;
1903 }
1904 return true;
1905}
1906
1907bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1908 while (!WL.empty()) {
1909 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001910 VisitorJob LI = WL.back();
1911 WL.pop_back();
1912
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001913 // Set the Parent field, then back to its old value once we're done.
1914 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1915
1916 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001917 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001918 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001919 if (!D)
1920 continue;
1921
1922 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001923 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001924 return true;
1925
1926 continue;
1927 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001928 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1929 const ExplicitTemplateArgumentList *ArgList =
1930 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1931 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1932 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1933 Arg != ArgEnd; ++Arg) {
1934 if (VisitTemplateArgumentLoc(*Arg))
1935 return true;
1936 }
1937 continue;
1938 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001939 case VisitorJob::TypeLocVisitKind: {
1940 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001941 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001942 return true;
1943 continue;
1944 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001945 case VisitorJob::LabelRefVisitKind: {
1946 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1947 if (Visit(MakeCursorLabelRef(LS,
1948 cast<LabelRefVisit>(&LI)->getLoc(),
1949 TU)))
1950 return true;
1951 continue;
1952 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001953 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001954 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001955 if (!S)
1956 continue;
1957
Ted Kremenekf1107452010-11-12 18:26:56 +00001958 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001959 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1960
1961 switch (S->getStmtClass()) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001962 // Cases not yet handled by the data-recursion
1963 // algorithm.
1964 case Stmt::OffsetOfExprClass:
1965 case Stmt::SizeOfAlignOfExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001966 case Stmt::DesignatedInitExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001967 case Stmt::CXXScalarValueInitExprClass:
1968 case Stmt::CXXPseudoDestructorExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001969 case Stmt::DependentScopeDeclRefExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001970 case Stmt::CXXDependentScopeMemberExprClass:
1971 if (Visit(Cursor))
1972 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001973 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001974 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001975 if (!IsInRegionOfInterest(Cursor))
1976 continue;
1977 switch (Visitor(Cursor, Parent, ClientData)) {
1978 case CXChildVisit_Break:
1979 return true;
1980 case CXChildVisit_Continue:
1981 break;
1982 case CXChildVisit_Recurse:
1983 EnqueueWorkList(WL, S);
1984 break;
1985 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001986 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001987 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001988 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001989 }
1990 case VisitorJob::MemberExprPartsKind: {
1991 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001992 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001993
1994 // Visit the nested-name-specifier
1995 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1996 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1997 return true;
1998
1999 // Visit the declaration name.
2000 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2001 return true;
2002
2003 // Visit the explicitly-specified template arguments, if any.
2004 if (M->hasExplicitTemplateArgs()) {
2005 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2006 *ArgEnd = Arg + M->getNumTemplateArgs();
2007 Arg != ArgEnd; ++Arg) {
2008 if (VisitTemplateArgumentLoc(*Arg))
2009 return true;
2010 }
2011 }
2012 continue;
2013 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002014 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002015 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002016 // Visit nested-name-specifier, if present.
2017 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2018 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2019 return true;
2020 // Visit declaration name.
2021 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2022 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002023 continue;
2024 }
Ted Kremenek60458782010-11-12 21:34:16 +00002025 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002026 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002027 // Visit the nested-name-specifier.
2028 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2029 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2030 return true;
2031 // Visit the declaration name.
2032 if (VisitDeclarationNameInfo(O->getNameInfo()))
2033 return true;
2034 // Visit the overloaded declaration reference.
2035 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2036 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002037 continue;
2038 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002039 }
2040 }
2041 return false;
2042}
2043
2044bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002045 VisitorWorkList *WL = 0;
2046 if (!WorkListFreeList.empty()) {
2047 WL = WorkListFreeList.back();
2048 WL->clear();
2049 WorkListFreeList.pop_back();
2050 }
2051 else {
2052 WL = new VisitorWorkList();
2053 WorkListCache.push_back(WL);
2054 }
2055 EnqueueWorkList(*WL, S);
2056 bool result = RunVisitorWorkList(*WL);
2057 WorkListFreeList.push_back(WL);
2058 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002059}
2060
2061//===----------------------------------------------------------------------===//
2062// Misc. API hooks.
2063//===----------------------------------------------------------------------===//
2064
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002065static llvm::sys::Mutex EnableMultithreadingMutex;
2066static bool EnabledMultithreading;
2067
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002068extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002069CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2070 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002071 // Disable pretty stack trace functionality, which will otherwise be a very
2072 // poor citizen of the world and set up all sorts of signal handlers.
2073 llvm::DisablePrettyStackTrace = true;
2074
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002075 // We use crash recovery to make some of our APIs more reliable, implicitly
2076 // enable it.
2077 llvm::CrashRecoveryContext::Enable();
2078
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002079 // Enable support for multithreading in LLVM.
2080 {
2081 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2082 if (!EnabledMultithreading) {
2083 llvm::llvm_start_multithreaded();
2084 EnabledMultithreading = true;
2085 }
2086 }
2087
Douglas Gregora030b7c2010-01-22 20:35:53 +00002088 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002089 if (excludeDeclarationsFromPCH)
2090 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002091 if (displayDiagnostics)
2092 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002093 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002094}
2095
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002096void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002097 if (CIdx)
2098 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002099}
2100
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002101CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002102 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002103 if (!CIdx)
2104 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002105
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002106 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002107 FileSystemOptions FileSystemOpts;
2108 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002109
Douglas Gregor28019772010-04-05 23:52:57 +00002110 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002111 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002112 CXXIdx->getOnlyLocalDecls(),
2113 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002114 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002115}
2116
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002117unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002118 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002119 CXTranslationUnit_CacheCompletionResults |
2120 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002121}
2122
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002123CXTranslationUnit
2124clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2125 const char *source_filename,
2126 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002127 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002128 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002129 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002130 return clang_parseTranslationUnit(CIdx, source_filename,
2131 command_line_args, num_command_line_args,
2132 unsaved_files, num_unsaved_files,
2133 CXTranslationUnit_DetailedPreprocessingRecord);
2134}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002135
2136struct ParseTranslationUnitInfo {
2137 CXIndex CIdx;
2138 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002139 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002140 int num_command_line_args;
2141 struct CXUnsavedFile *unsaved_files;
2142 unsigned num_unsaved_files;
2143 unsigned options;
2144 CXTranslationUnit result;
2145};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002146static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002147 ParseTranslationUnitInfo *PTUI =
2148 static_cast<ParseTranslationUnitInfo*>(UserData);
2149 CXIndex CIdx = PTUI->CIdx;
2150 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002151 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002152 int num_command_line_args = PTUI->num_command_line_args;
2153 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2154 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2155 unsigned options = PTUI->options;
2156 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002157
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002158 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002159 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002161 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2162
Douglas Gregor44c181a2010-07-23 00:33:23 +00002163 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002164 bool CompleteTranslationUnit
2165 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002166 bool CacheCodeCompetionResults
2167 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002168 bool CXXPrecompilePreamble
2169 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2170 bool CXXChainedPCH
2171 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002172
Douglas Gregor5352ac02010-01-28 00:27:43 +00002173 // Configure the diagnostics.
2174 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002175 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2176 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002177
Douglas Gregor4db64a42010-01-23 00:14:00 +00002178 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2179 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002180 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002181 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002182 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002183 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2184 Buffer));
2185 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002186
Douglas Gregorb10daed2010-10-11 16:52:23 +00002187 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002188
Ted Kremenek139ba862009-10-22 00:03:57 +00002189 // The 'source_filename' argument is optional. If the caller does not
2190 // specify it then it is assumed that the source file is specified
2191 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002192 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002193 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002194
2195 // Since the Clang C library is primarily used by batch tools dealing with
2196 // (often very broken) source code, where spell-checking can have a
2197 // significant negative impact on performance (particularly when
2198 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002199 // Only do this if we haven't found a spell-checking-related argument.
2200 bool FoundSpellCheckingArgument = false;
2201 for (int I = 0; I != num_command_line_args; ++I) {
2202 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2203 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2204 FoundSpellCheckingArgument = true;
2205 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002206 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002207 }
2208 if (!FoundSpellCheckingArgument)
2209 Args.push_back("-fno-spell-checking");
2210
2211 Args.insert(Args.end(), command_line_args,
2212 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002213
Douglas Gregor44c181a2010-07-23 00:33:23 +00002214 // Do we need the detailed preprocessing record?
2215 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 Args.push_back("-Xclang");
2217 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002218 }
2219
Douglas Gregorb10daed2010-10-11 16:52:23 +00002220 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002221 llvm::OwningPtr<ASTUnit> Unit(
2222 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2223 Diags,
2224 CXXIdx->getClangResourcesPath(),
2225 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002226 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002227 RemappedFiles.data(),
2228 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002229 PrecompilePreamble,
2230 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002231 CacheCodeCompetionResults,
2232 CXXPrecompilePreamble,
2233 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002234
Douglas Gregorb10daed2010-10-11 16:52:23 +00002235 if (NumErrors != Diags->getNumErrors()) {
2236 // Make sure to check that 'Unit' is non-NULL.
2237 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2238 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2239 DEnd = Unit->stored_diag_end();
2240 D != DEnd; ++D) {
2241 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2242 CXString Msg = clang_formatDiagnostic(&Diag,
2243 clang_defaultDiagnosticDisplayOptions());
2244 fprintf(stderr, "%s\n", clang_getCString(Msg));
2245 clang_disposeString(Msg);
2246 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002247#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002248 // On Windows, force a flush, since there may be multiple copies of
2249 // stderr and stdout in the file system, all with different buffers
2250 // but writing to the same device.
2251 fflush(stderr);
2252#endif
2253 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002254 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002255
Ted Kremeneka60ed472010-11-16 08:15:36 +00002256 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002257}
2258CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2259 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002260 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002261 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002262 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002263 unsigned num_unsaved_files,
2264 unsigned options) {
2265 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002266 num_command_line_args, unsaved_files,
2267 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002268 llvm::CrashRecoveryContext CRC;
2269
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002270 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002271 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2272 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2273 fprintf(stderr, " 'command_line_args' : [");
2274 for (int i = 0; i != num_command_line_args; ++i) {
2275 if (i)
2276 fprintf(stderr, ", ");
2277 fprintf(stderr, "'%s'", command_line_args[i]);
2278 }
2279 fprintf(stderr, "],\n");
2280 fprintf(stderr, " 'unsaved_files' : [");
2281 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2282 if (i)
2283 fprintf(stderr, ", ");
2284 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2285 unsaved_files[i].Length);
2286 }
2287 fprintf(stderr, "],\n");
2288 fprintf(stderr, " 'options' : %d,\n", options);
2289 fprintf(stderr, "}\n");
2290
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002291 return 0;
2292 }
2293
2294 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002295}
2296
Douglas Gregor19998442010-08-13 15:35:05 +00002297unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2298 return CXSaveTranslationUnit_None;
2299}
2300
2301int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2302 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002303 if (!TU)
2304 return 1;
2305
Ted Kremeneka60ed472010-11-16 08:15:36 +00002306 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002307}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002308
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002309void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002310 if (CTUnit) {
2311 // If the translation unit has been marked as unsafe to free, just discard
2312 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002313 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002314 return;
2315
Ted Kremeneka60ed472010-11-16 08:15:36 +00002316 delete static_cast<ASTUnit *>(CTUnit->TUData);
2317 disposeCXStringPool(CTUnit->StringPool);
2318 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002319 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002320}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002321
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002322unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2323 return CXReparse_None;
2324}
2325
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002326struct ReparseTranslationUnitInfo {
2327 CXTranslationUnit TU;
2328 unsigned num_unsaved_files;
2329 struct CXUnsavedFile *unsaved_files;
2330 unsigned options;
2331 int result;
2332};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002333
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002334static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002335 ReparseTranslationUnitInfo *RTUI =
2336 static_cast<ReparseTranslationUnitInfo*>(UserData);
2337 CXTranslationUnit TU = RTUI->TU;
2338 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2339 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2340 unsigned options = RTUI->options;
2341 (void) options;
2342 RTUI->result = 1;
2343
Douglas Gregorabc563f2010-07-19 21:46:24 +00002344 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002345 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002346
Ted Kremeneka60ed472010-11-16 08:15:36 +00002347 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002348 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002349
2350 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2351 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2352 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2353 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002354 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002355 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2356 Buffer));
2357 }
2358
Douglas Gregor593b0c12010-09-23 18:47:53 +00002359 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2360 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002361}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002362
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002363int clang_reparseTranslationUnit(CXTranslationUnit TU,
2364 unsigned num_unsaved_files,
2365 struct CXUnsavedFile *unsaved_files,
2366 unsigned options) {
2367 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2368 options, 0 };
2369 llvm::CrashRecoveryContext CRC;
2370
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002371 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002372 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002373 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002374 return 1;
2375 }
2376
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002377
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002378 return RTUI.result;
2379}
2380
Douglas Gregordf95a132010-08-09 20:45:32 +00002381
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002382CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002383 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002384 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002385
Ted Kremeneka60ed472010-11-16 08:15:36 +00002386 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002387 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002388}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002389
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002390CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002391 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002392 return Result;
2393}
2394
Ted Kremenekfb480492010-01-13 21:46:36 +00002395} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002396
Ted Kremenekfb480492010-01-13 21:46:36 +00002397//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002398// CXSourceLocation and CXSourceRange Operations.
2399//===----------------------------------------------------------------------===//
2400
Douglas Gregorb9790342010-01-22 21:44:22 +00002401extern "C" {
2402CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002403 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002404 return Result;
2405}
2406
2407unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002408 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2409 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2410 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002411}
2412
2413CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2414 CXFile file,
2415 unsigned line,
2416 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002417 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002418 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002419
Ted Kremeneka60ed472010-11-16 08:15:36 +00002420 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002421 SourceLocation SLoc
2422 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002423 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002424 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002425 if (SLoc.isInvalid()) return clang_getNullLocation();
2426
2427 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2428}
2429
2430CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2431 CXFile file,
2432 unsigned offset) {
2433 if (!tu || !file)
2434 return clang_getNullLocation();
2435
Ted Kremeneka60ed472010-11-16 08:15:36 +00002436 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002437 SourceLocation Start
2438 = CXXUnit->getSourceManager().getLocation(
2439 static_cast<const FileEntry *>(file),
2440 1, 1);
2441 if (Start.isInvalid()) return clang_getNullLocation();
2442
2443 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2444
2445 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002446
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002447 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002448}
2449
Douglas Gregor5352ac02010-01-28 00:27:43 +00002450CXSourceRange clang_getNullRange() {
2451 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2452 return Result;
2453}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002454
Douglas Gregor5352ac02010-01-28 00:27:43 +00002455CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2456 if (begin.ptr_data[0] != end.ptr_data[0] ||
2457 begin.ptr_data[1] != end.ptr_data[1])
2458 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002459
2460 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002461 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002462 return Result;
2463}
2464
Douglas Gregor46766dc2010-01-26 19:19:08 +00002465void clang_getInstantiationLocation(CXSourceLocation location,
2466 CXFile *file,
2467 unsigned *line,
2468 unsigned *column,
2469 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002470 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2471
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002472 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002473 if (file)
2474 *file = 0;
2475 if (line)
2476 *line = 0;
2477 if (column)
2478 *column = 0;
2479 if (offset)
2480 *offset = 0;
2481 return;
2482 }
2483
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002484 const SourceManager &SM =
2485 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002486 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002487
2488 if (file)
2489 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2490 if (line)
2491 *line = SM.getInstantiationLineNumber(InstLoc);
2492 if (column)
2493 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002494 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002495 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002496}
2497
Douglas Gregora9b06d42010-11-09 06:24:54 +00002498void clang_getSpellingLocation(CXSourceLocation location,
2499 CXFile *file,
2500 unsigned *line,
2501 unsigned *column,
2502 unsigned *offset) {
2503 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2504
2505 if (!location.ptr_data[0] || Loc.isInvalid()) {
2506 if (file)
2507 *file = 0;
2508 if (line)
2509 *line = 0;
2510 if (column)
2511 *column = 0;
2512 if (offset)
2513 *offset = 0;
2514 return;
2515 }
2516
2517 const SourceManager &SM =
2518 *static_cast<const SourceManager*>(location.ptr_data[0]);
2519 SourceLocation SpellLoc = Loc;
2520 if (SpellLoc.isMacroID()) {
2521 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2522 if (SimpleSpellingLoc.isFileID() &&
2523 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2524 SpellLoc = SimpleSpellingLoc;
2525 else
2526 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2527 }
2528
2529 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2530 FileID FID = LocInfo.first;
2531 unsigned FileOffset = LocInfo.second;
2532
2533 if (file)
2534 *file = (void *)SM.getFileEntryForID(FID);
2535 if (line)
2536 *line = SM.getLineNumber(FID, FileOffset);
2537 if (column)
2538 *column = SM.getColumnNumber(FID, FileOffset);
2539 if (offset)
2540 *offset = FileOffset;
2541}
2542
Douglas Gregor1db19de2010-01-19 21:36:55 +00002543CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002544 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002545 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002546 return Result;
2547}
2548
2549CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002550 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002551 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002552 return Result;
2553}
2554
Douglas Gregorb9790342010-01-22 21:44:22 +00002555} // end: extern "C"
2556
Douglas Gregor1db19de2010-01-19 21:36:55 +00002557//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002558// CXFile Operations.
2559//===----------------------------------------------------------------------===//
2560
2561extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002562CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002563 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002564 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002565
Steve Naroff88145032009-10-27 14:35:18 +00002566 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002567 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002568}
2569
2570time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002571 if (!SFile)
2572 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002573
Steve Naroff88145032009-10-27 14:35:18 +00002574 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2575 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002576}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002577
Douglas Gregorb9790342010-01-22 21:44:22 +00002578CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2579 if (!tu)
2580 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Ted Kremeneka60ed472010-11-16 08:15:36 +00002582 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002583
Douglas Gregorb9790342010-01-22 21:44:22 +00002584 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002585 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2586 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002587 return const_cast<FileEntry *>(File);
2588}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002589
Ted Kremenekfb480492010-01-13 21:46:36 +00002590} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002591
Ted Kremenekfb480492010-01-13 21:46:36 +00002592//===----------------------------------------------------------------------===//
2593// CXCursor Operations.
2594//===----------------------------------------------------------------------===//
2595
Ted Kremenekfb480492010-01-13 21:46:36 +00002596static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002597 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2598 return getDeclFromExpr(CE->getSubExpr());
2599
Ted Kremenekfb480492010-01-13 21:46:36 +00002600 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2601 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002602 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2603 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002604 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2605 return ME->getMemberDecl();
2606 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2607 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002608 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2609 return PRE->getProperty();
2610
Ted Kremenekfb480492010-01-13 21:46:36 +00002611 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2612 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002613 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2614 if (!CE->isElidable())
2615 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002616 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2617 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002618
Douglas Gregordb1314e2010-10-01 21:11:22 +00002619 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2620 return PE->getProtocol();
2621
Ted Kremenekfb480492010-01-13 21:46:36 +00002622 return 0;
2623}
2624
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002625static SourceLocation getLocationFromExpr(Expr *E) {
2626 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2627 return /*FIXME:*/Msg->getLeftLoc();
2628 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2629 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002630 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2631 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002632 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2633 return Member->getMemberLoc();
2634 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2635 return Ivar->getLocation();
2636 return E->getLocStart();
2637}
2638
Ted Kremenekfb480492010-01-13 21:46:36 +00002639extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002640
2641unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002642 CXCursorVisitor visitor,
2643 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002644 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2645 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002646 return CursorVis.VisitChildren(parent);
2647}
2648
David Chisnall3387c652010-11-03 14:12:26 +00002649#ifndef __has_feature
2650#define __has_feature(x) 0
2651#endif
2652#if __has_feature(blocks)
2653typedef enum CXChildVisitResult
2654 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2655
2656static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2657 CXClientData client_data) {
2658 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2659 return block(cursor, parent);
2660}
2661#else
2662// If we are compiled with a compiler that doesn't have native blocks support,
2663// define and call the block manually, so the
2664typedef struct _CXChildVisitResult
2665{
2666 void *isa;
2667 int flags;
2668 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002669 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2670 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002671} *CXCursorVisitorBlock;
2672
2673static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2674 CXClientData client_data) {
2675 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2676 return block->invoke(block, cursor, parent);
2677}
2678#endif
2679
2680
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002681unsigned clang_visitChildrenWithBlock(CXCursor parent,
2682 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002683 return clang_visitChildren(parent, visitWithBlock, block);
2684}
2685
Douglas Gregor78205d42010-01-20 21:45:58 +00002686static CXString getDeclSpelling(Decl *D) {
2687 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002688 if (!ND) {
2689 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2690 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2691 return createCXString(Property->getIdentifier()->getName());
2692
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002693 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002694 }
2695
Douglas Gregor78205d42010-01-20 21:45:58 +00002696 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002697 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002698
Douglas Gregor78205d42010-01-20 21:45:58 +00002699 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2700 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2701 // and returns different names. NamedDecl returns the class name and
2702 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002703 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002704
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002705 if (isa<UsingDirectiveDecl>(D))
2706 return createCXString("");
2707
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002708 llvm::SmallString<1024> S;
2709 llvm::raw_svector_ostream os(S);
2710 ND->printName(os);
2711
2712 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002713}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002714
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002715CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002716 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002717 return clang_getTranslationUnitSpelling(
2718 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002719
Steve Narofff334b4e2009-09-02 18:26:48 +00002720 if (clang_isReference(C.kind)) {
2721 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002722 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002723 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002724 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002725 }
2726 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002727 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002728 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002729 }
2730 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002731 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002732 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002733 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002734 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002735 case CXCursor_CXXBaseSpecifier: {
2736 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2737 return createCXString(B->getType().getAsString());
2738 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002739 case CXCursor_TypeRef: {
2740 TypeDecl *Type = getCursorTypeRef(C).first;
2741 assert(Type && "Missing type decl");
2742
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002743 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2744 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002745 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002746 case CXCursor_TemplateRef: {
2747 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002748 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002749
2750 return createCXString(Template->getNameAsString());
2751 }
Douglas Gregor69319002010-08-31 23:48:11 +00002752
2753 case CXCursor_NamespaceRef: {
2754 NamedDecl *NS = getCursorNamespaceRef(C).first;
2755 assert(NS && "Missing namespace decl");
2756
2757 return createCXString(NS->getNameAsString());
2758 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002759
Douglas Gregora67e03f2010-09-09 21:42:20 +00002760 case CXCursor_MemberRef: {
2761 FieldDecl *Field = getCursorMemberRef(C).first;
2762 assert(Field && "Missing member decl");
2763
2764 return createCXString(Field->getNameAsString());
2765 }
2766
Douglas Gregor36897b02010-09-10 00:22:18 +00002767 case CXCursor_LabelRef: {
2768 LabelStmt *Label = getCursorLabelRef(C).first;
2769 assert(Label && "Missing label");
2770
2771 return createCXString(Label->getID()->getName());
2772 }
2773
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002774 case CXCursor_OverloadedDeclRef: {
2775 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2776 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2777 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2778 return createCXString(ND->getNameAsString());
2779 return createCXString("");
2780 }
2781 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2782 return createCXString(E->getName().getAsString());
2783 OverloadedTemplateStorage *Ovl
2784 = Storage.get<OverloadedTemplateStorage*>();
2785 if (Ovl->size() == 0)
2786 return createCXString("");
2787 return createCXString((*Ovl->begin())->getNameAsString());
2788 }
2789
Daniel Dunbaracca7252009-11-30 20:42:49 +00002790 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002791 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002792 }
2793 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002794
2795 if (clang_isExpression(C.kind)) {
2796 Decl *D = getDeclFromExpr(getCursorExpr(C));
2797 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002798 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002799 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002800 }
2801
Douglas Gregor36897b02010-09-10 00:22:18 +00002802 if (clang_isStatement(C.kind)) {
2803 Stmt *S = getCursorStmt(C);
2804 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2805 return createCXString(Label->getID()->getName());
2806
2807 return createCXString("");
2808 }
2809
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002810 if (C.kind == CXCursor_MacroInstantiation)
2811 return createCXString(getCursorMacroInstantiation(C)->getName()
2812 ->getNameStart());
2813
Douglas Gregor572feb22010-03-18 18:04:21 +00002814 if (C.kind == CXCursor_MacroDefinition)
2815 return createCXString(getCursorMacroDefinition(C)->getName()
2816 ->getNameStart());
2817
Douglas Gregorecdcb882010-10-20 22:00:55 +00002818 if (C.kind == CXCursor_InclusionDirective)
2819 return createCXString(getCursorInclusionDirective(C)->getFileName());
2820
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002821 if (clang_isDeclaration(C.kind))
2822 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002823
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002824 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002825}
2826
Douglas Gregor358559d2010-10-02 22:49:11 +00002827CXString clang_getCursorDisplayName(CXCursor C) {
2828 if (!clang_isDeclaration(C.kind))
2829 return clang_getCursorSpelling(C);
2830
2831 Decl *D = getCursorDecl(C);
2832 if (!D)
2833 return createCXString("");
2834
2835 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2836 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2837 D = FunTmpl->getTemplatedDecl();
2838
2839 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2840 llvm::SmallString<64> Str;
2841 llvm::raw_svector_ostream OS(Str);
2842 OS << Function->getNameAsString();
2843 if (Function->getPrimaryTemplate())
2844 OS << "<>";
2845 OS << "(";
2846 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2847 if (I)
2848 OS << ", ";
2849 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2850 }
2851
2852 if (Function->isVariadic()) {
2853 if (Function->getNumParams())
2854 OS << ", ";
2855 OS << "...";
2856 }
2857 OS << ")";
2858 return createCXString(OS.str());
2859 }
2860
2861 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2862 llvm::SmallString<64> Str;
2863 llvm::raw_svector_ostream OS(Str);
2864 OS << ClassTemplate->getNameAsString();
2865 OS << "<";
2866 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2867 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2868 if (I)
2869 OS << ", ";
2870
2871 NamedDecl *Param = Params->getParam(I);
2872 if (Param->getIdentifier()) {
2873 OS << Param->getIdentifier()->getName();
2874 continue;
2875 }
2876
2877 // There is no parameter name, which makes this tricky. Try to come up
2878 // with something useful that isn't too long.
2879 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2880 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2881 else if (NonTypeTemplateParmDecl *NTTP
2882 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2883 OS << NTTP->getType().getAsString(Policy);
2884 else
2885 OS << "template<...> class";
2886 }
2887
2888 OS << ">";
2889 return createCXString(OS.str());
2890 }
2891
2892 if (ClassTemplateSpecializationDecl *ClassSpec
2893 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2894 // If the type was explicitly written, use that.
2895 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2896 return createCXString(TSInfo->getType().getAsString(Policy));
2897
2898 llvm::SmallString<64> Str;
2899 llvm::raw_svector_ostream OS(Str);
2900 OS << ClassSpec->getNameAsString();
2901 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002902 ClassSpec->getTemplateArgs().data(),
2903 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002904 Policy);
2905 return createCXString(OS.str());
2906 }
2907
2908 return clang_getCursorSpelling(C);
2909}
2910
Ted Kremeneke68fff62010-02-17 00:41:32 +00002911CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002912 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002913 case CXCursor_FunctionDecl:
2914 return createCXString("FunctionDecl");
2915 case CXCursor_TypedefDecl:
2916 return createCXString("TypedefDecl");
2917 case CXCursor_EnumDecl:
2918 return createCXString("EnumDecl");
2919 case CXCursor_EnumConstantDecl:
2920 return createCXString("EnumConstantDecl");
2921 case CXCursor_StructDecl:
2922 return createCXString("StructDecl");
2923 case CXCursor_UnionDecl:
2924 return createCXString("UnionDecl");
2925 case CXCursor_ClassDecl:
2926 return createCXString("ClassDecl");
2927 case CXCursor_FieldDecl:
2928 return createCXString("FieldDecl");
2929 case CXCursor_VarDecl:
2930 return createCXString("VarDecl");
2931 case CXCursor_ParmDecl:
2932 return createCXString("ParmDecl");
2933 case CXCursor_ObjCInterfaceDecl:
2934 return createCXString("ObjCInterfaceDecl");
2935 case CXCursor_ObjCCategoryDecl:
2936 return createCXString("ObjCCategoryDecl");
2937 case CXCursor_ObjCProtocolDecl:
2938 return createCXString("ObjCProtocolDecl");
2939 case CXCursor_ObjCPropertyDecl:
2940 return createCXString("ObjCPropertyDecl");
2941 case CXCursor_ObjCIvarDecl:
2942 return createCXString("ObjCIvarDecl");
2943 case CXCursor_ObjCInstanceMethodDecl:
2944 return createCXString("ObjCInstanceMethodDecl");
2945 case CXCursor_ObjCClassMethodDecl:
2946 return createCXString("ObjCClassMethodDecl");
2947 case CXCursor_ObjCImplementationDecl:
2948 return createCXString("ObjCImplementationDecl");
2949 case CXCursor_ObjCCategoryImplDecl:
2950 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002951 case CXCursor_CXXMethod:
2952 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002953 case CXCursor_UnexposedDecl:
2954 return createCXString("UnexposedDecl");
2955 case CXCursor_ObjCSuperClassRef:
2956 return createCXString("ObjCSuperClassRef");
2957 case CXCursor_ObjCProtocolRef:
2958 return createCXString("ObjCProtocolRef");
2959 case CXCursor_ObjCClassRef:
2960 return createCXString("ObjCClassRef");
2961 case CXCursor_TypeRef:
2962 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002963 case CXCursor_TemplateRef:
2964 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002965 case CXCursor_NamespaceRef:
2966 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002967 case CXCursor_MemberRef:
2968 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002969 case CXCursor_LabelRef:
2970 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002971 case CXCursor_OverloadedDeclRef:
2972 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002973 case CXCursor_UnexposedExpr:
2974 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002975 case CXCursor_BlockExpr:
2976 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002977 case CXCursor_DeclRefExpr:
2978 return createCXString("DeclRefExpr");
2979 case CXCursor_MemberRefExpr:
2980 return createCXString("MemberRefExpr");
2981 case CXCursor_CallExpr:
2982 return createCXString("CallExpr");
2983 case CXCursor_ObjCMessageExpr:
2984 return createCXString("ObjCMessageExpr");
2985 case CXCursor_UnexposedStmt:
2986 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002987 case CXCursor_LabelStmt:
2988 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002989 case CXCursor_InvalidFile:
2990 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002991 case CXCursor_InvalidCode:
2992 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002993 case CXCursor_NoDeclFound:
2994 return createCXString("NoDeclFound");
2995 case CXCursor_NotImplemented:
2996 return createCXString("NotImplemented");
2997 case CXCursor_TranslationUnit:
2998 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002999 case CXCursor_UnexposedAttr:
3000 return createCXString("UnexposedAttr");
3001 case CXCursor_IBActionAttr:
3002 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003003 case CXCursor_IBOutletAttr:
3004 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003005 case CXCursor_IBOutletCollectionAttr:
3006 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003007 case CXCursor_PreprocessingDirective:
3008 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003009 case CXCursor_MacroDefinition:
3010 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003011 case CXCursor_MacroInstantiation:
3012 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003013 case CXCursor_InclusionDirective:
3014 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003015 case CXCursor_Namespace:
3016 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003017 case CXCursor_LinkageSpec:
3018 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003019 case CXCursor_CXXBaseSpecifier:
3020 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003021 case CXCursor_Constructor:
3022 return createCXString("CXXConstructor");
3023 case CXCursor_Destructor:
3024 return createCXString("CXXDestructor");
3025 case CXCursor_ConversionFunction:
3026 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003027 case CXCursor_TemplateTypeParameter:
3028 return createCXString("TemplateTypeParameter");
3029 case CXCursor_NonTypeTemplateParameter:
3030 return createCXString("NonTypeTemplateParameter");
3031 case CXCursor_TemplateTemplateParameter:
3032 return createCXString("TemplateTemplateParameter");
3033 case CXCursor_FunctionTemplate:
3034 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003035 case CXCursor_ClassTemplate:
3036 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003037 case CXCursor_ClassTemplatePartialSpecialization:
3038 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003039 case CXCursor_NamespaceAlias:
3040 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003041 case CXCursor_UsingDirective:
3042 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003043 case CXCursor_UsingDeclaration:
3044 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003045 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003046
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003047 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003048 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003049}
Steve Naroff89922f82009-08-31 00:59:03 +00003050
Ted Kremeneke68fff62010-02-17 00:41:32 +00003051enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3052 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003053 CXClientData client_data) {
3054 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003055
3056 // If our current best cursor is the construction of a temporary object,
3057 // don't replace that cursor with a type reference, because we want
3058 // clang_getCursor() to point at the constructor.
3059 if (clang_isExpression(BestCursor->kind) &&
3060 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3061 cursor.kind == CXCursor_TypeRef)
3062 return CXChildVisit_Recurse;
3063
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003064 *BestCursor = cursor;
3065 return CXChildVisit_Recurse;
3066}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003067
Douglas Gregorb9790342010-01-22 21:44:22 +00003068CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3069 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003070 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003071
Ted Kremeneka60ed472010-11-16 08:15:36 +00003072 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003073 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3074
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003075 // Translate the given source location to make it point at the beginning of
3076 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003077 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003078
3079 // Guard against an invalid SourceLocation, or we may assert in one
3080 // of the following calls.
3081 if (SLoc.isInvalid())
3082 return clang_getNullCursor();
3083
Douglas Gregor40749ee2010-11-03 00:35:38 +00003084 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003085 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3086 CXXUnit->getASTContext().getLangOptions());
3087
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003088 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3089 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003090 // FIXME: Would be great to have a "hint" cursor, then walk from that
3091 // hint cursor upward until we find a cursor whose source range encloses
3092 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003093 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3094 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003095 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003096 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003097 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003098
3099 if (Logging) {
3100 CXFile SearchFile;
3101 unsigned SearchLine, SearchColumn;
3102 CXFile ResultFile;
3103 unsigned ResultLine, ResultColumn;
3104 CXString SearchFileName, ResultFileName, KindSpelling;
3105 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3106
3107 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3108 0);
3109 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3110 &ResultColumn, 0);
3111 SearchFileName = clang_getFileName(SearchFile);
3112 ResultFileName = clang_getFileName(ResultFile);
3113 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3114 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3115 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3116 clang_getCString(KindSpelling),
3117 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3118 clang_disposeString(SearchFileName);
3119 clang_disposeString(ResultFileName);
3120 clang_disposeString(KindSpelling);
3121 }
3122
Ted Kremeneke68fff62010-02-17 00:41:32 +00003123 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003124}
3125
Ted Kremenek73885552009-11-17 19:28:59 +00003126CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003127 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003128}
3129
3130unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003131 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003132}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003133
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003134unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003135 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3136}
3137
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003138unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003139 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3140}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003141
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003142unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003143 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3144}
3145
Douglas Gregor97b98722010-01-19 23:20:36 +00003146unsigned clang_isExpression(enum CXCursorKind K) {
3147 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3148}
3149
3150unsigned clang_isStatement(enum CXCursorKind K) {
3151 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3152}
3153
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003154unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3155 return K == CXCursor_TranslationUnit;
3156}
3157
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003158unsigned clang_isPreprocessing(enum CXCursorKind K) {
3159 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3160}
3161
Ted Kremenekad6eff62010-03-08 21:17:29 +00003162unsigned clang_isUnexposed(enum CXCursorKind K) {
3163 switch (K) {
3164 case CXCursor_UnexposedDecl:
3165 case CXCursor_UnexposedExpr:
3166 case CXCursor_UnexposedStmt:
3167 case CXCursor_UnexposedAttr:
3168 return true;
3169 default:
3170 return false;
3171 }
3172}
3173
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003174CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003175 return C.kind;
3176}
3177
Douglas Gregor98258af2010-01-18 22:46:11 +00003178CXSourceLocation clang_getCursorLocation(CXCursor C) {
3179 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003180 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003181 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003182 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3183 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003184 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003185 }
3186
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003187 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003188 std::pair<ObjCProtocolDecl *, SourceLocation> P
3189 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003190 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003191 }
3192
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003193 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003194 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3195 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003196 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003197 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003198
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003199 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003200 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003201 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003202 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003203
3204 case CXCursor_TemplateRef: {
3205 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3206 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3207 }
3208
Douglas Gregor69319002010-08-31 23:48:11 +00003209 case CXCursor_NamespaceRef: {
3210 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3211 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3212 }
3213
Douglas Gregora67e03f2010-09-09 21:42:20 +00003214 case CXCursor_MemberRef: {
3215 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3216 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3217 }
3218
Ted Kremenek3064ef92010-08-27 21:34:58 +00003219 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003220 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3221 if (!BaseSpec)
3222 return clang_getNullLocation();
3223
3224 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3225 return cxloc::translateSourceLocation(getCursorContext(C),
3226 TSInfo->getTypeLoc().getBeginLoc());
3227
3228 return cxloc::translateSourceLocation(getCursorContext(C),
3229 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003230 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003231
Douglas Gregor36897b02010-09-10 00:22:18 +00003232 case CXCursor_LabelRef: {
3233 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3234 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3235 }
3236
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003237 case CXCursor_OverloadedDeclRef:
3238 return cxloc::translateSourceLocation(getCursorContext(C),
3239 getCursorOverloadedDeclRef(C).second);
3240
Douglas Gregorf46034a2010-01-18 23:41:10 +00003241 default:
3242 // FIXME: Need a way to enumerate all non-reference cases.
3243 llvm_unreachable("Missed a reference kind");
3244 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003245 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003246
3247 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003248 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003249 getLocationFromExpr(getCursorExpr(C)));
3250
Douglas Gregor36897b02010-09-10 00:22:18 +00003251 if (clang_isStatement(C.kind))
3252 return cxloc::translateSourceLocation(getCursorContext(C),
3253 getCursorStmt(C)->getLocStart());
3254
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003255 if (C.kind == CXCursor_PreprocessingDirective) {
3256 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3257 return cxloc::translateSourceLocation(getCursorContext(C), L);
3258 }
Douglas Gregor48072312010-03-18 15:23:44 +00003259
3260 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003261 SourceLocation L
3262 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003263 return cxloc::translateSourceLocation(getCursorContext(C), L);
3264 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003265
3266 if (C.kind == CXCursor_MacroDefinition) {
3267 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3268 return cxloc::translateSourceLocation(getCursorContext(C), L);
3269 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003270
3271 if (C.kind == CXCursor_InclusionDirective) {
3272 SourceLocation L
3273 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3274 return cxloc::translateSourceLocation(getCursorContext(C), L);
3275 }
3276
Ted Kremenek9a700d22010-05-12 06:16:13 +00003277 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003278 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003279
Douglas Gregorf46034a2010-01-18 23:41:10 +00003280 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003281 SourceLocation Loc = D->getLocation();
3282 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3283 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003284 // FIXME: Multiple variables declared in a single declaration
3285 // currently lack the information needed to correctly determine their
3286 // ranges when accounting for the type-specifier. We use context
3287 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3288 // and if so, whether it is the first decl.
3289 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3290 if (!cxcursor::isFirstInDeclGroup(C))
3291 Loc = VD->getLocation();
3292 }
3293
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003294 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003295}
Douglas Gregora7bde202010-01-19 00:34:46 +00003296
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003297} // end extern "C"
3298
3299static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003300 if (clang_isReference(C.kind)) {
3301 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003302 case CXCursor_ObjCSuperClassRef:
3303 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003304
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003305 case CXCursor_ObjCProtocolRef:
3306 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003307
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003308 case CXCursor_ObjCClassRef:
3309 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003310
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003311 case CXCursor_TypeRef:
3312 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003313
3314 case CXCursor_TemplateRef:
3315 return getCursorTemplateRef(C).second;
3316
Douglas Gregor69319002010-08-31 23:48:11 +00003317 case CXCursor_NamespaceRef:
3318 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003319
3320 case CXCursor_MemberRef:
3321 return getCursorMemberRef(C).second;
3322
Ted Kremenek3064ef92010-08-27 21:34:58 +00003323 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003324 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003325
Douglas Gregor36897b02010-09-10 00:22:18 +00003326 case CXCursor_LabelRef:
3327 return getCursorLabelRef(C).second;
3328
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003329 case CXCursor_OverloadedDeclRef:
3330 return getCursorOverloadedDeclRef(C).second;
3331
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003332 default:
3333 // FIXME: Need a way to enumerate all non-reference cases.
3334 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003335 }
3336 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003337
3338 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003339 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003340
3341 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003342 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003343
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003344 if (C.kind == CXCursor_PreprocessingDirective)
3345 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003346
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003347 if (C.kind == CXCursor_MacroInstantiation)
3348 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003349
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003350 if (C.kind == CXCursor_MacroDefinition)
3351 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003352
3353 if (C.kind == CXCursor_InclusionDirective)
3354 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3355
Ted Kremenek007a7c92010-11-01 23:26:51 +00003356 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3357 Decl *D = cxcursor::getCursorDecl(C);
3358 SourceRange R = D->getSourceRange();
3359 // FIXME: Multiple variables declared in a single declaration
3360 // currently lack the information needed to correctly determine their
3361 // ranges when accounting for the type-specifier. We use context
3362 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3363 // and if so, whether it is the first decl.
3364 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3365 if (!cxcursor::isFirstInDeclGroup(C))
3366 R.setBegin(VD->getLocation());
3367 }
3368 return R;
3369 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003370 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003371
3372extern "C" {
3373
3374CXSourceRange clang_getCursorExtent(CXCursor C) {
3375 SourceRange R = getRawCursorExtent(C);
3376 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003377 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003378
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003379 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003380}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003381
3382CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003383 if (clang_isInvalid(C.kind))
3384 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003385
Ted Kremeneka60ed472010-11-16 08:15:36 +00003386 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003387 if (clang_isDeclaration(C.kind)) {
3388 Decl *D = getCursorDecl(C);
3389 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003390 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003391 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003392 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003393 if (ObjCForwardProtocolDecl *Protocols
3394 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003395 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003396 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3397 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3398 return MakeCXCursor(Property, tu);
3399
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003400 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003401 }
3402
Douglas Gregor97b98722010-01-19 23:20:36 +00003403 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003404 Expr *E = getCursorExpr(C);
3405 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003406 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003407 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003408
3409 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003410 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003411
Douglas Gregor97b98722010-01-19 23:20:36 +00003412 return clang_getNullCursor();
3413 }
3414
Douglas Gregor36897b02010-09-10 00:22:18 +00003415 if (clang_isStatement(C.kind)) {
3416 Stmt *S = getCursorStmt(C);
3417 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003418 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003419
3420 return clang_getNullCursor();
3421 }
3422
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003423 if (C.kind == CXCursor_MacroInstantiation) {
3424 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003425 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003426 }
3427
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003428 if (!clang_isReference(C.kind))
3429 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003430
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003431 switch (C.kind) {
3432 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003433 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003434
3435 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003436 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003437
3438 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003439 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003440
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003441 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003442 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003443
3444 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003445 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003446
Douglas Gregor69319002010-08-31 23:48:11 +00003447 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003448 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003449
Douglas Gregora67e03f2010-09-09 21:42:20 +00003450 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003451 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003452
Ted Kremenek3064ef92010-08-27 21:34:58 +00003453 case CXCursor_CXXBaseSpecifier: {
3454 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3455 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003456 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003457 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003458
Douglas Gregor36897b02010-09-10 00:22:18 +00003459 case CXCursor_LabelRef:
3460 // FIXME: We end up faking the "parent" declaration here because we
3461 // don't want to make CXCursor larger.
3462 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003463 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3464 .getTranslationUnitDecl(),
3465 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003466
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003467 case CXCursor_OverloadedDeclRef:
3468 return C;
3469
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003470 default:
3471 // We would prefer to enumerate all non-reference cursor kinds here.
3472 llvm_unreachable("Unhandled reference cursor kind");
3473 break;
3474 }
3475 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003476
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003477 return clang_getNullCursor();
3478}
3479
Douglas Gregorb6998662010-01-19 19:34:47 +00003480CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003481 if (clang_isInvalid(C.kind))
3482 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003483
Ted Kremeneka60ed472010-11-16 08:15:36 +00003484 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003485
Douglas Gregorb6998662010-01-19 19:34:47 +00003486 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003487 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003488 C = clang_getCursorReferenced(C);
3489 WasReference = true;
3490 }
3491
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003492 if (C.kind == CXCursor_MacroInstantiation)
3493 return clang_getCursorReferenced(C);
3494
Douglas Gregorb6998662010-01-19 19:34:47 +00003495 if (!clang_isDeclaration(C.kind))
3496 return clang_getNullCursor();
3497
3498 Decl *D = getCursorDecl(C);
3499 if (!D)
3500 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003501
Douglas Gregorb6998662010-01-19 19:34:47 +00003502 switch (D->getKind()) {
3503 // Declaration kinds that don't really separate the notions of
3504 // declaration and definition.
3505 case Decl::Namespace:
3506 case Decl::Typedef:
3507 case Decl::TemplateTypeParm:
3508 case Decl::EnumConstant:
3509 case Decl::Field:
3510 case Decl::ObjCIvar:
3511 case Decl::ObjCAtDefsField:
3512 case Decl::ImplicitParam:
3513 case Decl::ParmVar:
3514 case Decl::NonTypeTemplateParm:
3515 case Decl::TemplateTemplateParm:
3516 case Decl::ObjCCategoryImpl:
3517 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003518 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003519 case Decl::LinkageSpec:
3520 case Decl::ObjCPropertyImpl:
3521 case Decl::FileScopeAsm:
3522 case Decl::StaticAssert:
3523 case Decl::Block:
3524 return C;
3525
3526 // Declaration kinds that don't make any sense here, but are
3527 // nonetheless harmless.
3528 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003529 break;
3530
3531 // Declaration kinds for which the definition is not resolvable.
3532 case Decl::UnresolvedUsingTypename:
3533 case Decl::UnresolvedUsingValue:
3534 break;
3535
3536 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003537 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003538 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003539
3540 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003541 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003542
3543 case Decl::Enum:
3544 case Decl::Record:
3545 case Decl::CXXRecord:
3546 case Decl::ClassTemplateSpecialization:
3547 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003548 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003549 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003550 return clang_getNullCursor();
3551
3552 case Decl::Function:
3553 case Decl::CXXMethod:
3554 case Decl::CXXConstructor:
3555 case Decl::CXXDestructor:
3556 case Decl::CXXConversion: {
3557 const FunctionDecl *Def = 0;
3558 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003559 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003560 return clang_getNullCursor();
3561 }
3562
3563 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003564 // Ask the variable if it has a definition.
3565 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003566 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003567 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003568 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003569
Douglas Gregorb6998662010-01-19 19:34:47 +00003570 case Decl::FunctionTemplate: {
3571 const FunctionDecl *Def = 0;
3572 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003573 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003574 return clang_getNullCursor();
3575 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003576
Douglas Gregorb6998662010-01-19 19:34:47 +00003577 case Decl::ClassTemplate: {
3578 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003579 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003580 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003581 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003582 return clang_getNullCursor();
3583 }
3584
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003585 case Decl::Using:
3586 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003587 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003588
3589 case Decl::UsingShadow:
3590 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003591 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003592 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003593
3594 case Decl::ObjCMethod: {
3595 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3596 if (Method->isThisDeclarationADefinition())
3597 return C;
3598
3599 // Dig out the method definition in the associated
3600 // @implementation, if we have it.
3601 // FIXME: The ASTs should make finding the definition easier.
3602 if (ObjCInterfaceDecl *Class
3603 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3604 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3605 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3606 Method->isInstanceMethod()))
3607 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003608 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003609
3610 return clang_getNullCursor();
3611 }
3612
3613 case Decl::ObjCCategory:
3614 if (ObjCCategoryImplDecl *Impl
3615 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003616 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003617 return clang_getNullCursor();
3618
3619 case Decl::ObjCProtocol:
3620 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3621 return C;
3622 return clang_getNullCursor();
3623
3624 case Decl::ObjCInterface:
3625 // There are two notions of a "definition" for an Objective-C
3626 // class: the interface and its implementation. When we resolved a
3627 // reference to an Objective-C class, produce the @interface as
3628 // the definition; when we were provided with the interface,
3629 // produce the @implementation as the definition.
3630 if (WasReference) {
3631 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3632 return C;
3633 } else if (ObjCImplementationDecl *Impl
3634 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003635 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003636 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003637
Douglas Gregorb6998662010-01-19 19:34:47 +00003638 case Decl::ObjCProperty:
3639 // FIXME: We don't really know where to find the
3640 // ObjCPropertyImplDecls that implement this property.
3641 return clang_getNullCursor();
3642
3643 case Decl::ObjCCompatibleAlias:
3644 if (ObjCInterfaceDecl *Class
3645 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3646 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003647 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003648
Douglas Gregorb6998662010-01-19 19:34:47 +00003649 return clang_getNullCursor();
3650
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003651 case Decl::ObjCForwardProtocol:
3652 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003653 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003654
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003655 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003656 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003657 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003658
3659 case Decl::Friend:
3660 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003661 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003662 return clang_getNullCursor();
3663
3664 case Decl::FriendTemplate:
3665 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003666 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003667 return clang_getNullCursor();
3668 }
3669
3670 return clang_getNullCursor();
3671}
3672
3673unsigned clang_isCursorDefinition(CXCursor C) {
3674 if (!clang_isDeclaration(C.kind))
3675 return 0;
3676
3677 return clang_getCursorDefinition(C) == C;
3678}
3679
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003680unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003681 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003682 return 0;
3683
3684 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3685 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3686 return E->getNumDecls();
3687
3688 if (OverloadedTemplateStorage *S
3689 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3690 return S->size();
3691
3692 Decl *D = Storage.get<Decl*>();
3693 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003694 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003695 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3696 return Classes->size();
3697 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3698 return Protocols->protocol_size();
3699
3700 return 0;
3701}
3702
3703CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003704 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003705 return clang_getNullCursor();
3706
3707 if (index >= clang_getNumOverloadedDecls(cursor))
3708 return clang_getNullCursor();
3709
Ted Kremeneka60ed472010-11-16 08:15:36 +00003710 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003711 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3712 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003713 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003714
3715 if (OverloadedTemplateStorage *S
3716 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003717 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003718
3719 Decl *D = Storage.get<Decl*>();
3720 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3721 // FIXME: This is, unfortunately, linear time.
3722 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3723 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003724 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003725 }
3726
3727 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003728 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003729
3730 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003731 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003732
3733 return clang_getNullCursor();
3734}
3735
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003736void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003737 const char **startBuf,
3738 const char **endBuf,
3739 unsigned *startLine,
3740 unsigned *startColumn,
3741 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003742 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003743 assert(getCursorDecl(C) && "CXCursor has null decl");
3744 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003745 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3746 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003747
Steve Naroff4ade6d62009-09-23 17:52:52 +00003748 SourceManager &SM = FD->getASTContext().getSourceManager();
3749 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3750 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3751 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3752 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3753 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3754 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3755}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003756
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003757void clang_enableStackTraces(void) {
3758 llvm::sys::PrintStackTraceOnErrorSignal();
3759}
3760
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003761void clang_executeOnThread(void (*fn)(void*), void *user_data,
3762 unsigned stack_size) {
3763 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3764}
3765
Ted Kremenekfb480492010-01-13 21:46:36 +00003766} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003767
Ted Kremenekfb480492010-01-13 21:46:36 +00003768//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003769// Token-based Operations.
3770//===----------------------------------------------------------------------===//
3771
3772/* CXToken layout:
3773 * int_data[0]: a CXTokenKind
3774 * int_data[1]: starting token location
3775 * int_data[2]: token length
3776 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003777 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003778 * otherwise unused.
3779 */
3780extern "C" {
3781
3782CXTokenKind clang_getTokenKind(CXToken CXTok) {
3783 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3784}
3785
3786CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3787 switch (clang_getTokenKind(CXTok)) {
3788 case CXToken_Identifier:
3789 case CXToken_Keyword:
3790 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003791 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3792 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003793
3794 case CXToken_Literal: {
3795 // We have stashed the starting pointer in the ptr_data field. Use it.
3796 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003797 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003798 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003799
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003800 case CXToken_Punctuation:
3801 case CXToken_Comment:
3802 break;
3803 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003804
3805 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003806 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003807 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003808 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003809 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003810
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003811 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3812 std::pair<FileID, unsigned> LocInfo
3813 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003814 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003815 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003816 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3817 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003818 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003819
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003820 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003821}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003822
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003823CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003824 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003825 if (!CXXUnit)
3826 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003827
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003828 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3829 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3830}
3831
3832CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003833 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003834 if (!CXXUnit)
3835 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
3837 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003838 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3839}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003840
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003841void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3842 CXToken **Tokens, unsigned *NumTokens) {
3843 if (Tokens)
3844 *Tokens = 0;
3845 if (NumTokens)
3846 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
Ted Kremeneka60ed472010-11-16 08:15:36 +00003848 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003849 if (!CXXUnit || !Tokens || !NumTokens)
3850 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851
Douglas Gregorbdf60622010-03-05 21:16:25 +00003852 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3853
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003854 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855 if (R.isInvalid())
3856 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003857
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003858 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3859 std::pair<FileID, unsigned> BeginLocInfo
3860 = SourceMgr.getDecomposedLoc(R.getBegin());
3861 std::pair<FileID, unsigned> EndLocInfo
3862 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 // Cannot tokenize across files.
3865 if (BeginLocInfo.first != EndLocInfo.first)
3866 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003867
3868 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003869 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003870 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003871 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003872 if (Invalid)
3873 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003874
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003875 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3876 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003877 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003879
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003880 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003881 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003882 llvm::SmallVector<CXToken, 32> CXTokens;
3883 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003884 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003885 do {
3886 // Lex the next token
3887 Lex.LexFromRawLexer(Tok);
3888 if (Tok.is(tok::eof))
3889 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003890
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891 // Initialize the CXToken.
3892 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003893
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 // - Common fields
3895 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3896 CXTok.int_data[2] = Tok.getLength();
3897 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003898
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003899 // - Kind-specific fields
3900 if (Tok.isLiteral()) {
3901 CXTok.int_data[0] = CXToken_Literal;
3902 CXTok.ptr_data = (void *)Tok.getLiteralData();
3903 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003904 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003905 std::pair<FileID, unsigned> LocInfo
3906 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003907 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003908 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003909 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3910 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003911 return;
3912
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003913 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003914 IdentifierInfo *II
3915 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003916
David Chisnall096428b2010-10-13 21:44:48 +00003917 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003918 CXTok.int_data[0] = CXToken_Keyword;
3919 }
3920 else {
3921 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3922 CXToken_Identifier
3923 : CXToken_Keyword;
3924 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003925 CXTok.ptr_data = II;
3926 } else if (Tok.is(tok::comment)) {
3927 CXTok.int_data[0] = CXToken_Comment;
3928 CXTok.ptr_data = 0;
3929 } else {
3930 CXTok.int_data[0] = CXToken_Punctuation;
3931 CXTok.ptr_data = 0;
3932 }
3933 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003934 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003935 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003936
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003937 if (CXTokens.empty())
3938 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003939
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003940 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3941 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3942 *NumTokens = CXTokens.size();
3943}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003944
Ted Kremenek6db61092010-05-05 00:55:15 +00003945void clang_disposeTokens(CXTranslationUnit TU,
3946 CXToken *Tokens, unsigned NumTokens) {
3947 free(Tokens);
3948}
3949
3950} // end: extern "C"
3951
3952//===----------------------------------------------------------------------===//
3953// Token annotation APIs.
3954//===----------------------------------------------------------------------===//
3955
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003956typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003957static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3958 CXCursor parent,
3959 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003960namespace {
3961class AnnotateTokensWorker {
3962 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003963 CXToken *Tokens;
3964 CXCursor *Cursors;
3965 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003966 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003967 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003968 CursorVisitor AnnotateVis;
3969 SourceManager &SrcMgr;
3970
3971 bool MoreTokens() const { return TokIdx < NumTokens; }
3972 unsigned NextToken() const { return TokIdx; }
3973 void AdvanceToken() { ++TokIdx; }
3974 SourceLocation GetTokenLoc(unsigned tokI) {
3975 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3976 }
3977
Ted Kremenek6db61092010-05-05 00:55:15 +00003978public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003979 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003980 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003981 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003982 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003983 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003984 AnnotateVis(tu,
3985 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003986 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003987 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003988
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003989 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003990 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003991 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003992 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003993 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00003994 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003995};
3996}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003997
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003998void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3999 // Walk the AST within the region of interest, annotating tokens
4000 // along the way.
4001 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004002
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004003 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4004 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004005 if (Pos != Annotated.end() &&
4006 (clang_isInvalid(Cursors[I].kind) ||
4007 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004008 Cursors[I] = Pos->second;
4009 }
4010
4011 // Finish up annotating any tokens left.
4012 if (!MoreTokens())
4013 return;
4014
4015 const CXCursor &C = clang_getNullCursor();
4016 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4017 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4018 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004019 }
4020}
4021
Ted Kremenek6db61092010-05-05 00:55:15 +00004022enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004023AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004024 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004025 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004026 if (cursorRange.isInvalid())
4027 return CXChildVisit_Recurse;
4028
Douglas Gregor4419b672010-10-21 06:10:04 +00004029 if (clang_isPreprocessing(cursor.kind)) {
4030 // For macro instantiations, just note where the beginning of the macro
4031 // instantiation occurs.
4032 if (cursor.kind == CXCursor_MacroInstantiation) {
4033 Annotated[Loc.int_data] = cursor;
4034 return CXChildVisit_Recurse;
4035 }
4036
Douglas Gregor4419b672010-10-21 06:10:04 +00004037 // Items in the preprocessing record are kept separate from items in
4038 // declarations, so we keep a separate token index.
4039 unsigned SavedTokIdx = TokIdx;
4040 TokIdx = PreprocessingTokIdx;
4041
4042 // Skip tokens up until we catch up to the beginning of the preprocessing
4043 // entry.
4044 while (MoreTokens()) {
4045 const unsigned I = NextToken();
4046 SourceLocation TokLoc = GetTokenLoc(I);
4047 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4048 case RangeBefore:
4049 AdvanceToken();
4050 continue;
4051 case RangeAfter:
4052 case RangeOverlap:
4053 break;
4054 }
4055 break;
4056 }
4057
4058 // Look at all of the tokens within this range.
4059 while (MoreTokens()) {
4060 const unsigned I = NextToken();
4061 SourceLocation TokLoc = GetTokenLoc(I);
4062 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4063 case RangeBefore:
4064 assert(0 && "Infeasible");
4065 case RangeAfter:
4066 break;
4067 case RangeOverlap:
4068 Cursors[I] = cursor;
4069 AdvanceToken();
4070 continue;
4071 }
4072 break;
4073 }
4074
4075 // Save the preprocessing token index; restore the non-preprocessing
4076 // token index.
4077 PreprocessingTokIdx = TokIdx;
4078 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004079 return CXChildVisit_Recurse;
4080 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004081
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004082 if (cursorRange.isInvalid())
4083 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004084
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004085 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4086
Ted Kremeneka333c662010-05-12 05:29:33 +00004087 // Adjust the annotated range based specific declarations.
4088 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4089 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004090 Decl *D = cxcursor::getCursorDecl(cursor);
4091 // Don't visit synthesized ObjC methods, since they have no syntatic
4092 // representation in the source.
4093 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4094 if (MD->isSynthesized())
4095 return CXChildVisit_Continue;
4096 }
4097 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004098 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4099 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004100 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004101 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004102 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004103 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004104 }
4105 }
4106 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004107
Ted Kremenek3f404602010-08-14 01:14:06 +00004108 // If the location of the cursor occurs within a macro instantiation, record
4109 // the spelling location of the cursor in our annotation map. We can then
4110 // paper over the token labelings during a post-processing step to try and
4111 // get cursor mappings for tokens that are the *arguments* of a macro
4112 // instantiation.
4113 if (L.isMacroID()) {
4114 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4115 // Only invalidate the old annotation if it isn't part of a preprocessing
4116 // directive. Here we assume that the default construction of CXCursor
4117 // results in CXCursor.kind being an initialized value (i.e., 0). If
4118 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004119
Ted Kremenek3f404602010-08-14 01:14:06 +00004120 CXCursor &oldC = Annotated[rawEncoding];
4121 if (!clang_isPreprocessing(oldC.kind))
4122 oldC = cursor;
4123 }
4124
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004125 const enum CXCursorKind K = clang_getCursorKind(parent);
4126 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004127 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4128 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004129
4130 while (MoreTokens()) {
4131 const unsigned I = NextToken();
4132 SourceLocation TokLoc = GetTokenLoc(I);
4133 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4134 case RangeBefore:
4135 Cursors[I] = updateC;
4136 AdvanceToken();
4137 continue;
4138 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004139 case RangeOverlap:
4140 break;
4141 }
4142 break;
4143 }
4144
4145 // Visit children to get their cursor information.
4146 const unsigned BeforeChildren = NextToken();
4147 VisitChildren(cursor);
4148 const unsigned AfterChildren = NextToken();
4149
4150 // Adjust 'Last' to the last token within the extent of the cursor.
4151 while (MoreTokens()) {
4152 const unsigned I = NextToken();
4153 SourceLocation TokLoc = GetTokenLoc(I);
4154 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4155 case RangeBefore:
4156 assert(0 && "Infeasible");
4157 case RangeAfter:
4158 break;
4159 case RangeOverlap:
4160 Cursors[I] = updateC;
4161 AdvanceToken();
4162 continue;
4163 }
4164 break;
4165 }
4166 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004167
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004168 // Scan the tokens that are at the beginning of the cursor, but are not
4169 // capture by the child cursors.
4170
4171 // For AST elements within macros, rely on a post-annotate pass to
4172 // to correctly annotate the tokens with cursors. Otherwise we can
4173 // get confusing results of having tokens that map to cursors that really
4174 // are expanded by an instantiation.
4175 if (L.isMacroID())
4176 cursor = clang_getNullCursor();
4177
4178 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4179 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4180 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004181
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004182 Cursors[I] = cursor;
4183 }
4184 // Scan the tokens that are at the end of the cursor, but are not captured
4185 // but the child cursors.
4186 for (unsigned I = AfterChildren; I != Last; ++I)
4187 Cursors[I] = cursor;
4188
4189 TokIdx = Last;
4190 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004191}
4192
Ted Kremenek6db61092010-05-05 00:55:15 +00004193static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4194 CXCursor parent,
4195 CXClientData client_data) {
4196 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4197}
4198
Ted Kremenekab979612010-11-11 08:05:23 +00004199// This gets run a separate thread to avoid stack blowout.
4200static void runAnnotateTokensWorker(void *UserData) {
4201 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4202}
4203
Ted Kremenek6db61092010-05-05 00:55:15 +00004204extern "C" {
4205
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004206void clang_annotateTokens(CXTranslationUnit TU,
4207 CXToken *Tokens, unsigned NumTokens,
4208 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004209
4210 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004211 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004212
Douglas Gregor4419b672010-10-21 06:10:04 +00004213 // Any token we don't specifically annotate will have a NULL cursor.
4214 CXCursor C = clang_getNullCursor();
4215 for (unsigned I = 0; I != NumTokens; ++I)
4216 Cursors[I] = C;
4217
Ted Kremeneka60ed472010-11-16 08:15:36 +00004218 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004219 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004220 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004221
Douglas Gregorbdf60622010-03-05 21:16:25 +00004222 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004223
Douglas Gregor0396f462010-03-19 05:22:59 +00004224 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004225 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004226 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4227 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004228 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4229 clang_getTokenLocation(TU,
4230 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004231
Douglas Gregor0396f462010-03-19 05:22:59 +00004232 // A mapping from the source locations found when re-lexing or traversing the
4233 // region of interest to the corresponding cursors.
4234 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004235
4236 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004237 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004238 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4239 std::pair<FileID, unsigned> BeginLocInfo
4240 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4241 std::pair<FileID, unsigned> EndLocInfo
4242 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004243
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004244 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004245 bool Invalid = false;
4246 if (BeginLocInfo.first == EndLocInfo.first &&
4247 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4248 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004249 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4250 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004251 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004252 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004254
4255 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004256 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004257 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004258 Token Tok;
4259 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004260
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004261 reprocess:
4262 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4263 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004264 // don't see it while preprocessing these tokens later, but keep track
4265 // of all of the token locations inside this preprocessing directive so
4266 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004267 //
4268 // FIXME: Some simple tests here could identify macro definitions and
4269 // #undefs, to provide specific cursor kinds for those.
4270 std::vector<SourceLocation> Locations;
4271 do {
4272 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004273 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004274 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004275
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004276 using namespace cxcursor;
4277 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004278 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4279 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004280 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004281 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4282 Annotated[Locations[I].getRawEncoding()] = Cursor;
4283 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004284
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004285 if (Tok.isAtStartOfLine())
4286 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004287
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004288 continue;
4289 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004290
Douglas Gregor48072312010-03-18 15:23:44 +00004291 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004292 break;
4293 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004294 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004295
Douglas Gregor0396f462010-03-19 05:22:59 +00004296 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004297 // a specific cursor.
4298 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004299 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004300
4301 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004302 // FIXME: We use a ridiculous stack size here because the data-recursion
4303 // algorithm uses a large stack frame than the non-data recursive version,
4304 // and AnnotationTokensWorker currently transforms the data-recursion
4305 // algorithm back into a traditional recursion by explicitly calling
4306 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004307 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004308 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4309 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004310 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4311 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004312}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004313} // end: extern "C"
4314
4315//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004316// Operations for querying linkage of a cursor.
4317//===----------------------------------------------------------------------===//
4318
4319extern "C" {
4320CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004321 if (!clang_isDeclaration(cursor.kind))
4322 return CXLinkage_Invalid;
4323
Ted Kremenek16b42592010-03-03 06:36:57 +00004324 Decl *D = cxcursor::getCursorDecl(cursor);
4325 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4326 switch (ND->getLinkage()) {
4327 case NoLinkage: return CXLinkage_NoLinkage;
4328 case InternalLinkage: return CXLinkage_Internal;
4329 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4330 case ExternalLinkage: return CXLinkage_External;
4331 };
4332
4333 return CXLinkage_Invalid;
4334}
4335} // end: extern "C"
4336
4337//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004338// Operations for querying language of a cursor.
4339//===----------------------------------------------------------------------===//
4340
4341static CXLanguageKind getDeclLanguage(const Decl *D) {
4342 switch (D->getKind()) {
4343 default:
4344 break;
4345 case Decl::ImplicitParam:
4346 case Decl::ObjCAtDefsField:
4347 case Decl::ObjCCategory:
4348 case Decl::ObjCCategoryImpl:
4349 case Decl::ObjCClass:
4350 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004351 case Decl::ObjCForwardProtocol:
4352 case Decl::ObjCImplementation:
4353 case Decl::ObjCInterface:
4354 case Decl::ObjCIvar:
4355 case Decl::ObjCMethod:
4356 case Decl::ObjCProperty:
4357 case Decl::ObjCPropertyImpl:
4358 case Decl::ObjCProtocol:
4359 return CXLanguage_ObjC;
4360 case Decl::CXXConstructor:
4361 case Decl::CXXConversion:
4362 case Decl::CXXDestructor:
4363 case Decl::CXXMethod:
4364 case Decl::CXXRecord:
4365 case Decl::ClassTemplate:
4366 case Decl::ClassTemplatePartialSpecialization:
4367 case Decl::ClassTemplateSpecialization:
4368 case Decl::Friend:
4369 case Decl::FriendTemplate:
4370 case Decl::FunctionTemplate:
4371 case Decl::LinkageSpec:
4372 case Decl::Namespace:
4373 case Decl::NamespaceAlias:
4374 case Decl::NonTypeTemplateParm:
4375 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004376 case Decl::TemplateTemplateParm:
4377 case Decl::TemplateTypeParm:
4378 case Decl::UnresolvedUsingTypename:
4379 case Decl::UnresolvedUsingValue:
4380 case Decl::Using:
4381 case Decl::UsingDirective:
4382 case Decl::UsingShadow:
4383 return CXLanguage_CPlusPlus;
4384 }
4385
4386 return CXLanguage_C;
4387}
4388
4389extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004390
4391enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4392 if (clang_isDeclaration(cursor.kind))
4393 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4394 if (D->hasAttr<UnavailableAttr>() ||
4395 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4396 return CXAvailability_Available;
4397
4398 if (D->hasAttr<DeprecatedAttr>())
4399 return CXAvailability_Deprecated;
4400 }
4401
4402 return CXAvailability_Available;
4403}
4404
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004405CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4406 if (clang_isDeclaration(cursor.kind))
4407 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4408
4409 return CXLanguage_Invalid;
4410}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004411
4412CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4413 if (clang_isDeclaration(cursor.kind)) {
4414 if (Decl *D = getCursorDecl(cursor)) {
4415 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004416 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004417 }
4418 }
4419
4420 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4421 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004422 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004423 }
4424
4425 return clang_getNullCursor();
4426}
4427
4428CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4429 if (clang_isDeclaration(cursor.kind)) {
4430 if (Decl *D = getCursorDecl(cursor)) {
4431 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004432 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004433 }
4434 }
4435
4436 // FIXME: Note that we can't easily compute the lexical context of a
4437 // statement or expression, so we return nothing.
4438 return clang_getNullCursor();
4439}
4440
Douglas Gregor9f592342010-10-01 20:25:15 +00004441static void CollectOverriddenMethods(DeclContext *Ctx,
4442 ObjCMethodDecl *Method,
4443 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4444 if (!Ctx)
4445 return;
4446
4447 // If we have a class or category implementation, jump straight to the
4448 // interface.
4449 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4450 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4451
4452 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4453 if (!Container)
4454 return;
4455
4456 // Check whether we have a matching method at this level.
4457 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4458 Method->isInstanceMethod()))
4459 if (Method != Overridden) {
4460 // We found an override at this level; there is no need to look
4461 // into other protocols or categories.
4462 Methods.push_back(Overridden);
4463 return;
4464 }
4465
4466 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4467 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4468 PEnd = Protocol->protocol_end();
4469 P != PEnd; ++P)
4470 CollectOverriddenMethods(*P, Method, Methods);
4471 }
4472
4473 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4474 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4475 PEnd = Category->protocol_end();
4476 P != PEnd; ++P)
4477 CollectOverriddenMethods(*P, Method, Methods);
4478 }
4479
4480 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4481 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4482 PEnd = Interface->protocol_end();
4483 P != PEnd; ++P)
4484 CollectOverriddenMethods(*P, Method, Methods);
4485
4486 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4487 Category; Category = Category->getNextClassCategory())
4488 CollectOverriddenMethods(Category, Method, Methods);
4489
4490 // We only look into the superclass if we haven't found anything yet.
4491 if (Methods.empty())
4492 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4493 return CollectOverriddenMethods(Super, Method, Methods);
4494 }
4495}
4496
4497void clang_getOverriddenCursors(CXCursor cursor,
4498 CXCursor **overridden,
4499 unsigned *num_overridden) {
4500 if (overridden)
4501 *overridden = 0;
4502 if (num_overridden)
4503 *num_overridden = 0;
4504 if (!overridden || !num_overridden)
4505 return;
4506
4507 if (!clang_isDeclaration(cursor.kind))
4508 return;
4509
4510 Decl *D = getCursorDecl(cursor);
4511 if (!D)
4512 return;
4513
4514 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004515 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004516 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4517 *num_overridden = CXXMethod->size_overridden_methods();
4518 if (!*num_overridden)
4519 return;
4520
4521 *overridden = new CXCursor [*num_overridden];
4522 unsigned I = 0;
4523 for (CXXMethodDecl::method_iterator
4524 M = CXXMethod->begin_overridden_methods(),
4525 MEnd = CXXMethod->end_overridden_methods();
4526 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004527 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004528 return;
4529 }
4530
4531 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4532 if (!Method)
4533 return;
4534
4535 // Handle Objective-C methods.
4536 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4537 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4538
4539 if (Methods.empty())
4540 return;
4541
4542 *num_overridden = Methods.size();
4543 *overridden = new CXCursor [Methods.size()];
4544 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004545 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004546}
4547
4548void clang_disposeOverriddenCursors(CXCursor *overridden) {
4549 delete [] overridden;
4550}
4551
Douglas Gregorecdcb882010-10-20 22:00:55 +00004552CXFile clang_getIncludedFile(CXCursor cursor) {
4553 if (cursor.kind != CXCursor_InclusionDirective)
4554 return 0;
4555
4556 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4557 return (void *)ID->getFile();
4558}
4559
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004560} // end: extern "C"
4561
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004562
4563//===----------------------------------------------------------------------===//
4564// C++ AST instrospection.
4565//===----------------------------------------------------------------------===//
4566
4567extern "C" {
4568unsigned clang_CXXMethod_isStatic(CXCursor C) {
4569 if (!clang_isDeclaration(C.kind))
4570 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004571
4572 CXXMethodDecl *Method = 0;
4573 Decl *D = cxcursor::getCursorDecl(C);
4574 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4575 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4576 else
4577 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4578 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004579}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004580
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004581} // end: extern "C"
4582
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004583//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004584// Attribute introspection.
4585//===----------------------------------------------------------------------===//
4586
4587extern "C" {
4588CXType clang_getIBOutletCollectionType(CXCursor C) {
4589 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004590 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004591
4592 IBOutletCollectionAttr *A =
4593 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4594
Ted Kremeneka60ed472010-11-16 08:15:36 +00004595 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004596}
4597} // end: extern "C"
4598
4599//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004600// Misc. utility functions.
4601//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004602
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004603/// Default to using an 8 MB stack size on "safety" threads.
4604static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004605
4606namespace clang {
4607
4608bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004609 void (*Fn)(void*), void *UserData,
4610 unsigned Size) {
4611 if (!Size)
4612 Size = GetSafetyThreadStackSize();
4613 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004614 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4615 return CRC.RunSafely(Fn, UserData);
4616}
4617
4618unsigned GetSafetyThreadStackSize() {
4619 return SafetyStackThreadSize;
4620}
4621
4622void SetSafetyThreadStackSize(unsigned Value) {
4623 SafetyStackThreadSize = Value;
4624}
4625
4626}
4627
Ted Kremenek04bb7162010-01-22 22:44:15 +00004628extern "C" {
4629
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004630CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004631 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004632}
4633
4634} // end: extern "C"