blob: 7f4bf6629d1cdbaa82b2f727dfa3faf6e914c54e [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 Gregor3d37c0a2010-09-09 16:14:44 +0000343 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000344 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000345 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000346 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000347 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000348
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000349 // Data-recursive visitor functions.
350 bool IsInRegionOfInterest(CXCursor C);
351 bool RunVisitorWorkList(VisitorWorkList &WL);
352 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Benjamin Kramere645c722010-11-16 15:45:46 +0000353 LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000354};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000355
Ted Kremenekab188932010-01-05 19:32:54 +0000356} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000357
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000358static SourceRange getRawCursorExtent(CXCursor C);
359
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000361 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362}
363
Douglas Gregorb1373d02010-01-20 20:59:29 +0000364/// \brief Visit the given cursor and, if requested by the visitor,
365/// its children.
366///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367/// \param Cursor the cursor to visit.
368///
369/// \param CheckRegionOfInterest if true, then the caller already checked that
370/// this cursor is within the region of interest.
371///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372/// \returns true if the visitation should be aborted, false if it
373/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 if (clang_isInvalid(Cursor.kind))
376 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000377
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378 if (clang_isDeclaration(Cursor.kind)) {
379 Decl *D = getCursorDecl(Cursor);
380 assert(D && "Invalid declaration cursor");
381 if (D->getPCHLevel() > MaxPCHLevel)
382 return false;
383
384 if (D->isImplicit())
385 return false;
386 }
387
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388 // If we have a range of interest, and this cursor doesn't intersect with it,
389 // we're done.
390 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000391 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000392 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 return false;
394 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000395
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 switch (Visitor(Cursor, Parent, ClientData)) {
397 case CXChildVisit_Break:
398 return true;
399
400 case CXChildVisit_Continue:
401 return false;
402
403 case CXChildVisit_Recurse:
404 return VisitChildren(Cursor);
405 }
406
Douglas Gregorfd643772010-01-25 16:45:46 +0000407 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408}
409
Douglas Gregor788f5a12010-03-20 00:41:21 +0000410std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
411CursorVisitor::getPreprocessedEntities() {
412 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000413 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000414
415 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000416 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000417
418 // There is no region of interest; we have to walk everything.
419 if (RegionOfInterest.isInvalid())
420 return std::make_pair(PPRec.begin(OnlyLocalDecls),
421 PPRec.end(OnlyLocalDecls));
422
423 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000424 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000425 std::pair<FileID, unsigned> Begin
426 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
427 std::pair<FileID, unsigned> End
428 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
429
430 // The region of interest spans files; we have to walk everything.
431 if (Begin.first != End.first)
432 return std::make_pair(PPRec.begin(OnlyLocalDecls),
433 PPRec.end(OnlyLocalDecls));
434
435 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000436 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000437 if (ByFileMap.empty()) {
438 // Build the mapping from files to sets of preprocessed entities.
439 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
440 EEnd = PPRec.end(OnlyLocalDecls);
441 E != EEnd; ++E) {
442 std::pair<FileID, unsigned> P
443 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
444 ByFileMap[P.first].push_back(*E);
445 }
446 }
447
448 return std::make_pair(ByFileMap[Begin.first].begin(),
449 ByFileMap[Begin.first].end());
450}
451
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000453///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454/// \returns true if the visitation should be aborted, false if it
455/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000457 if (clang_isReference(Cursor.kind)) {
458 // By definition, references have no children.
459 return false;
460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461
462 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000464 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 if (clang_isDeclaration(Cursor.kind)) {
467 Decl *D = getCursorDecl(Cursor);
468 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000469 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregora59e3902010-01-21 23:27:09 +0000472 if (clang_isStatement(Cursor.kind))
473 return Visit(getCursorStmt(Cursor));
474 if (clang_isExpression(Cursor.kind))
475 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000478 CXTranslationUnit tu = getCursorTU(Cursor);
479 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000480 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
481 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000482 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
483 TLEnd = CXXUnit->top_level_end();
484 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000485 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000486 return true;
487 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000488 } else if (VisitDeclContext(
489 CXXUnit->getASTContext().getTranslationUnitDecl()))
490 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000491
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000493 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 // FIXME: Once we have the ability to deserialize a preprocessing record,
495 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000496 PreprocessingRecord::iterator E, EEnd;
497 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000499 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000501
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 continue;
503 }
504
505 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000506 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 return true;
508
509 continue;
510 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000511
512 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000513 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000514 return true;
515
516 continue;
517 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 }
519 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000520 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000522
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 return false;
525}
526
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000527bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000528 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
529 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530
Ted Kremenek664cffd2010-07-22 11:30:19 +0000531 if (Stmt *Body = B->getBody())
532 return Visit(MakeCXCursor(Body, StmtParent, TU));
533
534 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000535}
536
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000537llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
538 if (RegionOfInterest.isValid()) {
539 SourceRange Range = getRawCursorExtent(Cursor);
540 if (Range.isInvalid())
541 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000542
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543 switch (CompareRegionOfInterest(Range)) {
544 case RangeBefore:
545 // This declaration comes before the region of interest; skip it.
546 return llvm::Optional<bool>();
547
548 case RangeAfter:
549 // This declaration comes after the region of interest; we're done.
550 return false;
551
552 case RangeOverlap:
553 // This declaration overlaps the region of interest; visit it.
554 break;
555 }
556 }
557 return true;
558}
559
560bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
561 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
562
563 // FIXME: Eventually remove. This part of a hack to support proper
564 // iteration over all Decls contained lexically within an ObjC container.
565 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
566 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
567
568 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000569 Decl *D = *I;
570 if (D->getLexicalDeclContext() != DC)
571 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000572 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000573 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
574 if (!V.hasValue())
575 continue;
576 if (!V.getValue())
577 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000578 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000579 return true;
580 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000582}
583
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000584bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
585 llvm_unreachable("Translation units are visited directly by Visit()");
586 return false;
587}
588
589bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
590 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
591 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000592
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000593 return false;
594}
595
596bool CursorVisitor::VisitTagDecl(TagDecl *D) {
597 return VisitDeclContext(D);
598}
599
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000600bool CursorVisitor::VisitClassTemplateSpecializationDecl(
601 ClassTemplateSpecializationDecl *D) {
602 bool ShouldVisitBody = false;
603 switch (D->getSpecializationKind()) {
604 case TSK_Undeclared:
605 case TSK_ImplicitInstantiation:
606 // Nothing to visit
607 return false;
608
609 case TSK_ExplicitInstantiationDeclaration:
610 case TSK_ExplicitInstantiationDefinition:
611 break;
612
613 case TSK_ExplicitSpecialization:
614 ShouldVisitBody = true;
615 break;
616 }
617
618 // Visit the template arguments used in the specialization.
619 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
620 TypeLoc TL = SpecType->getTypeLoc();
621 if (TemplateSpecializationTypeLoc *TSTLoc
622 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
623 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
624 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
625 return true;
626 }
627 }
628
629 if (ShouldVisitBody && VisitCXXRecordDecl(D))
630 return true;
631
632 return false;
633}
634
Douglas Gregor74dbe642010-08-31 19:31:58 +0000635bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
636 ClassTemplatePartialSpecializationDecl *D) {
637 // FIXME: Visit the "outer" template parameter lists on the TagDecl
638 // before visiting these template parameters.
639 if (VisitTemplateParameters(D->getTemplateParameters()))
640 return true;
641
642 // Visit the partial specialization arguments.
643 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
644 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
645 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
646 return true;
647
648 return VisitCXXRecordDecl(D);
649}
650
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000651bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000652 // Visit the default argument.
653 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
654 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
655 if (Visit(DefArg->getTypeLoc()))
656 return true;
657
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000658 return false;
659}
660
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000661bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
662 if (Expr *Init = D->getInitExpr())
663 return Visit(MakeCXCursor(Init, StmtParent, TU));
664 return false;
665}
666
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000667bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
668 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
669 if (Visit(TSInfo->getTypeLoc()))
670 return true;
671
672 return false;
673}
674
Douglas Gregora67e03f2010-09-09 21:42:20 +0000675/// \brief Compare two base or member initializers based on their source order.
676static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
677 CXXBaseOrMemberInitializer const * const *X
678 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
679 CXXBaseOrMemberInitializer const * const *Y
680 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
681
682 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
683 return -1;
684 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
685 return 1;
686 else
687 return 0;
688}
689
Douglas Gregorb1373d02010-01-20 20:59:29 +0000690bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000691 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
692 // Visit the function declaration's syntactic components in the order
693 // written. This requires a bit of work.
694 TypeLoc TL = TSInfo->getTypeLoc();
695 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
696
697 // If we have a function declared directly (without the use of a typedef),
698 // visit just the return type. Otherwise, just visit the function's type
699 // now.
700 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
701 (!FTL && Visit(TL)))
702 return true;
703
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000704 // Visit the nested-name-specifier, if present.
705 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
706 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
707 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000708
709 // Visit the declaration name.
710 if (VisitDeclarationNameInfo(ND->getNameInfo()))
711 return true;
712
713 // FIXME: Visit explicitly-specified template arguments!
714
715 // Visit the function parameters, if we have a function type.
716 if (FTL && VisitFunctionTypeLoc(*FTL, true))
717 return true;
718
719 // FIXME: Attributes?
720 }
721
Douglas Gregora67e03f2010-09-09 21:42:20 +0000722 if (ND->isThisDeclarationADefinition()) {
723 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
724 // Find the initializers that were written in the source.
725 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
726 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
727 IEnd = Constructor->init_end();
728 I != IEnd; ++I) {
729 if (!(*I)->isWritten())
730 continue;
731
732 WrittenInits.push_back(*I);
733 }
734
735 // Sort the initializers in source order
736 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
737 &CompareCXXBaseOrMemberInitializers);
738
739 // Visit the initializers in source order
740 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
741 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
742 if (Init->isMemberInitializer()) {
743 if (Visit(MakeCursorMemberRef(Init->getMember(),
744 Init->getMemberLocation(), TU)))
745 return true;
746 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
747 if (Visit(BaseInfo->getTypeLoc()))
748 return true;
749 }
750
751 // Visit the initializer value.
752 if (Expr *Initializer = Init->getInit())
753 if (Visit(MakeCXCursor(Initializer, ND, TU)))
754 return true;
755 }
756 }
757
758 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
759 return true;
760 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761
Douglas Gregorb1373d02010-01-20 20:59:29 +0000762 return false;
763}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000764
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000765bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
766 if (VisitDeclaratorDecl(D))
767 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000768
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000769 if (Expr *BitWidth = D->getBitWidth())
770 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772 return false;
773}
774
775bool CursorVisitor::VisitVarDecl(VarDecl *D) {
776 if (VisitDeclaratorDecl(D))
777 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000778
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000779 if (Expr *Init = D->getInit())
780 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000781
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000782 return false;
783}
784
Douglas Gregor84b51d72010-09-01 20:16:53 +0000785bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
786 if (VisitDeclaratorDecl(D))
787 return true;
788
789 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
790 if (Expr *DefArg = D->getDefaultArgument())
791 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
792
793 return false;
794}
795
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000796bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
797 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
798 // before visiting these template parameters.
799 if (VisitTemplateParameters(D->getTemplateParameters()))
800 return true;
801
802 return VisitFunctionDecl(D->getTemplatedDecl());
803}
804
Douglas Gregor39d6f072010-08-31 19:02:00 +0000805bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
806 // FIXME: Visit the "outer" template parameter lists on the TagDecl
807 // before visiting these template parameters.
808 if (VisitTemplateParameters(D->getTemplateParameters()))
809 return true;
810
811 return VisitCXXRecordDecl(D->getTemplatedDecl());
812}
813
Douglas Gregor84b51d72010-09-01 20:16:53 +0000814bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
815 if (VisitTemplateParameters(D->getTemplateParameters()))
816 return true;
817
818 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
819 VisitTemplateArgumentLoc(D->getDefaultArgument()))
820 return true;
821
822 return false;
823}
824
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000825bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000826 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
827 if (Visit(TSInfo->getTypeLoc()))
828 return true;
829
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000830 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000831 PEnd = ND->param_end();
832 P != PEnd; ++P) {
833 if (Visit(MakeCXCursor(*P, TU)))
834 return true;
835 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000836
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000837 if (ND->isThisDeclarationADefinition() &&
838 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
839 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841 return false;
842}
843
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000844namespace {
845 struct ContainerDeclsSort {
846 SourceManager &SM;
847 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
848 bool operator()(Decl *A, Decl *B) {
849 SourceLocation L_A = A->getLocStart();
850 SourceLocation L_B = B->getLocStart();
851 assert(L_A.isValid() && L_B.isValid());
852 return SM.isBeforeInTranslationUnit(L_A, L_B);
853 }
854 };
855}
856
Douglas Gregora59e3902010-01-21 23:27:09 +0000857bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000858 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
859 // an @implementation can lexically contain Decls that are not properly
860 // nested in the AST. When we identify such cases, we need to retrofit
861 // this nesting here.
862 if (!DI_current)
863 return VisitDeclContext(D);
864
865 // Scan the Decls that immediately come after the container
866 // in the current DeclContext. If any fall within the
867 // container's lexical region, stash them into a vector
868 // for later processing.
869 llvm::SmallVector<Decl *, 24> DeclsInContainer;
870 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000871 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000872 if (EndLoc.isValid()) {
873 DeclContext::decl_iterator next = *DI_current;
874 while (++next != DE_current) {
875 Decl *D_next = *next;
876 if (!D_next)
877 break;
878 SourceLocation L = D_next->getLocStart();
879 if (!L.isValid())
880 break;
881 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
882 *DI_current = next;
883 DeclsInContainer.push_back(D_next);
884 continue;
885 }
886 break;
887 }
888 }
889
890 // The common case.
891 if (DeclsInContainer.empty())
892 return VisitDeclContext(D);
893
894 // Get all the Decls in the DeclContext, and sort them with the
895 // additional ones we've collected. Then visit them.
896 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
897 I!=E; ++I) {
898 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000899 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
900 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000901 continue;
902 DeclsInContainer.push_back(subDecl);
903 }
904
905 // Now sort the Decls so that they appear in lexical order.
906 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
907 ContainerDeclsSort(SM));
908
909 // Now visit the decls.
910 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
911 E = DeclsInContainer.end(); I != E; ++I) {
912 CXCursor Cursor = MakeCXCursor(*I, TU);
913 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
914 if (!V.hasValue())
915 continue;
916 if (!V.getValue())
917 return false;
918 if (Visit(Cursor, true))
919 return true;
920 }
921 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000922}
923
Douglas Gregorb1373d02010-01-20 20:59:29 +0000924bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000925 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
926 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000927 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000928
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000929 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
930 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
931 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000932 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregora59e3902010-01-21 23:27:09 +0000935 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000936}
937
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000938bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
939 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
940 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
941 E = PID->protocol_end(); I != E; ++I, ++PL)
942 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
943 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000944
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000945 return VisitObjCContainerDecl(PID);
946}
947
Ted Kremenek23173d72010-05-18 21:09:07 +0000948bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000949 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000950 return true;
951
Ted Kremenek23173d72010-05-18 21:09:07 +0000952 // FIXME: This implements a workaround with @property declarations also being
953 // installed in the DeclContext for the @interface. Eventually this code
954 // should be removed.
955 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
956 if (!CDecl || !CDecl->IsClassExtension())
957 return false;
958
959 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
960 if (!ID)
961 return false;
962
963 IdentifierInfo *PropertyId = PD->getIdentifier();
964 ObjCPropertyDecl *prevDecl =
965 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
966
967 if (!prevDecl)
968 return false;
969
970 // Visit synthesized methods since they will be skipped when visiting
971 // the @interface.
972 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000973 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000974 if (Visit(MakeCXCursor(MD, TU)))
975 return true;
976
977 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000978 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000979 if (Visit(MakeCXCursor(MD, TU)))
980 return true;
981
982 return false;
983}
984
Douglas Gregorb1373d02010-01-20 20:59:29 +0000985bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000986 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000987 if (D->getSuperClass() &&
988 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000990 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000991 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000993 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
994 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
995 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000996 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000997 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998
Douglas Gregora59e3902010-01-21 23:27:09 +0000999 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001000}
1001
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001002bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1003 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001004}
1005
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001006bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001007 // 'ID' could be null when dealing with invalid code.
1008 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1009 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1010 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001011
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001012 return VisitObjCImplDecl(D);
1013}
1014
1015bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1016#if 0
1017 // Issue callbacks for super class.
1018 // FIXME: No source location information!
1019 if (D->getSuperClass() &&
1020 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022 TU)))
1023 return true;
1024#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026 return VisitObjCImplDecl(D);
1027}
1028
1029bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1030 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1031 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1032 E = D->protocol_end();
1033 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001034 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001035 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001036
1037 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001038}
1039
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001040bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1041 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1042 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1043 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001046}
1047
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001048bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1049 return VisitDeclContext(D);
1050}
1051
Douglas Gregor69319002010-08-31 23:48:11 +00001052bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001053 // Visit nested-name-specifier.
1054 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1055 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1056 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001057
1058 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1059 D->getTargetNameLoc(), TU));
1060}
1061
Douglas Gregor7e242562010-09-01 19:52:22 +00001062bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001063 // Visit nested-name-specifier.
1064 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1065 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1066 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001067
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001068 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1069 return true;
1070
Douglas Gregor7e242562010-09-01 19:52:22 +00001071 return VisitDeclarationNameInfo(D->getNameInfo());
1072}
1073
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001074bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001075 // Visit nested-name-specifier.
1076 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1077 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1078 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001079
1080 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1081 D->getIdentLocation(), TU));
1082}
1083
Douglas Gregor7e242562010-09-01 19:52:22 +00001084bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001085 // Visit nested-name-specifier.
1086 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1087 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1088 return true;
1089
Douglas Gregor7e242562010-09-01 19:52:22 +00001090 return VisitDeclarationNameInfo(D->getNameInfo());
1091}
1092
1093bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1094 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001095 // Visit nested-name-specifier.
1096 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1097 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1098 return true;
1099
Douglas Gregor7e242562010-09-01 19:52:22 +00001100 return false;
1101}
1102
Douglas Gregor01829d32010-08-31 14:41:23 +00001103bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1104 switch (Name.getName().getNameKind()) {
1105 case clang::DeclarationName::Identifier:
1106 case clang::DeclarationName::CXXLiteralOperatorName:
1107 case clang::DeclarationName::CXXOperatorName:
1108 case clang::DeclarationName::CXXUsingDirective:
1109 return false;
1110
1111 case clang::DeclarationName::CXXConstructorName:
1112 case clang::DeclarationName::CXXDestructorName:
1113 case clang::DeclarationName::CXXConversionFunctionName:
1114 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1115 return Visit(TSInfo->getTypeLoc());
1116 return false;
1117
1118 case clang::DeclarationName::ObjCZeroArgSelector:
1119 case clang::DeclarationName::ObjCOneArgSelector:
1120 case clang::DeclarationName::ObjCMultiArgSelector:
1121 // FIXME: Per-identifier location info?
1122 return false;
1123 }
1124
1125 return false;
1126}
1127
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001128bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1129 SourceRange Range) {
1130 // FIXME: This whole routine is a hack to work around the lack of proper
1131 // source information in nested-name-specifiers (PR5791). Since we do have
1132 // a beginning source location, we can visit the first component of the
1133 // nested-name-specifier, if it's a single-token component.
1134 if (!NNS)
1135 return false;
1136
1137 // Get the first component in the nested-name-specifier.
1138 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1139 NNS = Prefix;
1140
1141 switch (NNS->getKind()) {
1142 case NestedNameSpecifier::Namespace:
1143 // FIXME: The token at this source location might actually have been a
1144 // namespace alias, but we don't model that. Lame!
1145 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1146 TU));
1147
1148 case NestedNameSpecifier::TypeSpec: {
1149 // If the type has a form where we know that the beginning of the source
1150 // range matches up with a reference cursor. Visit the appropriate reference
1151 // cursor.
1152 Type *T = NNS->getAsType();
1153 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1154 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1155 if (const TagType *Tag = dyn_cast<TagType>(T))
1156 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1157 if (const TemplateSpecializationType *TST
1158 = dyn_cast<TemplateSpecializationType>(T))
1159 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1160 break;
1161 }
1162
1163 case NestedNameSpecifier::TypeSpecWithTemplate:
1164 case NestedNameSpecifier::Global:
1165 case NestedNameSpecifier::Identifier:
1166 break;
1167 }
1168
1169 return false;
1170}
1171
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001172bool CursorVisitor::VisitTemplateParameters(
1173 const TemplateParameterList *Params) {
1174 if (!Params)
1175 return false;
1176
1177 for (TemplateParameterList::const_iterator P = Params->begin(),
1178 PEnd = Params->end();
1179 P != PEnd; ++P) {
1180 if (Visit(MakeCXCursor(*P, TU)))
1181 return true;
1182 }
1183
1184 return false;
1185}
1186
Douglas Gregor0b36e612010-08-31 20:37:03 +00001187bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1188 switch (Name.getKind()) {
1189 case TemplateName::Template:
1190 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1191
1192 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001193 // Visit the overloaded template set.
1194 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1195 return true;
1196
Douglas Gregor0b36e612010-08-31 20:37:03 +00001197 return false;
1198
1199 case TemplateName::DependentTemplate:
1200 // FIXME: Visit nested-name-specifier.
1201 return false;
1202
1203 case TemplateName::QualifiedTemplate:
1204 // FIXME: Visit nested-name-specifier.
1205 return Visit(MakeCursorTemplateRef(
1206 Name.getAsQualifiedTemplateName()->getDecl(),
1207 Loc, TU));
1208 }
1209
1210 return false;
1211}
1212
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001213bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1214 switch (TAL.getArgument().getKind()) {
1215 case TemplateArgument::Null:
1216 case TemplateArgument::Integral:
1217 return false;
1218
1219 case TemplateArgument::Pack:
1220 // FIXME: Implement when variadic templates come along.
1221 return false;
1222
1223 case TemplateArgument::Type:
1224 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1225 return Visit(TSInfo->getTypeLoc());
1226 return false;
1227
1228 case TemplateArgument::Declaration:
1229 if (Expr *E = TAL.getSourceDeclExpression())
1230 return Visit(MakeCXCursor(E, StmtParent, TU));
1231 return false;
1232
1233 case TemplateArgument::Expression:
1234 if (Expr *E = TAL.getSourceExpression())
1235 return Visit(MakeCXCursor(E, StmtParent, TU));
1236 return false;
1237
1238 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001239 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1240 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001241 }
1242
1243 return false;
1244}
1245
Ted Kremeneka0536d82010-05-07 01:04:29 +00001246bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1247 return VisitDeclContext(D);
1248}
1249
Douglas Gregor01829d32010-08-31 14:41:23 +00001250bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1251 return Visit(TL.getUnqualifiedLoc());
1252}
1253
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001254bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001255 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001256
1257 // Some builtin types (such as Objective-C's "id", "sel", and
1258 // "Class") have associated declarations. Create cursors for those.
1259 QualType VisitType;
1260 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001261 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001262 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001263 case BuiltinType::Char_U:
1264 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001265 case BuiltinType::Char16:
1266 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001267 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001268 case BuiltinType::UInt:
1269 case BuiltinType::ULong:
1270 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001271 case BuiltinType::UInt128:
1272 case BuiltinType::Char_S:
1273 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001274 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001275 case BuiltinType::Short:
1276 case BuiltinType::Int:
1277 case BuiltinType::Long:
1278 case BuiltinType::LongLong:
1279 case BuiltinType::Int128:
1280 case BuiltinType::Float:
1281 case BuiltinType::Double:
1282 case BuiltinType::LongDouble:
1283 case BuiltinType::NullPtr:
1284 case BuiltinType::Overload:
1285 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001286 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001287
1288 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001289 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001290
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001291 case BuiltinType::ObjCId:
1292 VisitType = Context.getObjCIdType();
1293 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001294
1295 case BuiltinType::ObjCClass:
1296 VisitType = Context.getObjCClassType();
1297 break;
1298
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001299 case BuiltinType::ObjCSel:
1300 VisitType = Context.getObjCSelType();
1301 break;
1302 }
1303
1304 if (!VisitType.isNull()) {
1305 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001306 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001307 TU));
1308 }
1309
1310 return false;
1311}
1312
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001313bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1314 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1315}
1316
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001317bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1318 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1319}
1320
1321bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1322 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1323}
1324
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001325bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001326 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001327 // no context information with which we can match up the depth/index in the
1328 // type to the appropriate
1329 return false;
1330}
1331
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001332bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1333 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1334 return true;
1335
John McCallc12c5bb2010-05-15 11:32:37 +00001336 return false;
1337}
1338
1339bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1340 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1341 return true;
1342
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001343 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1344 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1345 TU)))
1346 return true;
1347 }
1348
1349 return false;
1350}
1351
1352bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001353 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001354}
1355
1356bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1357 return Visit(TL.getPointeeLoc());
1358}
1359
1360bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1361 return Visit(TL.getPointeeLoc());
1362}
1363
1364bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1365 return Visit(TL.getPointeeLoc());
1366}
1367
1368bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001369 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370}
1371
1372bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001373 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001374}
1375
Douglas Gregor01829d32010-08-31 14:41:23 +00001376bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1377 bool SkipResultType) {
1378 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001379 return true;
1380
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001382 if (Decl *D = TL.getArg(I))
1383 if (Visit(MakeCXCursor(D, TU)))
1384 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385
1386 return false;
1387}
1388
1389bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1390 if (Visit(TL.getElementLoc()))
1391 return true;
1392
1393 if (Expr *Size = TL.getSizeExpr())
1394 return Visit(MakeCXCursor(Size, StmtParent, TU));
1395
1396 return false;
1397}
1398
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001399bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1400 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001401 // Visit the template name.
1402 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1403 TL.getTemplateNameLoc()))
1404 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001405
1406 // Visit the template arguments.
1407 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1408 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1409 return true;
1410
1411 return false;
1412}
1413
Douglas Gregor2332c112010-01-21 20:48:56 +00001414bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1415 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1416}
1417
1418bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1419 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1420 return Visit(TSInfo->getTypeLoc());
1421
1422 return false;
1423}
1424
Douglas Gregora59e3902010-01-21 23:27:09 +00001425bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001426 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001427}
1428
Ted Kremenek3064ef92010-08-27 21:34:58 +00001429bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1430 if (D->isDefinition()) {
1431 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1432 E = D->bases_end(); I != E; ++I) {
1433 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1434 return true;
1435 }
1436 }
1437
1438 return VisitTagDecl(D);
1439}
1440
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001441bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001442 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001443 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1444 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001445
1446 // Visit the components of the offsetof expression.
1447 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1448 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1449 const OffsetOfNode &Node = E->getComponent(I);
1450 switch (Node.getKind()) {
1451 case OffsetOfNode::Array:
1452 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1453 StmtParent, TU)))
1454 return true;
1455 break;
1456
1457 case OffsetOfNode::Field:
1458 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1459 TU)))
1460 return true;
1461 break;
1462
1463 case OffsetOfNode::Identifier:
1464 case OffsetOfNode::Base:
1465 continue;
1466 }
1467 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001468
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001469 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001470}
1471
Douglas Gregor336fd812010-01-23 00:40:08 +00001472bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1473 if (E->isArgumentType()) {
1474 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1475 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001476
Douglas Gregor336fd812010-01-23 00:40:08 +00001477 return false;
1478 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001479
Douglas Gregor336fd812010-01-23 00:40:08 +00001480 return VisitExpr(E);
1481}
1482
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001483bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1484 // Visit the designators.
1485 typedef DesignatedInitExpr::Designator Designator;
1486 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1487 DEnd = E->designators_end();
1488 D != DEnd; ++D) {
1489 if (D->isFieldDesignator()) {
1490 if (FieldDecl *Field = D->getField())
1491 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1492 return true;
1493
1494 continue;
1495 }
1496
1497 if (D->isArrayDesignator()) {
1498 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1499 return true;
1500
1501 continue;
1502 }
1503
1504 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1505 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1506 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1507 return true;
1508 }
1509
1510 // Visit the initializer value itself.
1511 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1512}
1513
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001514bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1515 if (E->isTypeOperand()) {
1516 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1517 return Visit(TSInfo->getTypeLoc());
1518
1519 return false;
1520 }
1521
1522 return VisitExpr(E);
1523}
1524
Douglas Gregorab6677e2010-09-08 00:15:04 +00001525bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1526 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1527 return Visit(TSInfo->getTypeLoc());
1528
1529 return false;
1530}
1531
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001532bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1533 // Visit base expression.
1534 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1535 return true;
1536
1537 // Visit the nested-name-specifier.
1538 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1539 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1540 return true;
1541
1542 // Visit the scope type that looks disturbingly like the nested-name-specifier
1543 // but isn't.
1544 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1545 if (Visit(TSInfo->getTypeLoc()))
1546 return true;
1547
1548 // Visit the name of the type being destroyed.
1549 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1550 if (Visit(TSInfo->getTypeLoc()))
1551 return true;
1552
1553 return false;
1554}
1555
Douglas Gregorbfebed22010-09-03 17:24:10 +00001556bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1557 DependentScopeDeclRefExpr *E) {
1558 // Visit the nested-name-specifier.
1559 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1560 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1561 return true;
1562
1563 // Visit the declaration name.
1564 if (VisitDeclarationNameInfo(E->getNameInfo()))
1565 return true;
1566
1567 // Visit the explicitly-specified template arguments.
1568 if (const ExplicitTemplateArgumentList *ArgList
1569 = E->getOptionalExplicitTemplateArgs()) {
1570 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1571 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1572 Arg != ArgEnd; ++Arg) {
1573 if (VisitTemplateArgumentLoc(*Arg))
1574 return true;
1575 }
1576 }
1577
1578 return false;
1579}
1580
Douglas Gregor25d63622010-09-03 17:35:34 +00001581bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1582 CXXDependentScopeMemberExpr *E) {
1583 // Visit the base expression, if there is one.
1584 if (!E->isImplicitAccess() &&
1585 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1586 return true;
1587
1588 // Visit the nested-name-specifier.
1589 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1590 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1591 return true;
1592
1593 // Visit the declaration name.
1594 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1595 return true;
1596
1597 // Visit the explicitly-specified template arguments.
1598 if (const ExplicitTemplateArgumentList *ArgList
1599 = E->getOptionalExplicitTemplateArgs()) {
1600 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1601 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1602 Arg != ArgEnd; ++Arg) {
1603 if (VisitTemplateArgumentLoc(*Arg))
1604 return true;
1605 }
1606 }
1607
1608 return false;
1609}
1610
Ted Kremenek09dfa372010-02-18 05:46:33 +00001611bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001612 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1613 i != e; ++i)
1614 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001615 return true;
1616
1617 return false;
1618}
1619
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001620//===----------------------------------------------------------------------===//
1621// Data-recursive visitor methods.
1622//===----------------------------------------------------------------------===//
1623
Ted Kremenek28a71942010-11-13 00:36:47 +00001624namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001625#define DEF_JOB(NAME, DATA, KIND)\
1626class NAME : public VisitorJob {\
1627public:\
1628 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1629 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1630 DATA *get() const { return static_cast<DATA*>(dataA); }\
1631};
1632
1633DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1634DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001635DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001636DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001637DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1638 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001639#undef DEF_JOB
1640
1641class DeclVisit : public VisitorJob {
1642public:
1643 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1644 VisitorJob(parent, VisitorJob::DeclVisitKind,
1645 d, isFirst ? (void*) 1 : (void*) 0) {}
1646 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001647 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001648 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001649 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001650 bool isFirst() const { return dataB ? true : false; }
1651};
Ted Kremenek035dc412010-11-13 00:36:50 +00001652class TypeLocVisit : public VisitorJob {
1653public:
1654 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1655 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1656 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1657
1658 static bool classof(const VisitorJob *VJ) {
1659 return VJ->getKind() == TypeLocVisitKind;
1660 }
1661
Ted Kremenek82f3c502010-11-15 22:23:26 +00001662 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001663 QualType T = QualType::getFromOpaquePtr(dataA);
1664 return TypeLoc(T, dataB);
1665 }
1666};
1667
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001668class LabelRefVisit : public VisitorJob {
1669public:
1670 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1671 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1672 (void*) labelLoc.getRawEncoding()) {}
1673
1674 static bool classof(const VisitorJob *VJ) {
1675 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1676 }
1677 LabelStmt *get() const { return static_cast<LabelStmt*>(dataA); }
1678 SourceLocation getLoc() const {
1679 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) dataB); }
1680};
1681
Ted Kremenek28a71942010-11-13 00:36:47 +00001682class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1683 VisitorWorkList &WL;
1684 CXCursor Parent;
1685public:
1686 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1687 : WL(wl), Parent(parent) {}
1688
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001689 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001690 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001691 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001692 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001693 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1694 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001695 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001696 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001697 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001698 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001699 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001700 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001701 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1702 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001703 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void VisitIfStmt(IfStmt *If);
1705 void VisitInitListExpr(InitListExpr *IE);
1706 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001707 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001708 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1709 void VisitOverloadExpr(OverloadExpr *E);
1710 void VisitStmt(Stmt *S);
1711 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001712 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001713 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001714 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001715 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001716 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001717
1718private:
Ted Kremenek60608ec2010-11-17 00:50:47 +00001719 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenek28a71942010-11-13 00:36:47 +00001720 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001721 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001722 void AddTypeLoc(TypeSourceInfo *TI);
1723 void EnqueueChildren(Stmt *S);
1724};
1725} // end anonyous namespace
1726
1727void EnqueueVisitor::AddStmt(Stmt *S) {
1728 if (S)
1729 WL.push_back(StmtVisit(S, Parent));
1730}
Ted Kremenek035dc412010-11-13 00:36:50 +00001731void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001732 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001733 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001734}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001735void EnqueueVisitor::
1736 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1737 if (A)
1738 WL.push_back(ExplicitTemplateArgsVisit(
1739 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1740}
Ted Kremenek28a71942010-11-13 00:36:47 +00001741void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1742 if (TI)
1743 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1744 }
1745void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001746 unsigned size = WL.size();
1747 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1748 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001749 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001750 }
1751 if (size == WL.size())
1752 return;
1753 // Now reverse the entries we just added. This will match the DFS
1754 // ordering performed by the worklist.
1755 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1756 std::reverse(I, E);
1757}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001758void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1759 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1760}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001761void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1762 AddDecl(B->getBlockDecl());
1763}
Ted Kremenek28a71942010-11-13 00:36:47 +00001764void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1765 EnqueueChildren(E);
1766 AddTypeLoc(E->getTypeSourceInfo());
1767}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001768void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1769 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1770 E = S->body_rend(); I != E; ++I) {
1771 AddStmt(*I);
1772 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001773}
1774void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1775 // Enqueue the initializer or constructor arguments.
1776 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1777 AddStmt(E->getConstructorArg(I-1));
1778 // Enqueue the array size, if any.
1779 AddStmt(E->getArraySize());
1780 // Enqueue the allocated type.
1781 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1782 // Enqueue the placement arguments.
1783 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1784 AddStmt(E->getPlacementArg(I-1));
1785}
Ted Kremenek28a71942010-11-13 00:36:47 +00001786void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001787 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1788 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001789 AddStmt(CE->getCallee());
1790 AddStmt(CE->getArg(0));
1791}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001792void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1793 EnqueueChildren(E);
1794 AddTypeLoc(E->getTypeSourceInfo());
1795}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001796void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1797 EnqueueChildren(E);
1798 if (E->isTypeOperand())
1799 AddTypeLoc(E->getTypeOperandSourceInfo());
1800}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001801
1802void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1803 *E) {
1804 EnqueueChildren(E);
1805 AddTypeLoc(E->getTypeSourceInfo());
1806}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001807void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001808 if (DR->hasExplicitTemplateArgs()) {
1809 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1810 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001811 WL.push_back(DeclRefExprParts(DR, Parent));
1812}
Ted Kremenek035dc412010-11-13 00:36:50 +00001813void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1814 unsigned size = WL.size();
1815 bool isFirst = true;
1816 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1817 D != DEnd; ++D) {
1818 AddDecl(*D, isFirst);
1819 isFirst = false;
1820 }
1821 if (size == WL.size())
1822 return;
1823 // Now reverse the entries we just added. This will match the DFS
1824 // ordering performed by the worklist.
1825 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1826 std::reverse(I, E);
1827}
Ted Kremenek28a71942010-11-13 00:36:47 +00001828void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1829 EnqueueChildren(E);
1830 AddTypeLoc(E->getTypeInfoAsWritten());
1831}
1832void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1833 AddStmt(FS->getBody());
1834 AddStmt(FS->getInc());
1835 AddStmt(FS->getCond());
1836 AddDecl(FS->getConditionVariable());
1837 AddStmt(FS->getInit());
1838}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001839void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1840 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1841}
Ted Kremenek28a71942010-11-13 00:36:47 +00001842void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1843 AddStmt(If->getElse());
1844 AddStmt(If->getThen());
1845 AddStmt(If->getCond());
1846 AddDecl(If->getConditionVariable());
1847}
1848void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1849 // We care about the syntactic form of the initializer list, only.
1850 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1851 IE = Syntactic;
1852 EnqueueChildren(IE);
1853}
1854void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1855 WL.push_back(MemberExprParts(M, Parent));
1856 AddStmt(M->getBase());
1857}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001858void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1859 AddTypeLoc(E->getEncodedTypeSourceInfo());
1860}
Ted Kremenek28a71942010-11-13 00:36:47 +00001861void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1862 EnqueueChildren(M);
1863 AddTypeLoc(M->getClassReceiverTypeInfo());
1864}
1865void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001866 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001867 WL.push_back(OverloadExprParts(E, Parent));
1868}
Ted Kremenek28a71942010-11-13 00:36:47 +00001869void EnqueueVisitor::VisitStmt(Stmt *S) {
1870 EnqueueChildren(S);
1871}
1872void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1873 AddStmt(S->getBody());
1874 AddStmt(S->getCond());
1875 AddDecl(S->getConditionVariable());
1876}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001877void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1878 AddTypeLoc(E->getArgTInfo2());
1879 AddTypeLoc(E->getArgTInfo1());
1880}
1881
Ted Kremenek28a71942010-11-13 00:36:47 +00001882void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1883 AddStmt(W->getBody());
1884 AddStmt(W->getCond());
1885 AddDecl(W->getConditionVariable());
1886}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001887void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1888 AddTypeLoc(E->getQueriedTypeSourceInfo());
1889}
Ted Kremenek28a71942010-11-13 00:36:47 +00001890void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1891 VisitOverloadExpr(U);
1892 if (!U->isImplicitAccess())
1893 AddStmt(U->getBase());
1894}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001895void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1896 AddStmt(E->getSubExpr());
1897 AddTypeLoc(E->getWrittenTypeInfo());
1898}
Ted Kremenek60458782010-11-12 21:34:16 +00001899
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001900void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001901 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001902}
1903
1904bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1905 if (RegionOfInterest.isValid()) {
1906 SourceRange Range = getRawCursorExtent(C);
1907 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1908 return false;
1909 }
1910 return true;
1911}
1912
1913bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1914 while (!WL.empty()) {
1915 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001916 VisitorJob LI = WL.back();
1917 WL.pop_back();
1918
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001919 // Set the Parent field, then back to its old value once we're done.
1920 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1921
1922 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001923 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001924 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001925 if (!D)
1926 continue;
1927
1928 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001929 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001930 return true;
1931
1932 continue;
1933 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001934 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1935 const ExplicitTemplateArgumentList *ArgList =
1936 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1937 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1938 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1939 Arg != ArgEnd; ++Arg) {
1940 if (VisitTemplateArgumentLoc(*Arg))
1941 return true;
1942 }
1943 continue;
1944 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001945 case VisitorJob::TypeLocVisitKind: {
1946 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001947 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001948 return true;
1949 continue;
1950 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001951 case VisitorJob::LabelRefVisitKind: {
1952 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1953 if (Visit(MakeCursorLabelRef(LS,
1954 cast<LabelRefVisit>(&LI)->getLoc(),
1955 TU)))
1956 return true;
1957 continue;
1958 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001959 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001960 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001961 if (!S)
1962 continue;
1963
Ted Kremenekf1107452010-11-12 18:26:56 +00001964 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001965 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1966
1967 switch (S->getStmtClass()) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001968 // Cases not yet handled by the data-recursion
1969 // algorithm.
1970 case Stmt::OffsetOfExprClass:
1971 case Stmt::SizeOfAlignOfExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001972 case Stmt::DesignatedInitExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001973 case Stmt::CXXUuidofExprClass:
1974 case Stmt::CXXScalarValueInitExprClass:
1975 case Stmt::CXXPseudoDestructorExprClass:
1976 case Stmt::UnaryTypeTraitExprClass:
1977 case Stmt::DependentScopeDeclRefExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001978 case Stmt::CXXDependentScopeMemberExprClass:
1979 if (Visit(Cursor))
1980 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001981 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001982 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001983 if (!IsInRegionOfInterest(Cursor))
1984 continue;
1985 switch (Visitor(Cursor, Parent, ClientData)) {
1986 case CXChildVisit_Break:
1987 return true;
1988 case CXChildVisit_Continue:
1989 break;
1990 case CXChildVisit_Recurse:
1991 EnqueueWorkList(WL, S);
1992 break;
1993 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001994 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001995 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001996 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001997 }
1998 case VisitorJob::MemberExprPartsKind: {
1999 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002000 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002001
2002 // Visit the nested-name-specifier
2003 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2004 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2005 return true;
2006
2007 // Visit the declaration name.
2008 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2009 return true;
2010
2011 // Visit the explicitly-specified template arguments, if any.
2012 if (M->hasExplicitTemplateArgs()) {
2013 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2014 *ArgEnd = Arg + M->getNumTemplateArgs();
2015 Arg != ArgEnd; ++Arg) {
2016 if (VisitTemplateArgumentLoc(*Arg))
2017 return true;
2018 }
2019 }
2020 continue;
2021 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002022 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002023 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002024 // Visit nested-name-specifier, if present.
2025 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2026 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2027 return true;
2028 // Visit declaration name.
2029 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2030 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002031 continue;
2032 }
Ted Kremenek60458782010-11-12 21:34:16 +00002033 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002034 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002035 // Visit the nested-name-specifier.
2036 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2037 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2038 return true;
2039 // Visit the declaration name.
2040 if (VisitDeclarationNameInfo(O->getNameInfo()))
2041 return true;
2042 // Visit the overloaded declaration reference.
2043 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2044 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002045 continue;
2046 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002047 }
2048 }
2049 return false;
2050}
2051
2052bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002053 VisitorWorkList *WL = 0;
2054 if (!WorkListFreeList.empty()) {
2055 WL = WorkListFreeList.back();
2056 WL->clear();
2057 WorkListFreeList.pop_back();
2058 }
2059 else {
2060 WL = new VisitorWorkList();
2061 WorkListCache.push_back(WL);
2062 }
2063 EnqueueWorkList(*WL, S);
2064 bool result = RunVisitorWorkList(*WL);
2065 WorkListFreeList.push_back(WL);
2066 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002067}
2068
2069//===----------------------------------------------------------------------===//
2070// Misc. API hooks.
2071//===----------------------------------------------------------------------===//
2072
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002073static llvm::sys::Mutex EnableMultithreadingMutex;
2074static bool EnabledMultithreading;
2075
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002076extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002077CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2078 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002079 // Disable pretty stack trace functionality, which will otherwise be a very
2080 // poor citizen of the world and set up all sorts of signal handlers.
2081 llvm::DisablePrettyStackTrace = true;
2082
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002083 // We use crash recovery to make some of our APIs more reliable, implicitly
2084 // enable it.
2085 llvm::CrashRecoveryContext::Enable();
2086
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002087 // Enable support for multithreading in LLVM.
2088 {
2089 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2090 if (!EnabledMultithreading) {
2091 llvm::llvm_start_multithreaded();
2092 EnabledMultithreading = true;
2093 }
2094 }
2095
Douglas Gregora030b7c2010-01-22 20:35:53 +00002096 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002097 if (excludeDeclarationsFromPCH)
2098 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002099 if (displayDiagnostics)
2100 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002101 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002102}
2103
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002104void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002105 if (CIdx)
2106 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002107}
2108
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002109CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002110 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002111 if (!CIdx)
2112 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002113
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002114 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002115 FileSystemOptions FileSystemOpts;
2116 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002117
Douglas Gregor28019772010-04-05 23:52:57 +00002118 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002119 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002120 CXXIdx->getOnlyLocalDecls(),
2121 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002122 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002123}
2124
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002125unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002126 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002127 CXTranslationUnit_CacheCompletionResults |
2128 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002129}
2130
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002131CXTranslationUnit
2132clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2133 const char *source_filename,
2134 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002135 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002136 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002137 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002138 return clang_parseTranslationUnit(CIdx, source_filename,
2139 command_line_args, num_command_line_args,
2140 unsaved_files, num_unsaved_files,
2141 CXTranslationUnit_DetailedPreprocessingRecord);
2142}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002143
2144struct ParseTranslationUnitInfo {
2145 CXIndex CIdx;
2146 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002147 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002148 int num_command_line_args;
2149 struct CXUnsavedFile *unsaved_files;
2150 unsigned num_unsaved_files;
2151 unsigned options;
2152 CXTranslationUnit result;
2153};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002154static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002155 ParseTranslationUnitInfo *PTUI =
2156 static_cast<ParseTranslationUnitInfo*>(UserData);
2157 CXIndex CIdx = PTUI->CIdx;
2158 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002159 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002160 int num_command_line_args = PTUI->num_command_line_args;
2161 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2162 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2163 unsigned options = PTUI->options;
2164 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002165
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002166 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002167 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002168
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002169 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2170
Douglas Gregor44c181a2010-07-23 00:33:23 +00002171 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002172 bool CompleteTranslationUnit
2173 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002174 bool CacheCodeCompetionResults
2175 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002176 bool CXXPrecompilePreamble
2177 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2178 bool CXXChainedPCH
2179 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002180
Douglas Gregor5352ac02010-01-28 00:27:43 +00002181 // Configure the diagnostics.
2182 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002183 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2184 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002185
Douglas Gregor4db64a42010-01-23 00:14:00 +00002186 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2187 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002188 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002189 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002190 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002191 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2192 Buffer));
2193 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002194
Douglas Gregorb10daed2010-10-11 16:52:23 +00002195 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002196
Ted Kremenek139ba862009-10-22 00:03:57 +00002197 // The 'source_filename' argument is optional. If the caller does not
2198 // specify it then it is assumed that the source file is specified
2199 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002200 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002201 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002202
2203 // Since the Clang C library is primarily used by batch tools dealing with
2204 // (often very broken) source code, where spell-checking can have a
2205 // significant negative impact on performance (particularly when
2206 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002207 // Only do this if we haven't found a spell-checking-related argument.
2208 bool FoundSpellCheckingArgument = false;
2209 for (int I = 0; I != num_command_line_args; ++I) {
2210 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2211 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2212 FoundSpellCheckingArgument = true;
2213 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002214 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002215 }
2216 if (!FoundSpellCheckingArgument)
2217 Args.push_back("-fno-spell-checking");
2218
2219 Args.insert(Args.end(), command_line_args,
2220 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002221
Douglas Gregor44c181a2010-07-23 00:33:23 +00002222 // Do we need the detailed preprocessing record?
2223 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002224 Args.push_back("-Xclang");
2225 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002226 }
2227
Douglas Gregorb10daed2010-10-11 16:52:23 +00002228 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002229 llvm::OwningPtr<ASTUnit> Unit(
2230 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2231 Diags,
2232 CXXIdx->getClangResourcesPath(),
2233 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002234 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002235 RemappedFiles.data(),
2236 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002237 PrecompilePreamble,
2238 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002239 CacheCodeCompetionResults,
2240 CXXPrecompilePreamble,
2241 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002242
Douglas Gregorb10daed2010-10-11 16:52:23 +00002243 if (NumErrors != Diags->getNumErrors()) {
2244 // Make sure to check that 'Unit' is non-NULL.
2245 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2246 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2247 DEnd = Unit->stored_diag_end();
2248 D != DEnd; ++D) {
2249 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2250 CXString Msg = clang_formatDiagnostic(&Diag,
2251 clang_defaultDiagnosticDisplayOptions());
2252 fprintf(stderr, "%s\n", clang_getCString(Msg));
2253 clang_disposeString(Msg);
2254 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002255#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002256 // On Windows, force a flush, since there may be multiple copies of
2257 // stderr and stdout in the file system, all with different buffers
2258 // but writing to the same device.
2259 fflush(stderr);
2260#endif
2261 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002262 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002263
Ted Kremeneka60ed472010-11-16 08:15:36 +00002264 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002265}
2266CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2267 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002268 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002269 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002270 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002271 unsigned num_unsaved_files,
2272 unsigned options) {
2273 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002274 num_command_line_args, unsaved_files,
2275 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002276 llvm::CrashRecoveryContext CRC;
2277
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002278 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002279 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2280 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2281 fprintf(stderr, " 'command_line_args' : [");
2282 for (int i = 0; i != num_command_line_args; ++i) {
2283 if (i)
2284 fprintf(stderr, ", ");
2285 fprintf(stderr, "'%s'", command_line_args[i]);
2286 }
2287 fprintf(stderr, "],\n");
2288 fprintf(stderr, " 'unsaved_files' : [");
2289 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2290 if (i)
2291 fprintf(stderr, ", ");
2292 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2293 unsaved_files[i].Length);
2294 }
2295 fprintf(stderr, "],\n");
2296 fprintf(stderr, " 'options' : %d,\n", options);
2297 fprintf(stderr, "}\n");
2298
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002299 return 0;
2300 }
2301
2302 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002303}
2304
Douglas Gregor19998442010-08-13 15:35:05 +00002305unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2306 return CXSaveTranslationUnit_None;
2307}
2308
2309int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2310 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002311 if (!TU)
2312 return 1;
2313
Ted Kremeneka60ed472010-11-16 08:15:36 +00002314 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002315}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002316
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002317void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002318 if (CTUnit) {
2319 // If the translation unit has been marked as unsafe to free, just discard
2320 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002321 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002322 return;
2323
Ted Kremeneka60ed472010-11-16 08:15:36 +00002324 delete static_cast<ASTUnit *>(CTUnit->TUData);
2325 disposeCXStringPool(CTUnit->StringPool);
2326 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002327 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002328}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002329
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002330unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2331 return CXReparse_None;
2332}
2333
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002334struct ReparseTranslationUnitInfo {
2335 CXTranslationUnit TU;
2336 unsigned num_unsaved_files;
2337 struct CXUnsavedFile *unsaved_files;
2338 unsigned options;
2339 int result;
2340};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002341
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002342static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002343 ReparseTranslationUnitInfo *RTUI =
2344 static_cast<ReparseTranslationUnitInfo*>(UserData);
2345 CXTranslationUnit TU = RTUI->TU;
2346 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2347 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2348 unsigned options = RTUI->options;
2349 (void) options;
2350 RTUI->result = 1;
2351
Douglas Gregorabc563f2010-07-19 21:46:24 +00002352 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002353 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002354
Ted Kremeneka60ed472010-11-16 08:15:36 +00002355 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002356 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002357
2358 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2359 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2360 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2361 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002362 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002363 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2364 Buffer));
2365 }
2366
Douglas Gregor593b0c12010-09-23 18:47:53 +00002367 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2368 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002369}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002370
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002371int clang_reparseTranslationUnit(CXTranslationUnit TU,
2372 unsigned num_unsaved_files,
2373 struct CXUnsavedFile *unsaved_files,
2374 unsigned options) {
2375 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2376 options, 0 };
2377 llvm::CrashRecoveryContext CRC;
2378
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002379 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002380 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002381 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002382 return 1;
2383 }
2384
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002385
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002386 return RTUI.result;
2387}
2388
Douglas Gregordf95a132010-08-09 20:45:32 +00002389
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002390CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002391 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002392 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002393
Ted Kremeneka60ed472010-11-16 08:15:36 +00002394 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002395 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002396}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002397
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002398CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002399 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002400 return Result;
2401}
2402
Ted Kremenekfb480492010-01-13 21:46:36 +00002403} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002404
Ted Kremenekfb480492010-01-13 21:46:36 +00002405//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002406// CXSourceLocation and CXSourceRange Operations.
2407//===----------------------------------------------------------------------===//
2408
Douglas Gregorb9790342010-01-22 21:44:22 +00002409extern "C" {
2410CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002411 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002412 return Result;
2413}
2414
2415unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002416 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2417 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2418 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002419}
2420
2421CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2422 CXFile file,
2423 unsigned line,
2424 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002425 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002426 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002427
Ted Kremeneka60ed472010-11-16 08:15:36 +00002428 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002429 SourceLocation SLoc
2430 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002431 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002432 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002433 if (SLoc.isInvalid()) return clang_getNullLocation();
2434
2435 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2436}
2437
2438CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2439 CXFile file,
2440 unsigned offset) {
2441 if (!tu || !file)
2442 return clang_getNullLocation();
2443
Ted Kremeneka60ed472010-11-16 08:15:36 +00002444 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002445 SourceLocation Start
2446 = CXXUnit->getSourceManager().getLocation(
2447 static_cast<const FileEntry *>(file),
2448 1, 1);
2449 if (Start.isInvalid()) return clang_getNullLocation();
2450
2451 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2452
2453 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002454
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002455 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002456}
2457
Douglas Gregor5352ac02010-01-28 00:27:43 +00002458CXSourceRange clang_getNullRange() {
2459 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2460 return Result;
2461}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002462
Douglas Gregor5352ac02010-01-28 00:27:43 +00002463CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2464 if (begin.ptr_data[0] != end.ptr_data[0] ||
2465 begin.ptr_data[1] != end.ptr_data[1])
2466 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002467
2468 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002469 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002470 return Result;
2471}
2472
Douglas Gregor46766dc2010-01-26 19:19:08 +00002473void clang_getInstantiationLocation(CXSourceLocation location,
2474 CXFile *file,
2475 unsigned *line,
2476 unsigned *column,
2477 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002478 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2479
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002480 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002481 if (file)
2482 *file = 0;
2483 if (line)
2484 *line = 0;
2485 if (column)
2486 *column = 0;
2487 if (offset)
2488 *offset = 0;
2489 return;
2490 }
2491
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002492 const SourceManager &SM =
2493 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002494 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002495
2496 if (file)
2497 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2498 if (line)
2499 *line = SM.getInstantiationLineNumber(InstLoc);
2500 if (column)
2501 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002502 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002503 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002504}
2505
Douglas Gregora9b06d42010-11-09 06:24:54 +00002506void clang_getSpellingLocation(CXSourceLocation location,
2507 CXFile *file,
2508 unsigned *line,
2509 unsigned *column,
2510 unsigned *offset) {
2511 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2512
2513 if (!location.ptr_data[0] || Loc.isInvalid()) {
2514 if (file)
2515 *file = 0;
2516 if (line)
2517 *line = 0;
2518 if (column)
2519 *column = 0;
2520 if (offset)
2521 *offset = 0;
2522 return;
2523 }
2524
2525 const SourceManager &SM =
2526 *static_cast<const SourceManager*>(location.ptr_data[0]);
2527 SourceLocation SpellLoc = Loc;
2528 if (SpellLoc.isMacroID()) {
2529 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2530 if (SimpleSpellingLoc.isFileID() &&
2531 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2532 SpellLoc = SimpleSpellingLoc;
2533 else
2534 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2535 }
2536
2537 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2538 FileID FID = LocInfo.first;
2539 unsigned FileOffset = LocInfo.second;
2540
2541 if (file)
2542 *file = (void *)SM.getFileEntryForID(FID);
2543 if (line)
2544 *line = SM.getLineNumber(FID, FileOffset);
2545 if (column)
2546 *column = SM.getColumnNumber(FID, FileOffset);
2547 if (offset)
2548 *offset = FileOffset;
2549}
2550
Douglas Gregor1db19de2010-01-19 21:36:55 +00002551CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002552 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002553 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002554 return Result;
2555}
2556
2557CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002558 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002559 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002560 return Result;
2561}
2562
Douglas Gregorb9790342010-01-22 21:44:22 +00002563} // end: extern "C"
2564
Douglas Gregor1db19de2010-01-19 21:36:55 +00002565//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002566// CXFile Operations.
2567//===----------------------------------------------------------------------===//
2568
2569extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002570CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002571 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002572 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002573
Steve Naroff88145032009-10-27 14:35:18 +00002574 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002575 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002576}
2577
2578time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002579 if (!SFile)
2580 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Steve Naroff88145032009-10-27 14:35:18 +00002582 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2583 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002584}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Douglas Gregorb9790342010-01-22 21:44:22 +00002586CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2587 if (!tu)
2588 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002589
Ted Kremeneka60ed472010-11-16 08:15:36 +00002590 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002591
Douglas Gregorb9790342010-01-22 21:44:22 +00002592 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002593 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2594 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002595 return const_cast<FileEntry *>(File);
2596}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002597
Ted Kremenekfb480492010-01-13 21:46:36 +00002598} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002599
Ted Kremenekfb480492010-01-13 21:46:36 +00002600//===----------------------------------------------------------------------===//
2601// CXCursor Operations.
2602//===----------------------------------------------------------------------===//
2603
Ted Kremenekfb480492010-01-13 21:46:36 +00002604static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002605 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2606 return getDeclFromExpr(CE->getSubExpr());
2607
Ted Kremenekfb480492010-01-13 21:46:36 +00002608 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2609 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002610 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2611 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002612 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2613 return ME->getMemberDecl();
2614 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2615 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002616 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2617 return PRE->getProperty();
2618
Ted Kremenekfb480492010-01-13 21:46:36 +00002619 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2620 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002621 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2622 if (!CE->isElidable())
2623 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002624 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2625 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002626
Douglas Gregordb1314e2010-10-01 21:11:22 +00002627 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2628 return PE->getProtocol();
2629
Ted Kremenekfb480492010-01-13 21:46:36 +00002630 return 0;
2631}
2632
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002633static SourceLocation getLocationFromExpr(Expr *E) {
2634 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2635 return /*FIXME:*/Msg->getLeftLoc();
2636 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2637 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002638 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2639 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002640 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2641 return Member->getMemberLoc();
2642 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2643 return Ivar->getLocation();
2644 return E->getLocStart();
2645}
2646
Ted Kremenekfb480492010-01-13 21:46:36 +00002647extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002648
2649unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002650 CXCursorVisitor visitor,
2651 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002652 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2653 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002654 return CursorVis.VisitChildren(parent);
2655}
2656
David Chisnall3387c652010-11-03 14:12:26 +00002657#ifndef __has_feature
2658#define __has_feature(x) 0
2659#endif
2660#if __has_feature(blocks)
2661typedef enum CXChildVisitResult
2662 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2663
2664static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2665 CXClientData client_data) {
2666 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2667 return block(cursor, parent);
2668}
2669#else
2670// If we are compiled with a compiler that doesn't have native blocks support,
2671// define and call the block manually, so the
2672typedef struct _CXChildVisitResult
2673{
2674 void *isa;
2675 int flags;
2676 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002677 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2678 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002679} *CXCursorVisitorBlock;
2680
2681static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2682 CXClientData client_data) {
2683 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2684 return block->invoke(block, cursor, parent);
2685}
2686#endif
2687
2688
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002689unsigned clang_visitChildrenWithBlock(CXCursor parent,
2690 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002691 return clang_visitChildren(parent, visitWithBlock, block);
2692}
2693
Douglas Gregor78205d42010-01-20 21:45:58 +00002694static CXString getDeclSpelling(Decl *D) {
2695 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002696 if (!ND) {
2697 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2698 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2699 return createCXString(Property->getIdentifier()->getName());
2700
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002701 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002702 }
2703
Douglas Gregor78205d42010-01-20 21:45:58 +00002704 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002705 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002706
Douglas Gregor78205d42010-01-20 21:45:58 +00002707 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2708 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2709 // and returns different names. NamedDecl returns the class name and
2710 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002711 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002712
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002713 if (isa<UsingDirectiveDecl>(D))
2714 return createCXString("");
2715
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002716 llvm::SmallString<1024> S;
2717 llvm::raw_svector_ostream os(S);
2718 ND->printName(os);
2719
2720 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002721}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002722
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002723CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002724 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002725 return clang_getTranslationUnitSpelling(
2726 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002727
Steve Narofff334b4e2009-09-02 18:26:48 +00002728 if (clang_isReference(C.kind)) {
2729 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002730 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002731 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002732 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002733 }
2734 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002735 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002736 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002737 }
2738 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002739 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002740 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002741 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002742 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002743 case CXCursor_CXXBaseSpecifier: {
2744 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2745 return createCXString(B->getType().getAsString());
2746 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002747 case CXCursor_TypeRef: {
2748 TypeDecl *Type = getCursorTypeRef(C).first;
2749 assert(Type && "Missing type decl");
2750
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002751 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2752 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002753 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002754 case CXCursor_TemplateRef: {
2755 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002756 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002757
2758 return createCXString(Template->getNameAsString());
2759 }
Douglas Gregor69319002010-08-31 23:48:11 +00002760
2761 case CXCursor_NamespaceRef: {
2762 NamedDecl *NS = getCursorNamespaceRef(C).first;
2763 assert(NS && "Missing namespace decl");
2764
2765 return createCXString(NS->getNameAsString());
2766 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002767
Douglas Gregora67e03f2010-09-09 21:42:20 +00002768 case CXCursor_MemberRef: {
2769 FieldDecl *Field = getCursorMemberRef(C).first;
2770 assert(Field && "Missing member decl");
2771
2772 return createCXString(Field->getNameAsString());
2773 }
2774
Douglas Gregor36897b02010-09-10 00:22:18 +00002775 case CXCursor_LabelRef: {
2776 LabelStmt *Label = getCursorLabelRef(C).first;
2777 assert(Label && "Missing label");
2778
2779 return createCXString(Label->getID()->getName());
2780 }
2781
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002782 case CXCursor_OverloadedDeclRef: {
2783 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2784 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2785 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2786 return createCXString(ND->getNameAsString());
2787 return createCXString("");
2788 }
2789 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2790 return createCXString(E->getName().getAsString());
2791 OverloadedTemplateStorage *Ovl
2792 = Storage.get<OverloadedTemplateStorage*>();
2793 if (Ovl->size() == 0)
2794 return createCXString("");
2795 return createCXString((*Ovl->begin())->getNameAsString());
2796 }
2797
Daniel Dunbaracca7252009-11-30 20:42:49 +00002798 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002799 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002800 }
2801 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002802
2803 if (clang_isExpression(C.kind)) {
2804 Decl *D = getDeclFromExpr(getCursorExpr(C));
2805 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002806 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002807 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002808 }
2809
Douglas Gregor36897b02010-09-10 00:22:18 +00002810 if (clang_isStatement(C.kind)) {
2811 Stmt *S = getCursorStmt(C);
2812 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2813 return createCXString(Label->getID()->getName());
2814
2815 return createCXString("");
2816 }
2817
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002818 if (C.kind == CXCursor_MacroInstantiation)
2819 return createCXString(getCursorMacroInstantiation(C)->getName()
2820 ->getNameStart());
2821
Douglas Gregor572feb22010-03-18 18:04:21 +00002822 if (C.kind == CXCursor_MacroDefinition)
2823 return createCXString(getCursorMacroDefinition(C)->getName()
2824 ->getNameStart());
2825
Douglas Gregorecdcb882010-10-20 22:00:55 +00002826 if (C.kind == CXCursor_InclusionDirective)
2827 return createCXString(getCursorInclusionDirective(C)->getFileName());
2828
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002829 if (clang_isDeclaration(C.kind))
2830 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002831
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002832 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002833}
2834
Douglas Gregor358559d2010-10-02 22:49:11 +00002835CXString clang_getCursorDisplayName(CXCursor C) {
2836 if (!clang_isDeclaration(C.kind))
2837 return clang_getCursorSpelling(C);
2838
2839 Decl *D = getCursorDecl(C);
2840 if (!D)
2841 return createCXString("");
2842
2843 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2844 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2845 D = FunTmpl->getTemplatedDecl();
2846
2847 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2848 llvm::SmallString<64> Str;
2849 llvm::raw_svector_ostream OS(Str);
2850 OS << Function->getNameAsString();
2851 if (Function->getPrimaryTemplate())
2852 OS << "<>";
2853 OS << "(";
2854 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2855 if (I)
2856 OS << ", ";
2857 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2858 }
2859
2860 if (Function->isVariadic()) {
2861 if (Function->getNumParams())
2862 OS << ", ";
2863 OS << "...";
2864 }
2865 OS << ")";
2866 return createCXString(OS.str());
2867 }
2868
2869 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2870 llvm::SmallString<64> Str;
2871 llvm::raw_svector_ostream OS(Str);
2872 OS << ClassTemplate->getNameAsString();
2873 OS << "<";
2874 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2875 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2876 if (I)
2877 OS << ", ";
2878
2879 NamedDecl *Param = Params->getParam(I);
2880 if (Param->getIdentifier()) {
2881 OS << Param->getIdentifier()->getName();
2882 continue;
2883 }
2884
2885 // There is no parameter name, which makes this tricky. Try to come up
2886 // with something useful that isn't too long.
2887 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2888 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2889 else if (NonTypeTemplateParmDecl *NTTP
2890 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2891 OS << NTTP->getType().getAsString(Policy);
2892 else
2893 OS << "template<...> class";
2894 }
2895
2896 OS << ">";
2897 return createCXString(OS.str());
2898 }
2899
2900 if (ClassTemplateSpecializationDecl *ClassSpec
2901 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2902 // If the type was explicitly written, use that.
2903 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2904 return createCXString(TSInfo->getType().getAsString(Policy));
2905
2906 llvm::SmallString<64> Str;
2907 llvm::raw_svector_ostream OS(Str);
2908 OS << ClassSpec->getNameAsString();
2909 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002910 ClassSpec->getTemplateArgs().data(),
2911 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002912 Policy);
2913 return createCXString(OS.str());
2914 }
2915
2916 return clang_getCursorSpelling(C);
2917}
2918
Ted Kremeneke68fff62010-02-17 00:41:32 +00002919CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002920 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002921 case CXCursor_FunctionDecl:
2922 return createCXString("FunctionDecl");
2923 case CXCursor_TypedefDecl:
2924 return createCXString("TypedefDecl");
2925 case CXCursor_EnumDecl:
2926 return createCXString("EnumDecl");
2927 case CXCursor_EnumConstantDecl:
2928 return createCXString("EnumConstantDecl");
2929 case CXCursor_StructDecl:
2930 return createCXString("StructDecl");
2931 case CXCursor_UnionDecl:
2932 return createCXString("UnionDecl");
2933 case CXCursor_ClassDecl:
2934 return createCXString("ClassDecl");
2935 case CXCursor_FieldDecl:
2936 return createCXString("FieldDecl");
2937 case CXCursor_VarDecl:
2938 return createCXString("VarDecl");
2939 case CXCursor_ParmDecl:
2940 return createCXString("ParmDecl");
2941 case CXCursor_ObjCInterfaceDecl:
2942 return createCXString("ObjCInterfaceDecl");
2943 case CXCursor_ObjCCategoryDecl:
2944 return createCXString("ObjCCategoryDecl");
2945 case CXCursor_ObjCProtocolDecl:
2946 return createCXString("ObjCProtocolDecl");
2947 case CXCursor_ObjCPropertyDecl:
2948 return createCXString("ObjCPropertyDecl");
2949 case CXCursor_ObjCIvarDecl:
2950 return createCXString("ObjCIvarDecl");
2951 case CXCursor_ObjCInstanceMethodDecl:
2952 return createCXString("ObjCInstanceMethodDecl");
2953 case CXCursor_ObjCClassMethodDecl:
2954 return createCXString("ObjCClassMethodDecl");
2955 case CXCursor_ObjCImplementationDecl:
2956 return createCXString("ObjCImplementationDecl");
2957 case CXCursor_ObjCCategoryImplDecl:
2958 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002959 case CXCursor_CXXMethod:
2960 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002961 case CXCursor_UnexposedDecl:
2962 return createCXString("UnexposedDecl");
2963 case CXCursor_ObjCSuperClassRef:
2964 return createCXString("ObjCSuperClassRef");
2965 case CXCursor_ObjCProtocolRef:
2966 return createCXString("ObjCProtocolRef");
2967 case CXCursor_ObjCClassRef:
2968 return createCXString("ObjCClassRef");
2969 case CXCursor_TypeRef:
2970 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002971 case CXCursor_TemplateRef:
2972 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002973 case CXCursor_NamespaceRef:
2974 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002975 case CXCursor_MemberRef:
2976 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002977 case CXCursor_LabelRef:
2978 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002979 case CXCursor_OverloadedDeclRef:
2980 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002981 case CXCursor_UnexposedExpr:
2982 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002983 case CXCursor_BlockExpr:
2984 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002985 case CXCursor_DeclRefExpr:
2986 return createCXString("DeclRefExpr");
2987 case CXCursor_MemberRefExpr:
2988 return createCXString("MemberRefExpr");
2989 case CXCursor_CallExpr:
2990 return createCXString("CallExpr");
2991 case CXCursor_ObjCMessageExpr:
2992 return createCXString("ObjCMessageExpr");
2993 case CXCursor_UnexposedStmt:
2994 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002995 case CXCursor_LabelStmt:
2996 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002997 case CXCursor_InvalidFile:
2998 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002999 case CXCursor_InvalidCode:
3000 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003001 case CXCursor_NoDeclFound:
3002 return createCXString("NoDeclFound");
3003 case CXCursor_NotImplemented:
3004 return createCXString("NotImplemented");
3005 case CXCursor_TranslationUnit:
3006 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003007 case CXCursor_UnexposedAttr:
3008 return createCXString("UnexposedAttr");
3009 case CXCursor_IBActionAttr:
3010 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003011 case CXCursor_IBOutletAttr:
3012 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003013 case CXCursor_IBOutletCollectionAttr:
3014 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003015 case CXCursor_PreprocessingDirective:
3016 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003017 case CXCursor_MacroDefinition:
3018 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003019 case CXCursor_MacroInstantiation:
3020 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003021 case CXCursor_InclusionDirective:
3022 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003023 case CXCursor_Namespace:
3024 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003025 case CXCursor_LinkageSpec:
3026 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003027 case CXCursor_CXXBaseSpecifier:
3028 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003029 case CXCursor_Constructor:
3030 return createCXString("CXXConstructor");
3031 case CXCursor_Destructor:
3032 return createCXString("CXXDestructor");
3033 case CXCursor_ConversionFunction:
3034 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003035 case CXCursor_TemplateTypeParameter:
3036 return createCXString("TemplateTypeParameter");
3037 case CXCursor_NonTypeTemplateParameter:
3038 return createCXString("NonTypeTemplateParameter");
3039 case CXCursor_TemplateTemplateParameter:
3040 return createCXString("TemplateTemplateParameter");
3041 case CXCursor_FunctionTemplate:
3042 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003043 case CXCursor_ClassTemplate:
3044 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003045 case CXCursor_ClassTemplatePartialSpecialization:
3046 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003047 case CXCursor_NamespaceAlias:
3048 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003049 case CXCursor_UsingDirective:
3050 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003051 case CXCursor_UsingDeclaration:
3052 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003053 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003054
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003055 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003056 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003057}
Steve Naroff89922f82009-08-31 00:59:03 +00003058
Ted Kremeneke68fff62010-02-17 00:41:32 +00003059enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3060 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003061 CXClientData client_data) {
3062 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003063
3064 // If our current best cursor is the construction of a temporary object,
3065 // don't replace that cursor with a type reference, because we want
3066 // clang_getCursor() to point at the constructor.
3067 if (clang_isExpression(BestCursor->kind) &&
3068 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3069 cursor.kind == CXCursor_TypeRef)
3070 return CXChildVisit_Recurse;
3071
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003072 *BestCursor = cursor;
3073 return CXChildVisit_Recurse;
3074}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003075
Douglas Gregorb9790342010-01-22 21:44:22 +00003076CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3077 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003078 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003079
Ted Kremeneka60ed472010-11-16 08:15:36 +00003080 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003081 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3082
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003083 // Translate the given source location to make it point at the beginning of
3084 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003085 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003086
3087 // Guard against an invalid SourceLocation, or we may assert in one
3088 // of the following calls.
3089 if (SLoc.isInvalid())
3090 return clang_getNullCursor();
3091
Douglas Gregor40749ee2010-11-03 00:35:38 +00003092 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003093 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3094 CXXUnit->getASTContext().getLangOptions());
3095
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003096 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3097 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003098 // FIXME: Would be great to have a "hint" cursor, then walk from that
3099 // hint cursor upward until we find a cursor whose source range encloses
3100 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003101 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3102 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003103 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003104 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003105 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003106
3107 if (Logging) {
3108 CXFile SearchFile;
3109 unsigned SearchLine, SearchColumn;
3110 CXFile ResultFile;
3111 unsigned ResultLine, ResultColumn;
3112 CXString SearchFileName, ResultFileName, KindSpelling;
3113 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3114
3115 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3116 0);
3117 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3118 &ResultColumn, 0);
3119 SearchFileName = clang_getFileName(SearchFile);
3120 ResultFileName = clang_getFileName(ResultFile);
3121 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3122 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3123 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3124 clang_getCString(KindSpelling),
3125 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3126 clang_disposeString(SearchFileName);
3127 clang_disposeString(ResultFileName);
3128 clang_disposeString(KindSpelling);
3129 }
3130
Ted Kremeneke68fff62010-02-17 00:41:32 +00003131 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003132}
3133
Ted Kremenek73885552009-11-17 19:28:59 +00003134CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003135 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003136}
3137
3138unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003139 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003140}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003141
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003142unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003143 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3144}
3145
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003146unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003147 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3148}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003149
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003150unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003151 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3152}
3153
Douglas Gregor97b98722010-01-19 23:20:36 +00003154unsigned clang_isExpression(enum CXCursorKind K) {
3155 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3156}
3157
3158unsigned clang_isStatement(enum CXCursorKind K) {
3159 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3160}
3161
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003162unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3163 return K == CXCursor_TranslationUnit;
3164}
3165
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003166unsigned clang_isPreprocessing(enum CXCursorKind K) {
3167 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3168}
3169
Ted Kremenekad6eff62010-03-08 21:17:29 +00003170unsigned clang_isUnexposed(enum CXCursorKind K) {
3171 switch (K) {
3172 case CXCursor_UnexposedDecl:
3173 case CXCursor_UnexposedExpr:
3174 case CXCursor_UnexposedStmt:
3175 case CXCursor_UnexposedAttr:
3176 return true;
3177 default:
3178 return false;
3179 }
3180}
3181
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003182CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003183 return C.kind;
3184}
3185
Douglas Gregor98258af2010-01-18 22:46:11 +00003186CXSourceLocation clang_getCursorLocation(CXCursor C) {
3187 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003188 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003189 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003190 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3191 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003192 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003193 }
3194
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003195 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003196 std::pair<ObjCProtocolDecl *, SourceLocation> P
3197 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003198 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003199 }
3200
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003201 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003202 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3203 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003204 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003205 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003206
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003207 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003208 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003209 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003210 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003211
3212 case CXCursor_TemplateRef: {
3213 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3214 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3215 }
3216
Douglas Gregor69319002010-08-31 23:48:11 +00003217 case CXCursor_NamespaceRef: {
3218 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3219 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3220 }
3221
Douglas Gregora67e03f2010-09-09 21:42:20 +00003222 case CXCursor_MemberRef: {
3223 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3224 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3225 }
3226
Ted Kremenek3064ef92010-08-27 21:34:58 +00003227 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003228 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3229 if (!BaseSpec)
3230 return clang_getNullLocation();
3231
3232 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3233 return cxloc::translateSourceLocation(getCursorContext(C),
3234 TSInfo->getTypeLoc().getBeginLoc());
3235
3236 return cxloc::translateSourceLocation(getCursorContext(C),
3237 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003238 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003239
Douglas Gregor36897b02010-09-10 00:22:18 +00003240 case CXCursor_LabelRef: {
3241 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3242 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3243 }
3244
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003245 case CXCursor_OverloadedDeclRef:
3246 return cxloc::translateSourceLocation(getCursorContext(C),
3247 getCursorOverloadedDeclRef(C).second);
3248
Douglas Gregorf46034a2010-01-18 23:41:10 +00003249 default:
3250 // FIXME: Need a way to enumerate all non-reference cases.
3251 llvm_unreachable("Missed a reference kind");
3252 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003253 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003254
3255 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003256 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003257 getLocationFromExpr(getCursorExpr(C)));
3258
Douglas Gregor36897b02010-09-10 00:22:18 +00003259 if (clang_isStatement(C.kind))
3260 return cxloc::translateSourceLocation(getCursorContext(C),
3261 getCursorStmt(C)->getLocStart());
3262
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003263 if (C.kind == CXCursor_PreprocessingDirective) {
3264 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3265 return cxloc::translateSourceLocation(getCursorContext(C), L);
3266 }
Douglas Gregor48072312010-03-18 15:23:44 +00003267
3268 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003269 SourceLocation L
3270 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003271 return cxloc::translateSourceLocation(getCursorContext(C), L);
3272 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003273
3274 if (C.kind == CXCursor_MacroDefinition) {
3275 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3276 return cxloc::translateSourceLocation(getCursorContext(C), L);
3277 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003278
3279 if (C.kind == CXCursor_InclusionDirective) {
3280 SourceLocation L
3281 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3282 return cxloc::translateSourceLocation(getCursorContext(C), L);
3283 }
3284
Ted Kremenek9a700d22010-05-12 06:16:13 +00003285 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003286 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003287
Douglas Gregorf46034a2010-01-18 23:41:10 +00003288 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003289 SourceLocation Loc = D->getLocation();
3290 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3291 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003292 // FIXME: Multiple variables declared in a single declaration
3293 // currently lack the information needed to correctly determine their
3294 // ranges when accounting for the type-specifier. We use context
3295 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3296 // and if so, whether it is the first decl.
3297 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3298 if (!cxcursor::isFirstInDeclGroup(C))
3299 Loc = VD->getLocation();
3300 }
3301
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003302 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003303}
Douglas Gregora7bde202010-01-19 00:34:46 +00003304
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003305} // end extern "C"
3306
3307static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003308 if (clang_isReference(C.kind)) {
3309 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003310 case CXCursor_ObjCSuperClassRef:
3311 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003312
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003313 case CXCursor_ObjCProtocolRef:
3314 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003315
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003316 case CXCursor_ObjCClassRef:
3317 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003318
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003319 case CXCursor_TypeRef:
3320 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003321
3322 case CXCursor_TemplateRef:
3323 return getCursorTemplateRef(C).second;
3324
Douglas Gregor69319002010-08-31 23:48:11 +00003325 case CXCursor_NamespaceRef:
3326 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003327
3328 case CXCursor_MemberRef:
3329 return getCursorMemberRef(C).second;
3330
Ted Kremenek3064ef92010-08-27 21:34:58 +00003331 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003332 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003333
Douglas Gregor36897b02010-09-10 00:22:18 +00003334 case CXCursor_LabelRef:
3335 return getCursorLabelRef(C).second;
3336
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003337 case CXCursor_OverloadedDeclRef:
3338 return getCursorOverloadedDeclRef(C).second;
3339
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003340 default:
3341 // FIXME: Need a way to enumerate all non-reference cases.
3342 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003343 }
3344 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003345
3346 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003347 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003348
3349 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003350 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003351
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003352 if (C.kind == CXCursor_PreprocessingDirective)
3353 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003354
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003355 if (C.kind == CXCursor_MacroInstantiation)
3356 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003357
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003358 if (C.kind == CXCursor_MacroDefinition)
3359 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003360
3361 if (C.kind == CXCursor_InclusionDirective)
3362 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3363
Ted Kremenek007a7c92010-11-01 23:26:51 +00003364 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3365 Decl *D = cxcursor::getCursorDecl(C);
3366 SourceRange R = D->getSourceRange();
3367 // FIXME: Multiple variables declared in a single declaration
3368 // currently lack the information needed to correctly determine their
3369 // ranges when accounting for the type-specifier. We use context
3370 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3371 // and if so, whether it is the first decl.
3372 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3373 if (!cxcursor::isFirstInDeclGroup(C))
3374 R.setBegin(VD->getLocation());
3375 }
3376 return R;
3377 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003378 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003379
3380extern "C" {
3381
3382CXSourceRange clang_getCursorExtent(CXCursor C) {
3383 SourceRange R = getRawCursorExtent(C);
3384 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003385 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003386
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003387 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003388}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003389
3390CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003391 if (clang_isInvalid(C.kind))
3392 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003393
Ted Kremeneka60ed472010-11-16 08:15:36 +00003394 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003395 if (clang_isDeclaration(C.kind)) {
3396 Decl *D = getCursorDecl(C);
3397 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003398 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003399 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003400 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003401 if (ObjCForwardProtocolDecl *Protocols
3402 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003403 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003404 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3405 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3406 return MakeCXCursor(Property, tu);
3407
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003408 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003409 }
3410
Douglas Gregor97b98722010-01-19 23:20:36 +00003411 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003412 Expr *E = getCursorExpr(C);
3413 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003414 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003415 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003416
3417 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003418 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003419
Douglas Gregor97b98722010-01-19 23:20:36 +00003420 return clang_getNullCursor();
3421 }
3422
Douglas Gregor36897b02010-09-10 00:22:18 +00003423 if (clang_isStatement(C.kind)) {
3424 Stmt *S = getCursorStmt(C);
3425 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003426 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003427
3428 return clang_getNullCursor();
3429 }
3430
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003431 if (C.kind == CXCursor_MacroInstantiation) {
3432 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003433 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003434 }
3435
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003436 if (!clang_isReference(C.kind))
3437 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003439 switch (C.kind) {
3440 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003441 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003442
3443 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003444 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003445
3446 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003447 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003448
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003449 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003450 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003451
3452 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003453 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003454
Douglas Gregor69319002010-08-31 23:48:11 +00003455 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003456 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003457
Douglas Gregora67e03f2010-09-09 21:42:20 +00003458 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003459 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003460
Ted Kremenek3064ef92010-08-27 21:34:58 +00003461 case CXCursor_CXXBaseSpecifier: {
3462 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3463 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003464 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003465 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003466
Douglas Gregor36897b02010-09-10 00:22:18 +00003467 case CXCursor_LabelRef:
3468 // FIXME: We end up faking the "parent" declaration here because we
3469 // don't want to make CXCursor larger.
3470 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003471 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3472 .getTranslationUnitDecl(),
3473 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003474
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003475 case CXCursor_OverloadedDeclRef:
3476 return C;
3477
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003478 default:
3479 // We would prefer to enumerate all non-reference cursor kinds here.
3480 llvm_unreachable("Unhandled reference cursor kind");
3481 break;
3482 }
3483 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003484
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003485 return clang_getNullCursor();
3486}
3487
Douglas Gregorb6998662010-01-19 19:34:47 +00003488CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003489 if (clang_isInvalid(C.kind))
3490 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003491
Ted Kremeneka60ed472010-11-16 08:15:36 +00003492 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003493
Douglas Gregorb6998662010-01-19 19:34:47 +00003494 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003495 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003496 C = clang_getCursorReferenced(C);
3497 WasReference = true;
3498 }
3499
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003500 if (C.kind == CXCursor_MacroInstantiation)
3501 return clang_getCursorReferenced(C);
3502
Douglas Gregorb6998662010-01-19 19:34:47 +00003503 if (!clang_isDeclaration(C.kind))
3504 return clang_getNullCursor();
3505
3506 Decl *D = getCursorDecl(C);
3507 if (!D)
3508 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003509
Douglas Gregorb6998662010-01-19 19:34:47 +00003510 switch (D->getKind()) {
3511 // Declaration kinds that don't really separate the notions of
3512 // declaration and definition.
3513 case Decl::Namespace:
3514 case Decl::Typedef:
3515 case Decl::TemplateTypeParm:
3516 case Decl::EnumConstant:
3517 case Decl::Field:
3518 case Decl::ObjCIvar:
3519 case Decl::ObjCAtDefsField:
3520 case Decl::ImplicitParam:
3521 case Decl::ParmVar:
3522 case Decl::NonTypeTemplateParm:
3523 case Decl::TemplateTemplateParm:
3524 case Decl::ObjCCategoryImpl:
3525 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003526 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003527 case Decl::LinkageSpec:
3528 case Decl::ObjCPropertyImpl:
3529 case Decl::FileScopeAsm:
3530 case Decl::StaticAssert:
3531 case Decl::Block:
3532 return C;
3533
3534 // Declaration kinds that don't make any sense here, but are
3535 // nonetheless harmless.
3536 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003537 break;
3538
3539 // Declaration kinds for which the definition is not resolvable.
3540 case Decl::UnresolvedUsingTypename:
3541 case Decl::UnresolvedUsingValue:
3542 break;
3543
3544 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003545 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003546 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003547
3548 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003549 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003550
3551 case Decl::Enum:
3552 case Decl::Record:
3553 case Decl::CXXRecord:
3554 case Decl::ClassTemplateSpecialization:
3555 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003556 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003557 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003558 return clang_getNullCursor();
3559
3560 case Decl::Function:
3561 case Decl::CXXMethod:
3562 case Decl::CXXConstructor:
3563 case Decl::CXXDestructor:
3564 case Decl::CXXConversion: {
3565 const FunctionDecl *Def = 0;
3566 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003567 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003568 return clang_getNullCursor();
3569 }
3570
3571 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003572 // Ask the variable if it has a definition.
3573 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003574 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003575 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003576 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003577
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 case Decl::FunctionTemplate: {
3579 const FunctionDecl *Def = 0;
3580 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003581 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003582 return clang_getNullCursor();
3583 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003584
Douglas Gregorb6998662010-01-19 19:34:47 +00003585 case Decl::ClassTemplate: {
3586 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003587 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003588 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003589 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003590 return clang_getNullCursor();
3591 }
3592
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003593 case Decl::Using:
3594 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003595 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003596
3597 case Decl::UsingShadow:
3598 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003599 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003600 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003601
3602 case Decl::ObjCMethod: {
3603 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3604 if (Method->isThisDeclarationADefinition())
3605 return C;
3606
3607 // Dig out the method definition in the associated
3608 // @implementation, if we have it.
3609 // FIXME: The ASTs should make finding the definition easier.
3610 if (ObjCInterfaceDecl *Class
3611 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3612 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3613 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3614 Method->isInstanceMethod()))
3615 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003616 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003617
3618 return clang_getNullCursor();
3619 }
3620
3621 case Decl::ObjCCategory:
3622 if (ObjCCategoryImplDecl *Impl
3623 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003624 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003625 return clang_getNullCursor();
3626
3627 case Decl::ObjCProtocol:
3628 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3629 return C;
3630 return clang_getNullCursor();
3631
3632 case Decl::ObjCInterface:
3633 // There are two notions of a "definition" for an Objective-C
3634 // class: the interface and its implementation. When we resolved a
3635 // reference to an Objective-C class, produce the @interface as
3636 // the definition; when we were provided with the interface,
3637 // produce the @implementation as the definition.
3638 if (WasReference) {
3639 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3640 return C;
3641 } else if (ObjCImplementationDecl *Impl
3642 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003643 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003644 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003645
Douglas Gregorb6998662010-01-19 19:34:47 +00003646 case Decl::ObjCProperty:
3647 // FIXME: We don't really know where to find the
3648 // ObjCPropertyImplDecls that implement this property.
3649 return clang_getNullCursor();
3650
3651 case Decl::ObjCCompatibleAlias:
3652 if (ObjCInterfaceDecl *Class
3653 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3654 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003655 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003656
Douglas Gregorb6998662010-01-19 19:34:47 +00003657 return clang_getNullCursor();
3658
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003659 case Decl::ObjCForwardProtocol:
3660 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003661 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003662
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003663 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003664 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003665 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003666
3667 case Decl::Friend:
3668 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003669 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003670 return clang_getNullCursor();
3671
3672 case Decl::FriendTemplate:
3673 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003674 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003675 return clang_getNullCursor();
3676 }
3677
3678 return clang_getNullCursor();
3679}
3680
3681unsigned clang_isCursorDefinition(CXCursor C) {
3682 if (!clang_isDeclaration(C.kind))
3683 return 0;
3684
3685 return clang_getCursorDefinition(C) == C;
3686}
3687
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003688unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003689 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003690 return 0;
3691
3692 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3693 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3694 return E->getNumDecls();
3695
3696 if (OverloadedTemplateStorage *S
3697 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3698 return S->size();
3699
3700 Decl *D = Storage.get<Decl*>();
3701 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003702 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003703 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3704 return Classes->size();
3705 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3706 return Protocols->protocol_size();
3707
3708 return 0;
3709}
3710
3711CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003712 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003713 return clang_getNullCursor();
3714
3715 if (index >= clang_getNumOverloadedDecls(cursor))
3716 return clang_getNullCursor();
3717
Ted Kremeneka60ed472010-11-16 08:15:36 +00003718 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003719 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3720 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003721 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003722
3723 if (OverloadedTemplateStorage *S
3724 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003725 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003726
3727 Decl *D = Storage.get<Decl*>();
3728 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3729 // FIXME: This is, unfortunately, linear time.
3730 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3731 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003732 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003733 }
3734
3735 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003736 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003737
3738 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003739 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003740
3741 return clang_getNullCursor();
3742}
3743
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003744void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003745 const char **startBuf,
3746 const char **endBuf,
3747 unsigned *startLine,
3748 unsigned *startColumn,
3749 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003750 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003751 assert(getCursorDecl(C) && "CXCursor has null decl");
3752 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003753 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3754 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003755
Steve Naroff4ade6d62009-09-23 17:52:52 +00003756 SourceManager &SM = FD->getASTContext().getSourceManager();
3757 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3758 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3759 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3760 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3761 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3762 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3763}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003764
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003765void clang_enableStackTraces(void) {
3766 llvm::sys::PrintStackTraceOnErrorSignal();
3767}
3768
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003769void clang_executeOnThread(void (*fn)(void*), void *user_data,
3770 unsigned stack_size) {
3771 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3772}
3773
Ted Kremenekfb480492010-01-13 21:46:36 +00003774} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003775
Ted Kremenekfb480492010-01-13 21:46:36 +00003776//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003777// Token-based Operations.
3778//===----------------------------------------------------------------------===//
3779
3780/* CXToken layout:
3781 * int_data[0]: a CXTokenKind
3782 * int_data[1]: starting token location
3783 * int_data[2]: token length
3784 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003785 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003786 * otherwise unused.
3787 */
3788extern "C" {
3789
3790CXTokenKind clang_getTokenKind(CXToken CXTok) {
3791 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3792}
3793
3794CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3795 switch (clang_getTokenKind(CXTok)) {
3796 case CXToken_Identifier:
3797 case CXToken_Keyword:
3798 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003799 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3800 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003801
3802 case CXToken_Literal: {
3803 // We have stashed the starting pointer in the ptr_data field. Use it.
3804 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003805 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003806 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003807
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003808 case CXToken_Punctuation:
3809 case CXToken_Comment:
3810 break;
3811 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003812
3813 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003814 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003815 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003816 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003817 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003818
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003819 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3820 std::pair<FileID, unsigned> LocInfo
3821 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003822 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003823 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003824 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3825 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003826 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003827
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003828 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003829}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003830
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003831CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003832 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003833 if (!CXXUnit)
3834 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003836 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3837 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3838}
3839
3840CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003841 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003842 if (!CXXUnit)
3843 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003844
3845 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003846 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3847}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003848
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003849void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3850 CXToken **Tokens, unsigned *NumTokens) {
3851 if (Tokens)
3852 *Tokens = 0;
3853 if (NumTokens)
3854 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003855
Ted Kremeneka60ed472010-11-16 08:15:36 +00003856 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003857 if (!CXXUnit || !Tokens || !NumTokens)
3858 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregorbdf60622010-03-05 21:16:25 +00003860 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3861
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003862 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003863 if (R.isInvalid())
3864 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003865
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003866 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3867 std::pair<FileID, unsigned> BeginLocInfo
3868 = SourceMgr.getDecomposedLoc(R.getBegin());
3869 std::pair<FileID, unsigned> EndLocInfo
3870 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003871
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003872 // Cannot tokenize across files.
3873 if (BeginLocInfo.first != EndLocInfo.first)
3874 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003875
3876 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003877 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003878 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003879 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003880 if (Invalid)
3881 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003882
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003883 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3884 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003885 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003886 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003888 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003889 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 llvm::SmallVector<CXToken, 32> CXTokens;
3891 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003892 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893 do {
3894 // Lex the next token
3895 Lex.LexFromRawLexer(Tok);
3896 if (Tok.is(tok::eof))
3897 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003898
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003899 // Initialize the CXToken.
3900 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003901
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003902 // - Common fields
3903 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3904 CXTok.int_data[2] = Tok.getLength();
3905 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003906
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003907 // - Kind-specific fields
3908 if (Tok.isLiteral()) {
3909 CXTok.int_data[0] = CXToken_Literal;
3910 CXTok.ptr_data = (void *)Tok.getLiteralData();
3911 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003912 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003913 std::pair<FileID, unsigned> LocInfo
3914 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003915 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003916 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003917 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3918 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003919 return;
3920
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003921 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003922 IdentifierInfo *II
3923 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003924
David Chisnall096428b2010-10-13 21:44:48 +00003925 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003926 CXTok.int_data[0] = CXToken_Keyword;
3927 }
3928 else {
3929 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3930 CXToken_Identifier
3931 : CXToken_Keyword;
3932 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003933 CXTok.ptr_data = II;
3934 } else if (Tok.is(tok::comment)) {
3935 CXTok.int_data[0] = CXToken_Comment;
3936 CXTok.ptr_data = 0;
3937 } else {
3938 CXTok.int_data[0] = CXToken_Punctuation;
3939 CXTok.ptr_data = 0;
3940 }
3941 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003942 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003943 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003944
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003945 if (CXTokens.empty())
3946 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003947
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003948 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3949 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3950 *NumTokens = CXTokens.size();
3951}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003952
Ted Kremenek6db61092010-05-05 00:55:15 +00003953void clang_disposeTokens(CXTranslationUnit TU,
3954 CXToken *Tokens, unsigned NumTokens) {
3955 free(Tokens);
3956}
3957
3958} // end: extern "C"
3959
3960//===----------------------------------------------------------------------===//
3961// Token annotation APIs.
3962//===----------------------------------------------------------------------===//
3963
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003964typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003965static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3966 CXCursor parent,
3967 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003968namespace {
3969class AnnotateTokensWorker {
3970 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003971 CXToken *Tokens;
3972 CXCursor *Cursors;
3973 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003974 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003975 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003976 CursorVisitor AnnotateVis;
3977 SourceManager &SrcMgr;
3978
3979 bool MoreTokens() const { return TokIdx < NumTokens; }
3980 unsigned NextToken() const { return TokIdx; }
3981 void AdvanceToken() { ++TokIdx; }
3982 SourceLocation GetTokenLoc(unsigned tokI) {
3983 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3984 }
3985
Ted Kremenek6db61092010-05-05 00:55:15 +00003986public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003987 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003988 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003989 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003990 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003991 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003992 AnnotateVis(tu,
3993 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003994 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003995 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003996
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003997 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003998 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003999 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004000 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004001 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004002 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004003};
4004}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004005
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004006void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4007 // Walk the AST within the region of interest, annotating tokens
4008 // along the way.
4009 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004010
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004011 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4012 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004013 if (Pos != Annotated.end() &&
4014 (clang_isInvalid(Cursors[I].kind) ||
4015 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004016 Cursors[I] = Pos->second;
4017 }
4018
4019 // Finish up annotating any tokens left.
4020 if (!MoreTokens())
4021 return;
4022
4023 const CXCursor &C = clang_getNullCursor();
4024 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4025 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4026 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004027 }
4028}
4029
Ted Kremenek6db61092010-05-05 00:55:15 +00004030enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004031AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004032 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004033 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004034 if (cursorRange.isInvalid())
4035 return CXChildVisit_Recurse;
4036
Douglas Gregor4419b672010-10-21 06:10:04 +00004037 if (clang_isPreprocessing(cursor.kind)) {
4038 // For macro instantiations, just note where the beginning of the macro
4039 // instantiation occurs.
4040 if (cursor.kind == CXCursor_MacroInstantiation) {
4041 Annotated[Loc.int_data] = cursor;
4042 return CXChildVisit_Recurse;
4043 }
4044
Douglas Gregor4419b672010-10-21 06:10:04 +00004045 // Items in the preprocessing record are kept separate from items in
4046 // declarations, so we keep a separate token index.
4047 unsigned SavedTokIdx = TokIdx;
4048 TokIdx = PreprocessingTokIdx;
4049
4050 // Skip tokens up until we catch up to the beginning of the preprocessing
4051 // entry.
4052 while (MoreTokens()) {
4053 const unsigned I = NextToken();
4054 SourceLocation TokLoc = GetTokenLoc(I);
4055 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4056 case RangeBefore:
4057 AdvanceToken();
4058 continue;
4059 case RangeAfter:
4060 case RangeOverlap:
4061 break;
4062 }
4063 break;
4064 }
4065
4066 // Look at all of the tokens within this range.
4067 while (MoreTokens()) {
4068 const unsigned I = NextToken();
4069 SourceLocation TokLoc = GetTokenLoc(I);
4070 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4071 case RangeBefore:
4072 assert(0 && "Infeasible");
4073 case RangeAfter:
4074 break;
4075 case RangeOverlap:
4076 Cursors[I] = cursor;
4077 AdvanceToken();
4078 continue;
4079 }
4080 break;
4081 }
4082
4083 // Save the preprocessing token index; restore the non-preprocessing
4084 // token index.
4085 PreprocessingTokIdx = TokIdx;
4086 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004087 return CXChildVisit_Recurse;
4088 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004089
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004090 if (cursorRange.isInvalid())
4091 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004092
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004093 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4094
Ted Kremeneka333c662010-05-12 05:29:33 +00004095 // Adjust the annotated range based specific declarations.
4096 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4097 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004098 Decl *D = cxcursor::getCursorDecl(cursor);
4099 // Don't visit synthesized ObjC methods, since they have no syntatic
4100 // representation in the source.
4101 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4102 if (MD->isSynthesized())
4103 return CXChildVisit_Continue;
4104 }
4105 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004106 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4107 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004108 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004109 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004110 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004111 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004112 }
4113 }
4114 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004115
Ted Kremenek3f404602010-08-14 01:14:06 +00004116 // If the location of the cursor occurs within a macro instantiation, record
4117 // the spelling location of the cursor in our annotation map. We can then
4118 // paper over the token labelings during a post-processing step to try and
4119 // get cursor mappings for tokens that are the *arguments* of a macro
4120 // instantiation.
4121 if (L.isMacroID()) {
4122 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4123 // Only invalidate the old annotation if it isn't part of a preprocessing
4124 // directive. Here we assume that the default construction of CXCursor
4125 // results in CXCursor.kind being an initialized value (i.e., 0). If
4126 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004127
Ted Kremenek3f404602010-08-14 01:14:06 +00004128 CXCursor &oldC = Annotated[rawEncoding];
4129 if (!clang_isPreprocessing(oldC.kind))
4130 oldC = cursor;
4131 }
4132
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004133 const enum CXCursorKind K = clang_getCursorKind(parent);
4134 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004135 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4136 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004137
4138 while (MoreTokens()) {
4139 const unsigned I = NextToken();
4140 SourceLocation TokLoc = GetTokenLoc(I);
4141 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4142 case RangeBefore:
4143 Cursors[I] = updateC;
4144 AdvanceToken();
4145 continue;
4146 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004147 case RangeOverlap:
4148 break;
4149 }
4150 break;
4151 }
4152
4153 // Visit children to get their cursor information.
4154 const unsigned BeforeChildren = NextToken();
4155 VisitChildren(cursor);
4156 const unsigned AfterChildren = NextToken();
4157
4158 // Adjust 'Last' to the last token within the extent of the cursor.
4159 while (MoreTokens()) {
4160 const unsigned I = NextToken();
4161 SourceLocation TokLoc = GetTokenLoc(I);
4162 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4163 case RangeBefore:
4164 assert(0 && "Infeasible");
4165 case RangeAfter:
4166 break;
4167 case RangeOverlap:
4168 Cursors[I] = updateC;
4169 AdvanceToken();
4170 continue;
4171 }
4172 break;
4173 }
4174 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004175
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004176 // Scan the tokens that are at the beginning of the cursor, but are not
4177 // capture by the child cursors.
4178
4179 // For AST elements within macros, rely on a post-annotate pass to
4180 // to correctly annotate the tokens with cursors. Otherwise we can
4181 // get confusing results of having tokens that map to cursors that really
4182 // are expanded by an instantiation.
4183 if (L.isMacroID())
4184 cursor = clang_getNullCursor();
4185
4186 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4187 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4188 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004189
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004190 Cursors[I] = cursor;
4191 }
4192 // Scan the tokens that are at the end of the cursor, but are not captured
4193 // but the child cursors.
4194 for (unsigned I = AfterChildren; I != Last; ++I)
4195 Cursors[I] = cursor;
4196
4197 TokIdx = Last;
4198 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004199}
4200
Ted Kremenek6db61092010-05-05 00:55:15 +00004201static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4202 CXCursor parent,
4203 CXClientData client_data) {
4204 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4205}
4206
Ted Kremenekab979612010-11-11 08:05:23 +00004207// This gets run a separate thread to avoid stack blowout.
4208static void runAnnotateTokensWorker(void *UserData) {
4209 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4210}
4211
Ted Kremenek6db61092010-05-05 00:55:15 +00004212extern "C" {
4213
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004214void clang_annotateTokens(CXTranslationUnit TU,
4215 CXToken *Tokens, unsigned NumTokens,
4216 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004217
4218 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004219 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004220
Douglas Gregor4419b672010-10-21 06:10:04 +00004221 // Any token we don't specifically annotate will have a NULL cursor.
4222 CXCursor C = clang_getNullCursor();
4223 for (unsigned I = 0; I != NumTokens; ++I)
4224 Cursors[I] = C;
4225
Ted Kremeneka60ed472010-11-16 08:15:36 +00004226 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004227 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004228 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229
Douglas Gregorbdf60622010-03-05 21:16:25 +00004230 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004231
Douglas Gregor0396f462010-03-19 05:22:59 +00004232 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004233 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004234 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4235 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004236 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4237 clang_getTokenLocation(TU,
4238 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Douglas Gregor0396f462010-03-19 05:22:59 +00004240 // A mapping from the source locations found when re-lexing or traversing the
4241 // region of interest to the corresponding cursors.
4242 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004243
4244 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004245 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004246 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4247 std::pair<FileID, unsigned> BeginLocInfo
4248 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4249 std::pair<FileID, unsigned> EndLocInfo
4250 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004251
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004252 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004253 bool Invalid = false;
4254 if (BeginLocInfo.first == EndLocInfo.first &&
4255 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4256 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004257 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4258 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004259 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004260 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004261 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004262
4263 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004264 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004265 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004266 Token Tok;
4267 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004268
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004269 reprocess:
4270 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4271 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004272 // don't see it while preprocessing these tokens later, but keep track
4273 // of all of the token locations inside this preprocessing directive so
4274 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004275 //
4276 // FIXME: Some simple tests here could identify macro definitions and
4277 // #undefs, to provide specific cursor kinds for those.
4278 std::vector<SourceLocation> Locations;
4279 do {
4280 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004281 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004282 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004283
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004284 using namespace cxcursor;
4285 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004286 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4287 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004288 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004289 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4290 Annotated[Locations[I].getRawEncoding()] = Cursor;
4291 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004292
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004293 if (Tok.isAtStartOfLine())
4294 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004295
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004296 continue;
4297 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004298
Douglas Gregor48072312010-03-18 15:23:44 +00004299 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004300 break;
4301 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004302 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004303
Douglas Gregor0396f462010-03-19 05:22:59 +00004304 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004305 // a specific cursor.
4306 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004307 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004308
4309 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004310 // FIXME: We use a ridiculous stack size here because the data-recursion
4311 // algorithm uses a large stack frame than the non-data recursive version,
4312 // and AnnotationTokensWorker currently transforms the data-recursion
4313 // algorithm back into a traditional recursion by explicitly calling
4314 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004315 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004316 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4317 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004318 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4319 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004320}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004321} // end: extern "C"
4322
4323//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004324// Operations for querying linkage of a cursor.
4325//===----------------------------------------------------------------------===//
4326
4327extern "C" {
4328CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004329 if (!clang_isDeclaration(cursor.kind))
4330 return CXLinkage_Invalid;
4331
Ted Kremenek16b42592010-03-03 06:36:57 +00004332 Decl *D = cxcursor::getCursorDecl(cursor);
4333 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4334 switch (ND->getLinkage()) {
4335 case NoLinkage: return CXLinkage_NoLinkage;
4336 case InternalLinkage: return CXLinkage_Internal;
4337 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4338 case ExternalLinkage: return CXLinkage_External;
4339 };
4340
4341 return CXLinkage_Invalid;
4342}
4343} // end: extern "C"
4344
4345//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004346// Operations for querying language of a cursor.
4347//===----------------------------------------------------------------------===//
4348
4349static CXLanguageKind getDeclLanguage(const Decl *D) {
4350 switch (D->getKind()) {
4351 default:
4352 break;
4353 case Decl::ImplicitParam:
4354 case Decl::ObjCAtDefsField:
4355 case Decl::ObjCCategory:
4356 case Decl::ObjCCategoryImpl:
4357 case Decl::ObjCClass:
4358 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004359 case Decl::ObjCForwardProtocol:
4360 case Decl::ObjCImplementation:
4361 case Decl::ObjCInterface:
4362 case Decl::ObjCIvar:
4363 case Decl::ObjCMethod:
4364 case Decl::ObjCProperty:
4365 case Decl::ObjCPropertyImpl:
4366 case Decl::ObjCProtocol:
4367 return CXLanguage_ObjC;
4368 case Decl::CXXConstructor:
4369 case Decl::CXXConversion:
4370 case Decl::CXXDestructor:
4371 case Decl::CXXMethod:
4372 case Decl::CXXRecord:
4373 case Decl::ClassTemplate:
4374 case Decl::ClassTemplatePartialSpecialization:
4375 case Decl::ClassTemplateSpecialization:
4376 case Decl::Friend:
4377 case Decl::FriendTemplate:
4378 case Decl::FunctionTemplate:
4379 case Decl::LinkageSpec:
4380 case Decl::Namespace:
4381 case Decl::NamespaceAlias:
4382 case Decl::NonTypeTemplateParm:
4383 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004384 case Decl::TemplateTemplateParm:
4385 case Decl::TemplateTypeParm:
4386 case Decl::UnresolvedUsingTypename:
4387 case Decl::UnresolvedUsingValue:
4388 case Decl::Using:
4389 case Decl::UsingDirective:
4390 case Decl::UsingShadow:
4391 return CXLanguage_CPlusPlus;
4392 }
4393
4394 return CXLanguage_C;
4395}
4396
4397extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004398
4399enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4400 if (clang_isDeclaration(cursor.kind))
4401 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4402 if (D->hasAttr<UnavailableAttr>() ||
4403 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4404 return CXAvailability_Available;
4405
4406 if (D->hasAttr<DeprecatedAttr>())
4407 return CXAvailability_Deprecated;
4408 }
4409
4410 return CXAvailability_Available;
4411}
4412
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004413CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4414 if (clang_isDeclaration(cursor.kind))
4415 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4416
4417 return CXLanguage_Invalid;
4418}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004419
4420CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4421 if (clang_isDeclaration(cursor.kind)) {
4422 if (Decl *D = getCursorDecl(cursor)) {
4423 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004424 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004425 }
4426 }
4427
4428 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4429 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004430 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004431 }
4432
4433 return clang_getNullCursor();
4434}
4435
4436CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4437 if (clang_isDeclaration(cursor.kind)) {
4438 if (Decl *D = getCursorDecl(cursor)) {
4439 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004440 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004441 }
4442 }
4443
4444 // FIXME: Note that we can't easily compute the lexical context of a
4445 // statement or expression, so we return nothing.
4446 return clang_getNullCursor();
4447}
4448
Douglas Gregor9f592342010-10-01 20:25:15 +00004449static void CollectOverriddenMethods(DeclContext *Ctx,
4450 ObjCMethodDecl *Method,
4451 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4452 if (!Ctx)
4453 return;
4454
4455 // If we have a class or category implementation, jump straight to the
4456 // interface.
4457 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4458 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4459
4460 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4461 if (!Container)
4462 return;
4463
4464 // Check whether we have a matching method at this level.
4465 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4466 Method->isInstanceMethod()))
4467 if (Method != Overridden) {
4468 // We found an override at this level; there is no need to look
4469 // into other protocols or categories.
4470 Methods.push_back(Overridden);
4471 return;
4472 }
4473
4474 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4475 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4476 PEnd = Protocol->protocol_end();
4477 P != PEnd; ++P)
4478 CollectOverriddenMethods(*P, Method, Methods);
4479 }
4480
4481 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4482 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4483 PEnd = Category->protocol_end();
4484 P != PEnd; ++P)
4485 CollectOverriddenMethods(*P, Method, Methods);
4486 }
4487
4488 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4489 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4490 PEnd = Interface->protocol_end();
4491 P != PEnd; ++P)
4492 CollectOverriddenMethods(*P, Method, Methods);
4493
4494 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4495 Category; Category = Category->getNextClassCategory())
4496 CollectOverriddenMethods(Category, Method, Methods);
4497
4498 // We only look into the superclass if we haven't found anything yet.
4499 if (Methods.empty())
4500 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4501 return CollectOverriddenMethods(Super, Method, Methods);
4502 }
4503}
4504
4505void clang_getOverriddenCursors(CXCursor cursor,
4506 CXCursor **overridden,
4507 unsigned *num_overridden) {
4508 if (overridden)
4509 *overridden = 0;
4510 if (num_overridden)
4511 *num_overridden = 0;
4512 if (!overridden || !num_overridden)
4513 return;
4514
4515 if (!clang_isDeclaration(cursor.kind))
4516 return;
4517
4518 Decl *D = getCursorDecl(cursor);
4519 if (!D)
4520 return;
4521
4522 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004523 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004524 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4525 *num_overridden = CXXMethod->size_overridden_methods();
4526 if (!*num_overridden)
4527 return;
4528
4529 *overridden = new CXCursor [*num_overridden];
4530 unsigned I = 0;
4531 for (CXXMethodDecl::method_iterator
4532 M = CXXMethod->begin_overridden_methods(),
4533 MEnd = CXXMethod->end_overridden_methods();
4534 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004535 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004536 return;
4537 }
4538
4539 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4540 if (!Method)
4541 return;
4542
4543 // Handle Objective-C methods.
4544 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4545 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4546
4547 if (Methods.empty())
4548 return;
4549
4550 *num_overridden = Methods.size();
4551 *overridden = new CXCursor [Methods.size()];
4552 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004553 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004554}
4555
4556void clang_disposeOverriddenCursors(CXCursor *overridden) {
4557 delete [] overridden;
4558}
4559
Douglas Gregorecdcb882010-10-20 22:00:55 +00004560CXFile clang_getIncludedFile(CXCursor cursor) {
4561 if (cursor.kind != CXCursor_InclusionDirective)
4562 return 0;
4563
4564 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4565 return (void *)ID->getFile();
4566}
4567
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004568} // end: extern "C"
4569
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004570
4571//===----------------------------------------------------------------------===//
4572// C++ AST instrospection.
4573//===----------------------------------------------------------------------===//
4574
4575extern "C" {
4576unsigned clang_CXXMethod_isStatic(CXCursor C) {
4577 if (!clang_isDeclaration(C.kind))
4578 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004579
4580 CXXMethodDecl *Method = 0;
4581 Decl *D = cxcursor::getCursorDecl(C);
4582 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4583 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4584 else
4585 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4586 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004587}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004588
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004589} // end: extern "C"
4590
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004591//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004592// Attribute introspection.
4593//===----------------------------------------------------------------------===//
4594
4595extern "C" {
4596CXType clang_getIBOutletCollectionType(CXCursor C) {
4597 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004598 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004599
4600 IBOutletCollectionAttr *A =
4601 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4602
Ted Kremeneka60ed472010-11-16 08:15:36 +00004603 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004604}
4605} // end: extern "C"
4606
4607//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004608// Misc. utility functions.
4609//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004610
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004611/// Default to using an 8 MB stack size on "safety" threads.
4612static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004613
4614namespace clang {
4615
4616bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004617 void (*Fn)(void*), void *UserData,
4618 unsigned Size) {
4619 if (!Size)
4620 Size = GetSafetyThreadStackSize();
4621 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004622 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4623 return CRC.RunSafely(Fn, UserData);
4624}
4625
4626unsigned GetSafetyThreadStackSize() {
4627 return SafetyStackThreadSize;
4628}
4629
4630void SetSafetyThreadStackSize(unsigned Value) {
4631 SafetyStackThreadSize = Value;
4632}
4633
4634}
4635
Ted Kremenek04bb7162010-01-22 22:44:15 +00004636extern "C" {
4637
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004638CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004639 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004640}
4641
4642} // end: extern "C"