blob: 23d259761326f2c925edc66e204133a87164bd21 [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 Kremenekae1fd6f2010-11-17 00:50:45 +0000139 DeclRefExprPartsKind, LabelRefVisitKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000140protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000141 void *dataA;
142 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000143 CXCursor parent;
144 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000145 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
146 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147public:
148 Kind getKind() const { return K; }
149 const CXCursor &getParent() const { return parent; }
150 static bool classof(VisitorJob *VJ) { return true; }
151};
152
153typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
154
Douglas Gregorb1373d02010-01-20 20:59:29 +0000155// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000156class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000157 public TypeLocVisitor<CursorVisitor, bool>,
158 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000159{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000160 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000161 CXTranslationUnit TU;
162 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000163
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000164 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000166
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 /// \brief The declaration that serves at the parent of any statement or
168 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000169 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000175 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000177 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
178 // to the visitor. Declarations with a PCH level greater than this value will
179 // be suppressed.
180 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181
182 /// \brief When valid, a source range to which the cursor should restrict
183 /// its search.
184 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000186 // FIXME: Eventually remove. This part of a hack to support proper
187 // iteration over all Decls contained lexically within an ObjC container.
188 DeclContext::decl_iterator *DI_current;
189 DeclContext::decl_iterator DE_current;
190
Ted Kremenekd1ded662010-11-15 23:31:32 +0000191 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
192 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
193 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
194
Douglas Gregorb1373d02010-01-20 20:59:29 +0000195 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000196 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000197 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000198
199 /// \brief Determine whether this particular source range comes before, comes
200 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000201 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000202 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000203 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
204
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000205 class SetParentRAII {
206 CXCursor &Parent;
207 Decl *&StmtParent;
208 CXCursor OldParent;
209
210 public:
211 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
212 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
213 {
214 Parent = NewParent;
215 if (clang_isDeclaration(Parent.kind))
216 StmtParent = getCursorDecl(Parent);
217 }
218
219 ~SetParentRAII() {
220 Parent = OldParent;
221 if (clang_isDeclaration(Parent.kind))
222 StmtParent = getCursorDecl(Parent);
223 }
224 };
225
Steve Naroff89922f82009-08-31 00:59:03 +0000226public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000227 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
228 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000229 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000230 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000231 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
232 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000233 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
234 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000235 {
236 Parent.kind = CXCursor_NoDeclFound;
237 Parent.data[0] = 0;
238 Parent.data[1] = 0;
239 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000240 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242
Ted Kremenekd1ded662010-11-15 23:31:32 +0000243 ~CursorVisitor() {
244 // Free the pre-allocated worklists for data-recursion.
245 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
246 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
247 delete *I;
248 }
249 }
250
Ted Kremeneka60ed472010-11-16 08:15:36 +0000251 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
252 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000253
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000254 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000255
256 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
257 getPreprocessedEntities();
258
Douglas Gregorb1373d02010-01-20 20:59:29 +0000259 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000260
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000261 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000262 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000263 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000264 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000265 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000266 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000267 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
268 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000270 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000271 bool VisitClassTemplatePartialSpecializationDecl(
272 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000273 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000274 bool VisitEnumConstantDecl(EnumConstantDecl *D);
275 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
276 bool VisitFunctionDecl(FunctionDecl *ND);
277 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000278 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000279 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000280 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000281 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000282 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000283 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
284 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
285 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
286 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000287 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
289 bool VisitObjCImplDecl(ObjCImplDecl *D);
290 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
291 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000292 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
293 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
294 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000295 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000296 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000297 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000298 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000299 bool VisitUsingDecl(UsingDecl *D);
300 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
301 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000302
Douglas Gregor01829d32010-08-31 14:41:23 +0000303 // Name visitor
304 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000305 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000306
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000307 // Template visitors
308 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000309 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000310 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
311
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000312 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000313 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000315 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000316 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
317 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000318 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000319 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000320 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
322 bool VisitPointerTypeLoc(PointerTypeLoc TL);
323 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
324 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
325 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
326 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000327 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000329 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000330 // FIXME: Implement visitors here when the unimplemented TypeLocs get
331 // implemented
332 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
333 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000334
Douglas Gregora59e3902010-01-21 23:27:09 +0000335 // Statement visitors
336 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000337
Douglas Gregor336fd812010-01-23 00:40:08 +0000338 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000339 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000340 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000341 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000342 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000343 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000344 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000345 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *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 Gregor3d37c0a2010-09-09 16:14:44 +00001556bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1557 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1558}
1559
Douglas Gregorbfebed22010-09-03 17:24:10 +00001560bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1561 DependentScopeDeclRefExpr *E) {
1562 // Visit the nested-name-specifier.
1563 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1564 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1565 return true;
1566
1567 // Visit the declaration name.
1568 if (VisitDeclarationNameInfo(E->getNameInfo()))
1569 return true;
1570
1571 // Visit the explicitly-specified template arguments.
1572 if (const ExplicitTemplateArgumentList *ArgList
1573 = E->getOptionalExplicitTemplateArgs()) {
1574 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1575 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1576 Arg != ArgEnd; ++Arg) {
1577 if (VisitTemplateArgumentLoc(*Arg))
1578 return true;
1579 }
1580 }
1581
1582 return false;
1583}
1584
Douglas Gregor25d63622010-09-03 17:35:34 +00001585bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1586 CXXDependentScopeMemberExpr *E) {
1587 // Visit the base expression, if there is one.
1588 if (!E->isImplicitAccess() &&
1589 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1590 return true;
1591
1592 // Visit the nested-name-specifier.
1593 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1594 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1595 return true;
1596
1597 // Visit the declaration name.
1598 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1599 return true;
1600
1601 // Visit the explicitly-specified template arguments.
1602 if (const ExplicitTemplateArgumentList *ArgList
1603 = E->getOptionalExplicitTemplateArgs()) {
1604 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1605 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1606 Arg != ArgEnd; ++Arg) {
1607 if (VisitTemplateArgumentLoc(*Arg))
1608 return true;
1609 }
1610 }
1611
1612 return false;
1613}
1614
Ted Kremenek09dfa372010-02-18 05:46:33 +00001615bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001616 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1617 i != e; ++i)
1618 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001619 return true;
1620
1621 return false;
1622}
1623
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001624//===----------------------------------------------------------------------===//
1625// Data-recursive visitor methods.
1626//===----------------------------------------------------------------------===//
1627
Ted Kremenek28a71942010-11-13 00:36:47 +00001628namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001629#define DEF_JOB(NAME, DATA, KIND)\
1630class NAME : public VisitorJob {\
1631public:\
1632 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1633 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1634 DATA *get() const { return static_cast<DATA*>(dataA); }\
1635};
1636
1637DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1638DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001639DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001640DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1641#undef DEF_JOB
1642
1643class DeclVisit : public VisitorJob {
1644public:
1645 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1646 VisitorJob(parent, VisitorJob::DeclVisitKind,
1647 d, isFirst ? (void*) 1 : (void*) 0) {}
1648 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001649 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001650 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001651 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001652 bool isFirst() const { return dataB ? true : false; }
1653};
1654
1655class TypeLocVisit : public VisitorJob {
1656public:
1657 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1658 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1659 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1660
1661 static bool classof(const VisitorJob *VJ) {
1662 return VJ->getKind() == TypeLocVisitKind;
1663 }
1664
Ted Kremenek82f3c502010-11-15 22:23:26 +00001665 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001666 QualType T = QualType::getFromOpaquePtr(dataA);
1667 return TypeLoc(T, dataB);
1668 }
1669};
1670
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001671class LabelRefVisit : public VisitorJob {
1672public:
1673 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1674 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1675 (void*) labelLoc.getRawEncoding()) {}
1676
1677 static bool classof(const VisitorJob *VJ) {
1678 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1679 }
1680 LabelStmt *get() const { return static_cast<LabelStmt*>(dataA); }
1681 SourceLocation getLoc() const {
1682 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) dataB); }
1683};
1684
Ted Kremenek28a71942010-11-13 00:36:47 +00001685class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1686 VisitorWorkList &WL;
1687 CXCursor Parent;
1688public:
1689 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1690 : WL(wl), Parent(parent) {}
1691
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001692 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001693 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001694 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001695 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001696 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1697 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001698 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001699 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001700 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001701 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001702 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001703 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1705 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001706 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001707 void VisitIfStmt(IfStmt *If);
1708 void VisitInitListExpr(InitListExpr *IE);
1709 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001710 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001711 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1712 void VisitOverloadExpr(OverloadExpr *E);
1713 void VisitStmt(Stmt *S);
1714 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001715 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001716 void VisitWhileStmt(WhileStmt *W);
1717 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001718 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001719
1720private:
1721 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001722 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001723 void AddTypeLoc(TypeSourceInfo *TI);
1724 void EnqueueChildren(Stmt *S);
1725};
1726} // end anonyous namespace
1727
1728void EnqueueVisitor::AddStmt(Stmt *S) {
1729 if (S)
1730 WL.push_back(StmtVisit(S, Parent));
1731}
Ted Kremenek035dc412010-11-13 00:36:50 +00001732void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001733 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001734 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001735}
1736void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1737 if (TI)
1738 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1739 }
1740void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001741 unsigned size = WL.size();
1742 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1743 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001744 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001745 }
1746 if (size == WL.size())
1747 return;
1748 // Now reverse the entries we just added. This will match the DFS
1749 // ordering performed by the worklist.
1750 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1751 std::reverse(I, E);
1752}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001753void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1754 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1755}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001756void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1757 AddDecl(B->getBlockDecl());
1758}
Ted Kremenek28a71942010-11-13 00:36:47 +00001759void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1760 EnqueueChildren(E);
1761 AddTypeLoc(E->getTypeSourceInfo());
1762}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001763void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1764 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1765 E = S->body_rend(); I != E; ++I) {
1766 AddStmt(*I);
1767 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001768}
1769void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1770 // Enqueue the initializer or constructor arguments.
1771 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1772 AddStmt(E->getConstructorArg(I-1));
1773 // Enqueue the array size, if any.
1774 AddStmt(E->getArraySize());
1775 // Enqueue the allocated type.
1776 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1777 // Enqueue the placement arguments.
1778 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1779 AddStmt(E->getPlacementArg(I-1));
1780}
Ted Kremenek28a71942010-11-13 00:36:47 +00001781void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001782 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1783 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001784 AddStmt(CE->getCallee());
1785 AddStmt(CE->getArg(0));
1786}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001787void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1788 EnqueueChildren(E);
1789 AddTypeLoc(E->getTypeSourceInfo());
1790}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001791void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1792 EnqueueChildren(E);
1793 if (E->isTypeOperand())
1794 AddTypeLoc(E->getTypeOperandSourceInfo());
1795}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001796
1797void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1798 *E) {
1799 EnqueueChildren(E);
1800 AddTypeLoc(E->getTypeSourceInfo());
1801}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001802void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1803 WL.push_back(DeclRefExprParts(DR, Parent));
1804}
Ted Kremenek035dc412010-11-13 00:36:50 +00001805void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1806 unsigned size = WL.size();
1807 bool isFirst = true;
1808 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1809 D != DEnd; ++D) {
1810 AddDecl(*D, isFirst);
1811 isFirst = false;
1812 }
1813 if (size == WL.size())
1814 return;
1815 // Now reverse the entries we just added. This will match the DFS
1816 // ordering performed by the worklist.
1817 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1818 std::reverse(I, E);
1819}
Ted Kremenek28a71942010-11-13 00:36:47 +00001820void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1821 EnqueueChildren(E);
1822 AddTypeLoc(E->getTypeInfoAsWritten());
1823}
1824void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1825 AddStmt(FS->getBody());
1826 AddStmt(FS->getInc());
1827 AddStmt(FS->getCond());
1828 AddDecl(FS->getConditionVariable());
1829 AddStmt(FS->getInit());
1830}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001831void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1832 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1833}
Ted Kremenek28a71942010-11-13 00:36:47 +00001834void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1835 AddStmt(If->getElse());
1836 AddStmt(If->getThen());
1837 AddStmt(If->getCond());
1838 AddDecl(If->getConditionVariable());
1839}
1840void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1841 // We care about the syntactic form of the initializer list, only.
1842 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1843 IE = Syntactic;
1844 EnqueueChildren(IE);
1845}
1846void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1847 WL.push_back(MemberExprParts(M, Parent));
1848 AddStmt(M->getBase());
1849}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001850void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1851 AddTypeLoc(E->getEncodedTypeSourceInfo());
1852}
Ted Kremenek28a71942010-11-13 00:36:47 +00001853void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1854 EnqueueChildren(M);
1855 AddTypeLoc(M->getClassReceiverTypeInfo());
1856}
1857void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001858 WL.push_back(OverloadExprParts(E, Parent));
1859}
Ted Kremenek28a71942010-11-13 00:36:47 +00001860void EnqueueVisitor::VisitStmt(Stmt *S) {
1861 EnqueueChildren(S);
1862}
1863void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1864 AddStmt(S->getBody());
1865 AddStmt(S->getCond());
1866 AddDecl(S->getConditionVariable());
1867}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001868void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1869 AddTypeLoc(E->getArgTInfo2());
1870 AddTypeLoc(E->getArgTInfo1());
1871}
1872
Ted Kremenek28a71942010-11-13 00:36:47 +00001873void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1874 AddStmt(W->getBody());
1875 AddStmt(W->getCond());
1876 AddDecl(W->getConditionVariable());
1877}
1878void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1879 VisitOverloadExpr(U);
1880 if (!U->isImplicitAccess())
1881 AddStmt(U->getBase());
1882}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001883void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1884 AddStmt(E->getSubExpr());
1885 AddTypeLoc(E->getWrittenTypeInfo());
1886}
Ted Kremenek60458782010-11-12 21:34:16 +00001887
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001888void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001889 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001890}
1891
1892bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1893 if (RegionOfInterest.isValid()) {
1894 SourceRange Range = getRawCursorExtent(C);
1895 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1896 return false;
1897 }
1898 return true;
1899}
1900
1901bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1902 while (!WL.empty()) {
1903 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001904 VisitorJob LI = WL.back();
1905 WL.pop_back();
1906
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001907 // Set the Parent field, then back to its old value once we're done.
1908 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1909
1910 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001911 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001912 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001913 if (!D)
1914 continue;
1915
1916 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001917 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001918 return true;
1919
1920 continue;
1921 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001922 case VisitorJob::TypeLocVisitKind: {
1923 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001924 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001925 return true;
1926 continue;
1927 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001928 case VisitorJob::LabelRefVisitKind: {
1929 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1930 if (Visit(MakeCursorLabelRef(LS,
1931 cast<LabelRefVisit>(&LI)->getLoc(),
1932 TU)))
1933 return true;
1934 continue;
1935 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001936 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001937 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001938 if (!S)
1939 continue;
1940
Ted Kremenekf1107452010-11-12 18:26:56 +00001941 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001942 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1943
1944 switch (S->getStmtClass()) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001945 // Cases not yet handled by the data-recursion
1946 // algorithm.
1947 case Stmt::OffsetOfExprClass:
1948 case Stmt::SizeOfAlignOfExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001949 case Stmt::DesignatedInitExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001950 case Stmt::CXXUuidofExprClass:
1951 case Stmt::CXXScalarValueInitExprClass:
1952 case Stmt::CXXPseudoDestructorExprClass:
1953 case Stmt::UnaryTypeTraitExprClass:
1954 case Stmt::DependentScopeDeclRefExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001955 case Stmt::CXXDependentScopeMemberExprClass:
1956 if (Visit(Cursor))
1957 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001958 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001959 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001960 if (!IsInRegionOfInterest(Cursor))
1961 continue;
1962 switch (Visitor(Cursor, Parent, ClientData)) {
1963 case CXChildVisit_Break:
1964 return true;
1965 case CXChildVisit_Continue:
1966 break;
1967 case CXChildVisit_Recurse:
1968 EnqueueWorkList(WL, S);
1969 break;
1970 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001971 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001972 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001973 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001974 }
1975 case VisitorJob::MemberExprPartsKind: {
1976 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001977 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001978
1979 // Visit the nested-name-specifier
1980 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1981 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1982 return true;
1983
1984 // Visit the declaration name.
1985 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1986 return true;
1987
1988 // Visit the explicitly-specified template arguments, if any.
1989 if (M->hasExplicitTemplateArgs()) {
1990 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1991 *ArgEnd = Arg + M->getNumTemplateArgs();
1992 Arg != ArgEnd; ++Arg) {
1993 if (VisitTemplateArgumentLoc(*Arg))
1994 return true;
1995 }
1996 }
1997 continue;
1998 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001999 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002000 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002001 // Visit nested-name-specifier, if present.
2002 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2003 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2004 return true;
2005 // Visit declaration name.
2006 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2007 return true;
2008 // Visit explicitly-specified template arguments.
2009 if (DR->hasExplicitTemplateArgs()) {
2010 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2011 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2012 *ArgEnd = Arg + Args.NumTemplateArgs;
2013 Arg != ArgEnd; ++Arg)
2014 if (VisitTemplateArgumentLoc(*Arg))
2015 return true;
2016 }
2017 continue;
2018 }
Ted Kremenek60458782010-11-12 21:34:16 +00002019 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002020 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002021 // Visit the nested-name-specifier.
2022 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2023 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2024 return true;
2025 // Visit the declaration name.
2026 if (VisitDeclarationNameInfo(O->getNameInfo()))
2027 return true;
2028 // Visit the overloaded declaration reference.
2029 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2030 return true;
2031 // Visit the explicitly-specified template arguments.
2032 if (const ExplicitTemplateArgumentList *ArgList
2033 = O->getOptionalExplicitTemplateArgs()) {
2034 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2035 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2036 Arg != ArgEnd; ++Arg) {
2037 if (VisitTemplateArgumentLoc(*Arg))
2038 return true;
2039 }
2040 }
2041 continue;
2042 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002043 }
2044 }
2045 return false;
2046}
2047
2048bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002049 VisitorWorkList *WL = 0;
2050 if (!WorkListFreeList.empty()) {
2051 WL = WorkListFreeList.back();
2052 WL->clear();
2053 WorkListFreeList.pop_back();
2054 }
2055 else {
2056 WL = new VisitorWorkList();
2057 WorkListCache.push_back(WL);
2058 }
2059 EnqueueWorkList(*WL, S);
2060 bool result = RunVisitorWorkList(*WL);
2061 WorkListFreeList.push_back(WL);
2062 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002063}
2064
2065//===----------------------------------------------------------------------===//
2066// Misc. API hooks.
2067//===----------------------------------------------------------------------===//
2068
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002069static llvm::sys::Mutex EnableMultithreadingMutex;
2070static bool EnabledMultithreading;
2071
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002072extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002073CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2074 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002075 // Disable pretty stack trace functionality, which will otherwise be a very
2076 // poor citizen of the world and set up all sorts of signal handlers.
2077 llvm::DisablePrettyStackTrace = true;
2078
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002079 // We use crash recovery to make some of our APIs more reliable, implicitly
2080 // enable it.
2081 llvm::CrashRecoveryContext::Enable();
2082
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002083 // Enable support for multithreading in LLVM.
2084 {
2085 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2086 if (!EnabledMultithreading) {
2087 llvm::llvm_start_multithreaded();
2088 EnabledMultithreading = true;
2089 }
2090 }
2091
Douglas Gregora030b7c2010-01-22 20:35:53 +00002092 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002093 if (excludeDeclarationsFromPCH)
2094 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002095 if (displayDiagnostics)
2096 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002097 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002098}
2099
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002100void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002101 if (CIdx)
2102 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002103}
2104
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002105CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002106 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002107 if (!CIdx)
2108 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002109
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002110 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002111 FileSystemOptions FileSystemOpts;
2112 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002113
Douglas Gregor28019772010-04-05 23:52:57 +00002114 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002115 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002116 CXXIdx->getOnlyLocalDecls(),
2117 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002118 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002119}
2120
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002121unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002122 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002123 CXTranslationUnit_CacheCompletionResults |
2124 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002125}
2126
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002127CXTranslationUnit
2128clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2129 const char *source_filename,
2130 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002131 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002132 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002133 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002134 return clang_parseTranslationUnit(CIdx, source_filename,
2135 command_line_args, num_command_line_args,
2136 unsaved_files, num_unsaved_files,
2137 CXTranslationUnit_DetailedPreprocessingRecord);
2138}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002139
2140struct ParseTranslationUnitInfo {
2141 CXIndex CIdx;
2142 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002143 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002144 int num_command_line_args;
2145 struct CXUnsavedFile *unsaved_files;
2146 unsigned num_unsaved_files;
2147 unsigned options;
2148 CXTranslationUnit result;
2149};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002150static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002151 ParseTranslationUnitInfo *PTUI =
2152 static_cast<ParseTranslationUnitInfo*>(UserData);
2153 CXIndex CIdx = PTUI->CIdx;
2154 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002155 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002156 int num_command_line_args = PTUI->num_command_line_args;
2157 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2158 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2159 unsigned options = PTUI->options;
2160 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002161
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002162 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002163 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002164
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002165 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2166
Douglas Gregor44c181a2010-07-23 00:33:23 +00002167 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002168 bool CompleteTranslationUnit
2169 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002170 bool CacheCodeCompetionResults
2171 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002172 bool CXXPrecompilePreamble
2173 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2174 bool CXXChainedPCH
2175 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002176
Douglas Gregor5352ac02010-01-28 00:27:43 +00002177 // Configure the diagnostics.
2178 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002179 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2180 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002181
Douglas Gregor4db64a42010-01-23 00:14:00 +00002182 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2183 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002184 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002185 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002186 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002187 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2188 Buffer));
2189 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002190
Douglas Gregorb10daed2010-10-11 16:52:23 +00002191 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002192
Ted Kremenek139ba862009-10-22 00:03:57 +00002193 // The 'source_filename' argument is optional. If the caller does not
2194 // specify it then it is assumed that the source file is specified
2195 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002196 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002197 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002198
2199 // Since the Clang C library is primarily used by batch tools dealing with
2200 // (often very broken) source code, where spell-checking can have a
2201 // significant negative impact on performance (particularly when
2202 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002203 // Only do this if we haven't found a spell-checking-related argument.
2204 bool FoundSpellCheckingArgument = false;
2205 for (int I = 0; I != num_command_line_args; ++I) {
2206 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2207 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2208 FoundSpellCheckingArgument = true;
2209 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002210 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002211 }
2212 if (!FoundSpellCheckingArgument)
2213 Args.push_back("-fno-spell-checking");
2214
2215 Args.insert(Args.end(), command_line_args,
2216 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002217
Douglas Gregor44c181a2010-07-23 00:33:23 +00002218 // Do we need the detailed preprocessing record?
2219 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002220 Args.push_back("-Xclang");
2221 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002222 }
2223
Douglas Gregorb10daed2010-10-11 16:52:23 +00002224 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002225 llvm::OwningPtr<ASTUnit> Unit(
2226 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2227 Diags,
2228 CXXIdx->getClangResourcesPath(),
2229 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002230 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002231 RemappedFiles.data(),
2232 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002233 PrecompilePreamble,
2234 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002235 CacheCodeCompetionResults,
2236 CXXPrecompilePreamble,
2237 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002238
Douglas Gregorb10daed2010-10-11 16:52:23 +00002239 if (NumErrors != Diags->getNumErrors()) {
2240 // Make sure to check that 'Unit' is non-NULL.
2241 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2242 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2243 DEnd = Unit->stored_diag_end();
2244 D != DEnd; ++D) {
2245 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2246 CXString Msg = clang_formatDiagnostic(&Diag,
2247 clang_defaultDiagnosticDisplayOptions());
2248 fprintf(stderr, "%s\n", clang_getCString(Msg));
2249 clang_disposeString(Msg);
2250 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002251#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002252 // On Windows, force a flush, since there may be multiple copies of
2253 // stderr and stdout in the file system, all with different buffers
2254 // but writing to the same device.
2255 fflush(stderr);
2256#endif
2257 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002258 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002259
Ted Kremeneka60ed472010-11-16 08:15:36 +00002260 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002261}
2262CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2263 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002264 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002265 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002266 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002267 unsigned num_unsaved_files,
2268 unsigned options) {
2269 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002270 num_command_line_args, unsaved_files,
2271 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002272 llvm::CrashRecoveryContext CRC;
2273
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002274 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002275 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2276 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2277 fprintf(stderr, " 'command_line_args' : [");
2278 for (int i = 0; i != num_command_line_args; ++i) {
2279 if (i)
2280 fprintf(stderr, ", ");
2281 fprintf(stderr, "'%s'", command_line_args[i]);
2282 }
2283 fprintf(stderr, "],\n");
2284 fprintf(stderr, " 'unsaved_files' : [");
2285 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2286 if (i)
2287 fprintf(stderr, ", ");
2288 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2289 unsaved_files[i].Length);
2290 }
2291 fprintf(stderr, "],\n");
2292 fprintf(stderr, " 'options' : %d,\n", options);
2293 fprintf(stderr, "}\n");
2294
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002295 return 0;
2296 }
2297
2298 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002299}
2300
Douglas Gregor19998442010-08-13 15:35:05 +00002301unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2302 return CXSaveTranslationUnit_None;
2303}
2304
2305int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2306 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002307 if (!TU)
2308 return 1;
2309
Ted Kremeneka60ed472010-11-16 08:15:36 +00002310 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002311}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002312
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002313void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002314 if (CTUnit) {
2315 // If the translation unit has been marked as unsafe to free, just discard
2316 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002317 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002318 return;
2319
Ted Kremeneka60ed472010-11-16 08:15:36 +00002320 delete static_cast<ASTUnit *>(CTUnit->TUData);
2321 disposeCXStringPool(CTUnit->StringPool);
2322 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002323 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002324}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002325
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002326unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2327 return CXReparse_None;
2328}
2329
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002330struct ReparseTranslationUnitInfo {
2331 CXTranslationUnit TU;
2332 unsigned num_unsaved_files;
2333 struct CXUnsavedFile *unsaved_files;
2334 unsigned options;
2335 int result;
2336};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002337
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002338static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002339 ReparseTranslationUnitInfo *RTUI =
2340 static_cast<ReparseTranslationUnitInfo*>(UserData);
2341 CXTranslationUnit TU = RTUI->TU;
2342 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2343 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2344 unsigned options = RTUI->options;
2345 (void) options;
2346 RTUI->result = 1;
2347
Douglas Gregorabc563f2010-07-19 21:46:24 +00002348 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002349 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002350
Ted Kremeneka60ed472010-11-16 08:15:36 +00002351 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002352 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002353
2354 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2355 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2356 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2357 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002358 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002359 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2360 Buffer));
2361 }
2362
Douglas Gregor593b0c12010-09-23 18:47:53 +00002363 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2364 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002365}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002366
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002367int clang_reparseTranslationUnit(CXTranslationUnit TU,
2368 unsigned num_unsaved_files,
2369 struct CXUnsavedFile *unsaved_files,
2370 unsigned options) {
2371 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2372 options, 0 };
2373 llvm::CrashRecoveryContext CRC;
2374
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002375 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002376 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002377 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002378 return 1;
2379 }
2380
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002381
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002382 return RTUI.result;
2383}
2384
Douglas Gregordf95a132010-08-09 20:45:32 +00002385
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002386CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002387 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002388 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002389
Ted Kremeneka60ed472010-11-16 08:15:36 +00002390 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002391 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002392}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002393
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002394CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002395 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002396 return Result;
2397}
2398
Ted Kremenekfb480492010-01-13 21:46:36 +00002399} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002400
Ted Kremenekfb480492010-01-13 21:46:36 +00002401//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002402// CXSourceLocation and CXSourceRange Operations.
2403//===----------------------------------------------------------------------===//
2404
Douglas Gregorb9790342010-01-22 21:44:22 +00002405extern "C" {
2406CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002407 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002408 return Result;
2409}
2410
2411unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002412 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2413 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2414 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002415}
2416
2417CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2418 CXFile file,
2419 unsigned line,
2420 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002421 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002422 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002423
Ted Kremeneka60ed472010-11-16 08:15:36 +00002424 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002425 SourceLocation SLoc
2426 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002428 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002429 if (SLoc.isInvalid()) return clang_getNullLocation();
2430
2431 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2432}
2433
2434CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2435 CXFile file,
2436 unsigned offset) {
2437 if (!tu || !file)
2438 return clang_getNullLocation();
2439
Ted Kremeneka60ed472010-11-16 08:15:36 +00002440 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002441 SourceLocation Start
2442 = CXXUnit->getSourceManager().getLocation(
2443 static_cast<const FileEntry *>(file),
2444 1, 1);
2445 if (Start.isInvalid()) return clang_getNullLocation();
2446
2447 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2448
2449 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002450
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002451 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002452}
2453
Douglas Gregor5352ac02010-01-28 00:27:43 +00002454CXSourceRange clang_getNullRange() {
2455 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2456 return Result;
2457}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002458
Douglas Gregor5352ac02010-01-28 00:27:43 +00002459CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2460 if (begin.ptr_data[0] != end.ptr_data[0] ||
2461 begin.ptr_data[1] != end.ptr_data[1])
2462 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002463
2464 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002465 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002466 return Result;
2467}
2468
Douglas Gregor46766dc2010-01-26 19:19:08 +00002469void clang_getInstantiationLocation(CXSourceLocation location,
2470 CXFile *file,
2471 unsigned *line,
2472 unsigned *column,
2473 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002474 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2475
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002476 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002477 if (file)
2478 *file = 0;
2479 if (line)
2480 *line = 0;
2481 if (column)
2482 *column = 0;
2483 if (offset)
2484 *offset = 0;
2485 return;
2486 }
2487
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002488 const SourceManager &SM =
2489 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002490 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002491
2492 if (file)
2493 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2494 if (line)
2495 *line = SM.getInstantiationLineNumber(InstLoc);
2496 if (column)
2497 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002498 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002499 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002500}
2501
Douglas Gregora9b06d42010-11-09 06:24:54 +00002502void clang_getSpellingLocation(CXSourceLocation location,
2503 CXFile *file,
2504 unsigned *line,
2505 unsigned *column,
2506 unsigned *offset) {
2507 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2508
2509 if (!location.ptr_data[0] || Loc.isInvalid()) {
2510 if (file)
2511 *file = 0;
2512 if (line)
2513 *line = 0;
2514 if (column)
2515 *column = 0;
2516 if (offset)
2517 *offset = 0;
2518 return;
2519 }
2520
2521 const SourceManager &SM =
2522 *static_cast<const SourceManager*>(location.ptr_data[0]);
2523 SourceLocation SpellLoc = Loc;
2524 if (SpellLoc.isMacroID()) {
2525 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2526 if (SimpleSpellingLoc.isFileID() &&
2527 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2528 SpellLoc = SimpleSpellingLoc;
2529 else
2530 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2531 }
2532
2533 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2534 FileID FID = LocInfo.first;
2535 unsigned FileOffset = LocInfo.second;
2536
2537 if (file)
2538 *file = (void *)SM.getFileEntryForID(FID);
2539 if (line)
2540 *line = SM.getLineNumber(FID, FileOffset);
2541 if (column)
2542 *column = SM.getColumnNumber(FID, FileOffset);
2543 if (offset)
2544 *offset = FileOffset;
2545}
2546
Douglas Gregor1db19de2010-01-19 21:36:55 +00002547CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002548 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002549 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002550 return Result;
2551}
2552
2553CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002554 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002555 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002556 return Result;
2557}
2558
Douglas Gregorb9790342010-01-22 21:44:22 +00002559} // end: extern "C"
2560
Douglas Gregor1db19de2010-01-19 21:36:55 +00002561//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002562// CXFile Operations.
2563//===----------------------------------------------------------------------===//
2564
2565extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002566CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002567 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002568 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Steve Naroff88145032009-10-27 14:35:18 +00002570 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002571 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002572}
2573
2574time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002575 if (!SFile)
2576 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002577
Steve Naroff88145032009-10-27 14:35:18 +00002578 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2579 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002580}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Douglas Gregorb9790342010-01-22 21:44:22 +00002582CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2583 if (!tu)
2584 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Ted Kremeneka60ed472010-11-16 08:15:36 +00002586 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002587
Douglas Gregorb9790342010-01-22 21:44:22 +00002588 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002589 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2590 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002591 return const_cast<FileEntry *>(File);
2592}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002593
Ted Kremenekfb480492010-01-13 21:46:36 +00002594} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002595
Ted Kremenekfb480492010-01-13 21:46:36 +00002596//===----------------------------------------------------------------------===//
2597// CXCursor Operations.
2598//===----------------------------------------------------------------------===//
2599
Ted Kremenekfb480492010-01-13 21:46:36 +00002600static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002601 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2602 return getDeclFromExpr(CE->getSubExpr());
2603
Ted Kremenekfb480492010-01-13 21:46:36 +00002604 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2605 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002606 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2607 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002608 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2609 return ME->getMemberDecl();
2610 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2611 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002612 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2613 return PRE->getProperty();
2614
Ted Kremenekfb480492010-01-13 21:46:36 +00002615 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2616 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002617 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2618 if (!CE->isElidable())
2619 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002620 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2621 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002622
Douglas Gregordb1314e2010-10-01 21:11:22 +00002623 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2624 return PE->getProtocol();
2625
Ted Kremenekfb480492010-01-13 21:46:36 +00002626 return 0;
2627}
2628
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002629static SourceLocation getLocationFromExpr(Expr *E) {
2630 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2631 return /*FIXME:*/Msg->getLeftLoc();
2632 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2633 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002634 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2635 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002636 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2637 return Member->getMemberLoc();
2638 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2639 return Ivar->getLocation();
2640 return E->getLocStart();
2641}
2642
Ted Kremenekfb480492010-01-13 21:46:36 +00002643extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002644
2645unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002646 CXCursorVisitor visitor,
2647 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002648 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2649 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002650 return CursorVis.VisitChildren(parent);
2651}
2652
David Chisnall3387c652010-11-03 14:12:26 +00002653#ifndef __has_feature
2654#define __has_feature(x) 0
2655#endif
2656#if __has_feature(blocks)
2657typedef enum CXChildVisitResult
2658 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2659
2660static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2661 CXClientData client_data) {
2662 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2663 return block(cursor, parent);
2664}
2665#else
2666// If we are compiled with a compiler that doesn't have native blocks support,
2667// define and call the block manually, so the
2668typedef struct _CXChildVisitResult
2669{
2670 void *isa;
2671 int flags;
2672 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002673 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2674 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002675} *CXCursorVisitorBlock;
2676
2677static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2678 CXClientData client_data) {
2679 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2680 return block->invoke(block, cursor, parent);
2681}
2682#endif
2683
2684
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002685unsigned clang_visitChildrenWithBlock(CXCursor parent,
2686 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002687 return clang_visitChildren(parent, visitWithBlock, block);
2688}
2689
Douglas Gregor78205d42010-01-20 21:45:58 +00002690static CXString getDeclSpelling(Decl *D) {
2691 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002692 if (!ND) {
2693 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2694 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2695 return createCXString(Property->getIdentifier()->getName());
2696
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002697 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002698 }
2699
Douglas Gregor78205d42010-01-20 21:45:58 +00002700 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002701 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002702
Douglas Gregor78205d42010-01-20 21:45:58 +00002703 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2704 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2705 // and returns different names. NamedDecl returns the class name and
2706 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002707 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002708
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002709 if (isa<UsingDirectiveDecl>(D))
2710 return createCXString("");
2711
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002712 llvm::SmallString<1024> S;
2713 llvm::raw_svector_ostream os(S);
2714 ND->printName(os);
2715
2716 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002717}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002718
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002719CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002720 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002721 return clang_getTranslationUnitSpelling(
2722 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002723
Steve Narofff334b4e2009-09-02 18:26:48 +00002724 if (clang_isReference(C.kind)) {
2725 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002726 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002727 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002728 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002729 }
2730 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002731 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002732 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002733 }
2734 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002735 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002736 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002737 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002738 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002739 case CXCursor_CXXBaseSpecifier: {
2740 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2741 return createCXString(B->getType().getAsString());
2742 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002743 case CXCursor_TypeRef: {
2744 TypeDecl *Type = getCursorTypeRef(C).first;
2745 assert(Type && "Missing type decl");
2746
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002747 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2748 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002749 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002750 case CXCursor_TemplateRef: {
2751 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002752 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002753
2754 return createCXString(Template->getNameAsString());
2755 }
Douglas Gregor69319002010-08-31 23:48:11 +00002756
2757 case CXCursor_NamespaceRef: {
2758 NamedDecl *NS = getCursorNamespaceRef(C).first;
2759 assert(NS && "Missing namespace decl");
2760
2761 return createCXString(NS->getNameAsString());
2762 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002763
Douglas Gregora67e03f2010-09-09 21:42:20 +00002764 case CXCursor_MemberRef: {
2765 FieldDecl *Field = getCursorMemberRef(C).first;
2766 assert(Field && "Missing member decl");
2767
2768 return createCXString(Field->getNameAsString());
2769 }
2770
Douglas Gregor36897b02010-09-10 00:22:18 +00002771 case CXCursor_LabelRef: {
2772 LabelStmt *Label = getCursorLabelRef(C).first;
2773 assert(Label && "Missing label");
2774
2775 return createCXString(Label->getID()->getName());
2776 }
2777
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002778 case CXCursor_OverloadedDeclRef: {
2779 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2780 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2781 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2782 return createCXString(ND->getNameAsString());
2783 return createCXString("");
2784 }
2785 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2786 return createCXString(E->getName().getAsString());
2787 OverloadedTemplateStorage *Ovl
2788 = Storage.get<OverloadedTemplateStorage*>();
2789 if (Ovl->size() == 0)
2790 return createCXString("");
2791 return createCXString((*Ovl->begin())->getNameAsString());
2792 }
2793
Daniel Dunbaracca7252009-11-30 20:42:49 +00002794 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002795 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002796 }
2797 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002798
2799 if (clang_isExpression(C.kind)) {
2800 Decl *D = getDeclFromExpr(getCursorExpr(C));
2801 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002802 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002803 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002804 }
2805
Douglas Gregor36897b02010-09-10 00:22:18 +00002806 if (clang_isStatement(C.kind)) {
2807 Stmt *S = getCursorStmt(C);
2808 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2809 return createCXString(Label->getID()->getName());
2810
2811 return createCXString("");
2812 }
2813
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002814 if (C.kind == CXCursor_MacroInstantiation)
2815 return createCXString(getCursorMacroInstantiation(C)->getName()
2816 ->getNameStart());
2817
Douglas Gregor572feb22010-03-18 18:04:21 +00002818 if (C.kind == CXCursor_MacroDefinition)
2819 return createCXString(getCursorMacroDefinition(C)->getName()
2820 ->getNameStart());
2821
Douglas Gregorecdcb882010-10-20 22:00:55 +00002822 if (C.kind == CXCursor_InclusionDirective)
2823 return createCXString(getCursorInclusionDirective(C)->getFileName());
2824
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002825 if (clang_isDeclaration(C.kind))
2826 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002827
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002828 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002829}
2830
Douglas Gregor358559d2010-10-02 22:49:11 +00002831CXString clang_getCursorDisplayName(CXCursor C) {
2832 if (!clang_isDeclaration(C.kind))
2833 return clang_getCursorSpelling(C);
2834
2835 Decl *D = getCursorDecl(C);
2836 if (!D)
2837 return createCXString("");
2838
2839 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2840 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2841 D = FunTmpl->getTemplatedDecl();
2842
2843 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2844 llvm::SmallString<64> Str;
2845 llvm::raw_svector_ostream OS(Str);
2846 OS << Function->getNameAsString();
2847 if (Function->getPrimaryTemplate())
2848 OS << "<>";
2849 OS << "(";
2850 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2851 if (I)
2852 OS << ", ";
2853 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2854 }
2855
2856 if (Function->isVariadic()) {
2857 if (Function->getNumParams())
2858 OS << ", ";
2859 OS << "...";
2860 }
2861 OS << ")";
2862 return createCXString(OS.str());
2863 }
2864
2865 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2866 llvm::SmallString<64> Str;
2867 llvm::raw_svector_ostream OS(Str);
2868 OS << ClassTemplate->getNameAsString();
2869 OS << "<";
2870 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2871 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2872 if (I)
2873 OS << ", ";
2874
2875 NamedDecl *Param = Params->getParam(I);
2876 if (Param->getIdentifier()) {
2877 OS << Param->getIdentifier()->getName();
2878 continue;
2879 }
2880
2881 // There is no parameter name, which makes this tricky. Try to come up
2882 // with something useful that isn't too long.
2883 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2884 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2885 else if (NonTypeTemplateParmDecl *NTTP
2886 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2887 OS << NTTP->getType().getAsString(Policy);
2888 else
2889 OS << "template<...> class";
2890 }
2891
2892 OS << ">";
2893 return createCXString(OS.str());
2894 }
2895
2896 if (ClassTemplateSpecializationDecl *ClassSpec
2897 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2898 // If the type was explicitly written, use that.
2899 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2900 return createCXString(TSInfo->getType().getAsString(Policy));
2901
2902 llvm::SmallString<64> Str;
2903 llvm::raw_svector_ostream OS(Str);
2904 OS << ClassSpec->getNameAsString();
2905 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002906 ClassSpec->getTemplateArgs().data(),
2907 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002908 Policy);
2909 return createCXString(OS.str());
2910 }
2911
2912 return clang_getCursorSpelling(C);
2913}
2914
Ted Kremeneke68fff62010-02-17 00:41:32 +00002915CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002916 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002917 case CXCursor_FunctionDecl:
2918 return createCXString("FunctionDecl");
2919 case CXCursor_TypedefDecl:
2920 return createCXString("TypedefDecl");
2921 case CXCursor_EnumDecl:
2922 return createCXString("EnumDecl");
2923 case CXCursor_EnumConstantDecl:
2924 return createCXString("EnumConstantDecl");
2925 case CXCursor_StructDecl:
2926 return createCXString("StructDecl");
2927 case CXCursor_UnionDecl:
2928 return createCXString("UnionDecl");
2929 case CXCursor_ClassDecl:
2930 return createCXString("ClassDecl");
2931 case CXCursor_FieldDecl:
2932 return createCXString("FieldDecl");
2933 case CXCursor_VarDecl:
2934 return createCXString("VarDecl");
2935 case CXCursor_ParmDecl:
2936 return createCXString("ParmDecl");
2937 case CXCursor_ObjCInterfaceDecl:
2938 return createCXString("ObjCInterfaceDecl");
2939 case CXCursor_ObjCCategoryDecl:
2940 return createCXString("ObjCCategoryDecl");
2941 case CXCursor_ObjCProtocolDecl:
2942 return createCXString("ObjCProtocolDecl");
2943 case CXCursor_ObjCPropertyDecl:
2944 return createCXString("ObjCPropertyDecl");
2945 case CXCursor_ObjCIvarDecl:
2946 return createCXString("ObjCIvarDecl");
2947 case CXCursor_ObjCInstanceMethodDecl:
2948 return createCXString("ObjCInstanceMethodDecl");
2949 case CXCursor_ObjCClassMethodDecl:
2950 return createCXString("ObjCClassMethodDecl");
2951 case CXCursor_ObjCImplementationDecl:
2952 return createCXString("ObjCImplementationDecl");
2953 case CXCursor_ObjCCategoryImplDecl:
2954 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002955 case CXCursor_CXXMethod:
2956 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002957 case CXCursor_UnexposedDecl:
2958 return createCXString("UnexposedDecl");
2959 case CXCursor_ObjCSuperClassRef:
2960 return createCXString("ObjCSuperClassRef");
2961 case CXCursor_ObjCProtocolRef:
2962 return createCXString("ObjCProtocolRef");
2963 case CXCursor_ObjCClassRef:
2964 return createCXString("ObjCClassRef");
2965 case CXCursor_TypeRef:
2966 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002967 case CXCursor_TemplateRef:
2968 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002969 case CXCursor_NamespaceRef:
2970 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002971 case CXCursor_MemberRef:
2972 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002973 case CXCursor_LabelRef:
2974 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002975 case CXCursor_OverloadedDeclRef:
2976 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002977 case CXCursor_UnexposedExpr:
2978 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002979 case CXCursor_BlockExpr:
2980 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002981 case CXCursor_DeclRefExpr:
2982 return createCXString("DeclRefExpr");
2983 case CXCursor_MemberRefExpr:
2984 return createCXString("MemberRefExpr");
2985 case CXCursor_CallExpr:
2986 return createCXString("CallExpr");
2987 case CXCursor_ObjCMessageExpr:
2988 return createCXString("ObjCMessageExpr");
2989 case CXCursor_UnexposedStmt:
2990 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002991 case CXCursor_LabelStmt:
2992 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002993 case CXCursor_InvalidFile:
2994 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002995 case CXCursor_InvalidCode:
2996 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002997 case CXCursor_NoDeclFound:
2998 return createCXString("NoDeclFound");
2999 case CXCursor_NotImplemented:
3000 return createCXString("NotImplemented");
3001 case CXCursor_TranslationUnit:
3002 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003003 case CXCursor_UnexposedAttr:
3004 return createCXString("UnexposedAttr");
3005 case CXCursor_IBActionAttr:
3006 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003007 case CXCursor_IBOutletAttr:
3008 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003009 case CXCursor_IBOutletCollectionAttr:
3010 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003011 case CXCursor_PreprocessingDirective:
3012 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003013 case CXCursor_MacroDefinition:
3014 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003015 case CXCursor_MacroInstantiation:
3016 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003017 case CXCursor_InclusionDirective:
3018 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003019 case CXCursor_Namespace:
3020 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003021 case CXCursor_LinkageSpec:
3022 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003023 case CXCursor_CXXBaseSpecifier:
3024 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003025 case CXCursor_Constructor:
3026 return createCXString("CXXConstructor");
3027 case CXCursor_Destructor:
3028 return createCXString("CXXDestructor");
3029 case CXCursor_ConversionFunction:
3030 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003031 case CXCursor_TemplateTypeParameter:
3032 return createCXString("TemplateTypeParameter");
3033 case CXCursor_NonTypeTemplateParameter:
3034 return createCXString("NonTypeTemplateParameter");
3035 case CXCursor_TemplateTemplateParameter:
3036 return createCXString("TemplateTemplateParameter");
3037 case CXCursor_FunctionTemplate:
3038 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003039 case CXCursor_ClassTemplate:
3040 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003041 case CXCursor_ClassTemplatePartialSpecialization:
3042 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003043 case CXCursor_NamespaceAlias:
3044 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003045 case CXCursor_UsingDirective:
3046 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003047 case CXCursor_UsingDeclaration:
3048 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003049 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003050
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003051 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003052 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003053}
Steve Naroff89922f82009-08-31 00:59:03 +00003054
Ted Kremeneke68fff62010-02-17 00:41:32 +00003055enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3056 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003057 CXClientData client_data) {
3058 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003059
3060 // If our current best cursor is the construction of a temporary object,
3061 // don't replace that cursor with a type reference, because we want
3062 // clang_getCursor() to point at the constructor.
3063 if (clang_isExpression(BestCursor->kind) &&
3064 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3065 cursor.kind == CXCursor_TypeRef)
3066 return CXChildVisit_Recurse;
3067
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003068 *BestCursor = cursor;
3069 return CXChildVisit_Recurse;
3070}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003071
Douglas Gregorb9790342010-01-22 21:44:22 +00003072CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3073 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003074 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003075
Ted Kremeneka60ed472010-11-16 08:15:36 +00003076 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003077 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3078
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003079 // Translate the given source location to make it point at the beginning of
3080 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003081 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003082
3083 // Guard against an invalid SourceLocation, or we may assert in one
3084 // of the following calls.
3085 if (SLoc.isInvalid())
3086 return clang_getNullCursor();
3087
Douglas Gregor40749ee2010-11-03 00:35:38 +00003088 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003089 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3090 CXXUnit->getASTContext().getLangOptions());
3091
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003092 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3093 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003094 // FIXME: Would be great to have a "hint" cursor, then walk from that
3095 // hint cursor upward until we find a cursor whose source range encloses
3096 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003097 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3098 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003099 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003100 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003101 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003102
3103 if (Logging) {
3104 CXFile SearchFile;
3105 unsigned SearchLine, SearchColumn;
3106 CXFile ResultFile;
3107 unsigned ResultLine, ResultColumn;
3108 CXString SearchFileName, ResultFileName, KindSpelling;
3109 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3110
3111 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3112 0);
3113 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3114 &ResultColumn, 0);
3115 SearchFileName = clang_getFileName(SearchFile);
3116 ResultFileName = clang_getFileName(ResultFile);
3117 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3118 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3119 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3120 clang_getCString(KindSpelling),
3121 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3122 clang_disposeString(SearchFileName);
3123 clang_disposeString(ResultFileName);
3124 clang_disposeString(KindSpelling);
3125 }
3126
Ted Kremeneke68fff62010-02-17 00:41:32 +00003127 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003128}
3129
Ted Kremenek73885552009-11-17 19:28:59 +00003130CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003131 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003132}
3133
3134unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003135 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003136}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003137
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003138unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003139 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3140}
3141
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003142unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003143 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3144}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003145
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003146unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003147 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3148}
3149
Douglas Gregor97b98722010-01-19 23:20:36 +00003150unsigned clang_isExpression(enum CXCursorKind K) {
3151 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3152}
3153
3154unsigned clang_isStatement(enum CXCursorKind K) {
3155 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3156}
3157
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003158unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3159 return K == CXCursor_TranslationUnit;
3160}
3161
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003162unsigned clang_isPreprocessing(enum CXCursorKind K) {
3163 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3164}
3165
Ted Kremenekad6eff62010-03-08 21:17:29 +00003166unsigned clang_isUnexposed(enum CXCursorKind K) {
3167 switch (K) {
3168 case CXCursor_UnexposedDecl:
3169 case CXCursor_UnexposedExpr:
3170 case CXCursor_UnexposedStmt:
3171 case CXCursor_UnexposedAttr:
3172 return true;
3173 default:
3174 return false;
3175 }
3176}
3177
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003178CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003179 return C.kind;
3180}
3181
Douglas Gregor98258af2010-01-18 22:46:11 +00003182CXSourceLocation clang_getCursorLocation(CXCursor C) {
3183 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003184 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003185 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003186 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3187 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003188 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003189 }
3190
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003191 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003192 std::pair<ObjCProtocolDecl *, SourceLocation> P
3193 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003194 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003195 }
3196
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003197 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003198 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3199 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003200 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003201 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003202
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003203 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003204 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003205 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003206 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003207
3208 case CXCursor_TemplateRef: {
3209 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3210 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3211 }
3212
Douglas Gregor69319002010-08-31 23:48:11 +00003213 case CXCursor_NamespaceRef: {
3214 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3215 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3216 }
3217
Douglas Gregora67e03f2010-09-09 21:42:20 +00003218 case CXCursor_MemberRef: {
3219 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3220 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3221 }
3222
Ted Kremenek3064ef92010-08-27 21:34:58 +00003223 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003224 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3225 if (!BaseSpec)
3226 return clang_getNullLocation();
3227
3228 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3229 return cxloc::translateSourceLocation(getCursorContext(C),
3230 TSInfo->getTypeLoc().getBeginLoc());
3231
3232 return cxloc::translateSourceLocation(getCursorContext(C),
3233 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003234 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003235
Douglas Gregor36897b02010-09-10 00:22:18 +00003236 case CXCursor_LabelRef: {
3237 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3238 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3239 }
3240
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003241 case CXCursor_OverloadedDeclRef:
3242 return cxloc::translateSourceLocation(getCursorContext(C),
3243 getCursorOverloadedDeclRef(C).second);
3244
Douglas Gregorf46034a2010-01-18 23:41:10 +00003245 default:
3246 // FIXME: Need a way to enumerate all non-reference cases.
3247 llvm_unreachable("Missed a reference kind");
3248 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003249 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003250
3251 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003252 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003253 getLocationFromExpr(getCursorExpr(C)));
3254
Douglas Gregor36897b02010-09-10 00:22:18 +00003255 if (clang_isStatement(C.kind))
3256 return cxloc::translateSourceLocation(getCursorContext(C),
3257 getCursorStmt(C)->getLocStart());
3258
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003259 if (C.kind == CXCursor_PreprocessingDirective) {
3260 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3261 return cxloc::translateSourceLocation(getCursorContext(C), L);
3262 }
Douglas Gregor48072312010-03-18 15:23:44 +00003263
3264 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003265 SourceLocation L
3266 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003267 return cxloc::translateSourceLocation(getCursorContext(C), L);
3268 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003269
3270 if (C.kind == CXCursor_MacroDefinition) {
3271 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3272 return cxloc::translateSourceLocation(getCursorContext(C), L);
3273 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003274
3275 if (C.kind == CXCursor_InclusionDirective) {
3276 SourceLocation L
3277 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3278 return cxloc::translateSourceLocation(getCursorContext(C), L);
3279 }
3280
Ted Kremenek9a700d22010-05-12 06:16:13 +00003281 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003282 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003283
Douglas Gregorf46034a2010-01-18 23:41:10 +00003284 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003285 SourceLocation Loc = D->getLocation();
3286 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3287 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003288 // FIXME: Multiple variables declared in a single declaration
3289 // currently lack the information needed to correctly determine their
3290 // ranges when accounting for the type-specifier. We use context
3291 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3292 // and if so, whether it is the first decl.
3293 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3294 if (!cxcursor::isFirstInDeclGroup(C))
3295 Loc = VD->getLocation();
3296 }
3297
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003298 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003299}
Douglas Gregora7bde202010-01-19 00:34:46 +00003300
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003301} // end extern "C"
3302
3303static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003304 if (clang_isReference(C.kind)) {
3305 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003306 case CXCursor_ObjCSuperClassRef:
3307 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003308
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003309 case CXCursor_ObjCProtocolRef:
3310 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003311
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003312 case CXCursor_ObjCClassRef:
3313 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003314
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003315 case CXCursor_TypeRef:
3316 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003317
3318 case CXCursor_TemplateRef:
3319 return getCursorTemplateRef(C).second;
3320
Douglas Gregor69319002010-08-31 23:48:11 +00003321 case CXCursor_NamespaceRef:
3322 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003323
3324 case CXCursor_MemberRef:
3325 return getCursorMemberRef(C).second;
3326
Ted Kremenek3064ef92010-08-27 21:34:58 +00003327 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003328 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003329
Douglas Gregor36897b02010-09-10 00:22:18 +00003330 case CXCursor_LabelRef:
3331 return getCursorLabelRef(C).second;
3332
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003333 case CXCursor_OverloadedDeclRef:
3334 return getCursorOverloadedDeclRef(C).second;
3335
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003336 default:
3337 // FIXME: Need a way to enumerate all non-reference cases.
3338 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003339 }
3340 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003341
3342 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003343 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003344
3345 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003346 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003347
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003348 if (C.kind == CXCursor_PreprocessingDirective)
3349 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003350
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003351 if (C.kind == CXCursor_MacroInstantiation)
3352 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003353
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003354 if (C.kind == CXCursor_MacroDefinition)
3355 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003356
3357 if (C.kind == CXCursor_InclusionDirective)
3358 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3359
Ted Kremenek007a7c92010-11-01 23:26:51 +00003360 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3361 Decl *D = cxcursor::getCursorDecl(C);
3362 SourceRange R = D->getSourceRange();
3363 // FIXME: Multiple variables declared in a single declaration
3364 // currently lack the information needed to correctly determine their
3365 // ranges when accounting for the type-specifier. We use context
3366 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3367 // and if so, whether it is the first decl.
3368 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3369 if (!cxcursor::isFirstInDeclGroup(C))
3370 R.setBegin(VD->getLocation());
3371 }
3372 return R;
3373 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003374 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003375
3376extern "C" {
3377
3378CXSourceRange clang_getCursorExtent(CXCursor C) {
3379 SourceRange R = getRawCursorExtent(C);
3380 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003381 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003382
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003383 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003384}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003385
3386CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003387 if (clang_isInvalid(C.kind))
3388 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003389
Ted Kremeneka60ed472010-11-16 08:15:36 +00003390 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003391 if (clang_isDeclaration(C.kind)) {
3392 Decl *D = getCursorDecl(C);
3393 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003394 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003395 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003396 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003397 if (ObjCForwardProtocolDecl *Protocols
3398 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003399 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003400 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3401 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3402 return MakeCXCursor(Property, tu);
3403
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003404 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003405 }
3406
Douglas Gregor97b98722010-01-19 23:20:36 +00003407 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003408 Expr *E = getCursorExpr(C);
3409 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003410 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003411 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003412
3413 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003414 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003415
Douglas Gregor97b98722010-01-19 23:20:36 +00003416 return clang_getNullCursor();
3417 }
3418
Douglas Gregor36897b02010-09-10 00:22:18 +00003419 if (clang_isStatement(C.kind)) {
3420 Stmt *S = getCursorStmt(C);
3421 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003422 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003423
3424 return clang_getNullCursor();
3425 }
3426
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003427 if (C.kind == CXCursor_MacroInstantiation) {
3428 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003429 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003430 }
3431
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003432 if (!clang_isReference(C.kind))
3433 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003434
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003435 switch (C.kind) {
3436 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003437 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438
3439 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003440 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003441
3442 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003443 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003444
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003445 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003446 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003447
3448 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003449 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003450
Douglas Gregor69319002010-08-31 23:48:11 +00003451 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003452 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003453
Douglas Gregora67e03f2010-09-09 21:42:20 +00003454 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003455 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003456
Ted Kremenek3064ef92010-08-27 21:34:58 +00003457 case CXCursor_CXXBaseSpecifier: {
3458 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3459 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003460 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003461 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003462
Douglas Gregor36897b02010-09-10 00:22:18 +00003463 case CXCursor_LabelRef:
3464 // FIXME: We end up faking the "parent" declaration here because we
3465 // don't want to make CXCursor larger.
3466 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003467 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3468 .getTranslationUnitDecl(),
3469 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003470
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003471 case CXCursor_OverloadedDeclRef:
3472 return C;
3473
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003474 default:
3475 // We would prefer to enumerate all non-reference cursor kinds here.
3476 llvm_unreachable("Unhandled reference cursor kind");
3477 break;
3478 }
3479 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003480
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003481 return clang_getNullCursor();
3482}
3483
Douglas Gregorb6998662010-01-19 19:34:47 +00003484CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003485 if (clang_isInvalid(C.kind))
3486 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003487
Ted Kremeneka60ed472010-11-16 08:15:36 +00003488 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003489
Douglas Gregorb6998662010-01-19 19:34:47 +00003490 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003491 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003492 C = clang_getCursorReferenced(C);
3493 WasReference = true;
3494 }
3495
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003496 if (C.kind == CXCursor_MacroInstantiation)
3497 return clang_getCursorReferenced(C);
3498
Douglas Gregorb6998662010-01-19 19:34:47 +00003499 if (!clang_isDeclaration(C.kind))
3500 return clang_getNullCursor();
3501
3502 Decl *D = getCursorDecl(C);
3503 if (!D)
3504 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003505
Douglas Gregorb6998662010-01-19 19:34:47 +00003506 switch (D->getKind()) {
3507 // Declaration kinds that don't really separate the notions of
3508 // declaration and definition.
3509 case Decl::Namespace:
3510 case Decl::Typedef:
3511 case Decl::TemplateTypeParm:
3512 case Decl::EnumConstant:
3513 case Decl::Field:
3514 case Decl::ObjCIvar:
3515 case Decl::ObjCAtDefsField:
3516 case Decl::ImplicitParam:
3517 case Decl::ParmVar:
3518 case Decl::NonTypeTemplateParm:
3519 case Decl::TemplateTemplateParm:
3520 case Decl::ObjCCategoryImpl:
3521 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003522 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003523 case Decl::LinkageSpec:
3524 case Decl::ObjCPropertyImpl:
3525 case Decl::FileScopeAsm:
3526 case Decl::StaticAssert:
3527 case Decl::Block:
3528 return C;
3529
3530 // Declaration kinds that don't make any sense here, but are
3531 // nonetheless harmless.
3532 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003533 break;
3534
3535 // Declaration kinds for which the definition is not resolvable.
3536 case Decl::UnresolvedUsingTypename:
3537 case Decl::UnresolvedUsingValue:
3538 break;
3539
3540 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003541 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003542 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003543
3544 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003545 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003546
3547 case Decl::Enum:
3548 case Decl::Record:
3549 case Decl::CXXRecord:
3550 case Decl::ClassTemplateSpecialization:
3551 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003552 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003553 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003554 return clang_getNullCursor();
3555
3556 case Decl::Function:
3557 case Decl::CXXMethod:
3558 case Decl::CXXConstructor:
3559 case Decl::CXXDestructor:
3560 case Decl::CXXConversion: {
3561 const FunctionDecl *Def = 0;
3562 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003563 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003564 return clang_getNullCursor();
3565 }
3566
3567 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003568 // Ask the variable if it has a definition.
3569 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003570 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003571 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003572 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003573
Douglas Gregorb6998662010-01-19 19:34:47 +00003574 case Decl::FunctionTemplate: {
3575 const FunctionDecl *Def = 0;
3576 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003577 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 return clang_getNullCursor();
3579 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003580
Douglas Gregorb6998662010-01-19 19:34:47 +00003581 case Decl::ClassTemplate: {
3582 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003583 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003584 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003585 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003586 return clang_getNullCursor();
3587 }
3588
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003589 case Decl::Using:
3590 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003591 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003592
3593 case Decl::UsingShadow:
3594 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003595 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003596 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003597
3598 case Decl::ObjCMethod: {
3599 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3600 if (Method->isThisDeclarationADefinition())
3601 return C;
3602
3603 // Dig out the method definition in the associated
3604 // @implementation, if we have it.
3605 // FIXME: The ASTs should make finding the definition easier.
3606 if (ObjCInterfaceDecl *Class
3607 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3608 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3609 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3610 Method->isInstanceMethod()))
3611 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003612 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003613
3614 return clang_getNullCursor();
3615 }
3616
3617 case Decl::ObjCCategory:
3618 if (ObjCCategoryImplDecl *Impl
3619 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003620 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003621 return clang_getNullCursor();
3622
3623 case Decl::ObjCProtocol:
3624 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3625 return C;
3626 return clang_getNullCursor();
3627
3628 case Decl::ObjCInterface:
3629 // There are two notions of a "definition" for an Objective-C
3630 // class: the interface and its implementation. When we resolved a
3631 // reference to an Objective-C class, produce the @interface as
3632 // the definition; when we were provided with the interface,
3633 // produce the @implementation as the definition.
3634 if (WasReference) {
3635 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3636 return C;
3637 } else if (ObjCImplementationDecl *Impl
3638 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003639 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003640 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003641
Douglas Gregorb6998662010-01-19 19:34:47 +00003642 case Decl::ObjCProperty:
3643 // FIXME: We don't really know where to find the
3644 // ObjCPropertyImplDecls that implement this property.
3645 return clang_getNullCursor();
3646
3647 case Decl::ObjCCompatibleAlias:
3648 if (ObjCInterfaceDecl *Class
3649 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3650 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003651 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003652
Douglas Gregorb6998662010-01-19 19:34:47 +00003653 return clang_getNullCursor();
3654
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003655 case Decl::ObjCForwardProtocol:
3656 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003657 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003658
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003659 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003660 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003661 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003662
3663 case Decl::Friend:
3664 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003665 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003666 return clang_getNullCursor();
3667
3668 case Decl::FriendTemplate:
3669 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003670 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003671 return clang_getNullCursor();
3672 }
3673
3674 return clang_getNullCursor();
3675}
3676
3677unsigned clang_isCursorDefinition(CXCursor C) {
3678 if (!clang_isDeclaration(C.kind))
3679 return 0;
3680
3681 return clang_getCursorDefinition(C) == C;
3682}
3683
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003684unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003685 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003686 return 0;
3687
3688 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3689 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3690 return E->getNumDecls();
3691
3692 if (OverloadedTemplateStorage *S
3693 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3694 return S->size();
3695
3696 Decl *D = Storage.get<Decl*>();
3697 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003698 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003699 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3700 return Classes->size();
3701 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3702 return Protocols->protocol_size();
3703
3704 return 0;
3705}
3706
3707CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003708 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003709 return clang_getNullCursor();
3710
3711 if (index >= clang_getNumOverloadedDecls(cursor))
3712 return clang_getNullCursor();
3713
Ted Kremeneka60ed472010-11-16 08:15:36 +00003714 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003715 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3716 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003717 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003718
3719 if (OverloadedTemplateStorage *S
3720 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003721 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003722
3723 Decl *D = Storage.get<Decl*>();
3724 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3725 // FIXME: This is, unfortunately, linear time.
3726 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3727 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003728 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003729 }
3730
3731 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003732 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003733
3734 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003735 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003736
3737 return clang_getNullCursor();
3738}
3739
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003740void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003741 const char **startBuf,
3742 const char **endBuf,
3743 unsigned *startLine,
3744 unsigned *startColumn,
3745 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003746 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003747 assert(getCursorDecl(C) && "CXCursor has null decl");
3748 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003749 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3750 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003751
Steve Naroff4ade6d62009-09-23 17:52:52 +00003752 SourceManager &SM = FD->getASTContext().getSourceManager();
3753 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3754 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3755 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3756 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3757 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3758 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3759}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003760
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003761void clang_enableStackTraces(void) {
3762 llvm::sys::PrintStackTraceOnErrorSignal();
3763}
3764
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003765void clang_executeOnThread(void (*fn)(void*), void *user_data,
3766 unsigned stack_size) {
3767 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3768}
3769
Ted Kremenekfb480492010-01-13 21:46:36 +00003770} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003771
Ted Kremenekfb480492010-01-13 21:46:36 +00003772//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003773// Token-based Operations.
3774//===----------------------------------------------------------------------===//
3775
3776/* CXToken layout:
3777 * int_data[0]: a CXTokenKind
3778 * int_data[1]: starting token location
3779 * int_data[2]: token length
3780 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003781 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003782 * otherwise unused.
3783 */
3784extern "C" {
3785
3786CXTokenKind clang_getTokenKind(CXToken CXTok) {
3787 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3788}
3789
3790CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3791 switch (clang_getTokenKind(CXTok)) {
3792 case CXToken_Identifier:
3793 case CXToken_Keyword:
3794 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003795 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3796 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003797
3798 case CXToken_Literal: {
3799 // We have stashed the starting pointer in the ptr_data field. Use it.
3800 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003801 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003803
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003804 case CXToken_Punctuation:
3805 case CXToken_Comment:
3806 break;
3807 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003808
3809 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003810 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003811 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003812 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003813 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003814
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003815 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3816 std::pair<FileID, unsigned> LocInfo
3817 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003818 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003819 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003820 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3821 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003822 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003823
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003824 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003825}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003826
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003827CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003828 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003829 if (!CXXUnit)
3830 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003831
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003832 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3833 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3834}
3835
3836CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003837 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003838 if (!CXXUnit)
3839 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003840
3841 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003842 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3843}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003844
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003845void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3846 CXToken **Tokens, unsigned *NumTokens) {
3847 if (Tokens)
3848 *Tokens = 0;
3849 if (NumTokens)
3850 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851
Ted Kremeneka60ed472010-11-16 08:15:36 +00003852 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003853 if (!CXXUnit || !Tokens || !NumTokens)
3854 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003855
Douglas Gregorbdf60622010-03-05 21:16:25 +00003856 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3857
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003858 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 if (R.isInvalid())
3860 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003861
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003862 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3863 std::pair<FileID, unsigned> BeginLocInfo
3864 = SourceMgr.getDecomposedLoc(R.getBegin());
3865 std::pair<FileID, unsigned> EndLocInfo
3866 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003867
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003868 // Cannot tokenize across files.
3869 if (BeginLocInfo.first != EndLocInfo.first)
3870 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003871
3872 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003873 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003874 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003875 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003876 if (Invalid)
3877 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003878
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003879 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3880 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003881 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003882 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003883
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003884 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003885 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003886 llvm::SmallVector<CXToken, 32> CXTokens;
3887 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003888 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003889 do {
3890 // Lex the next token
3891 Lex.LexFromRawLexer(Tok);
3892 if (Tok.is(tok::eof))
3893 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895 // Initialize the CXToken.
3896 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003897
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003898 // - Common fields
3899 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3900 CXTok.int_data[2] = Tok.getLength();
3901 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003902
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003903 // - Kind-specific fields
3904 if (Tok.isLiteral()) {
3905 CXTok.int_data[0] = CXToken_Literal;
3906 CXTok.ptr_data = (void *)Tok.getLiteralData();
3907 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003908 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003909 std::pair<FileID, unsigned> LocInfo
3910 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003911 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003912 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003913 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3914 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003915 return;
3916
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003917 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003918 IdentifierInfo *II
3919 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003920
David Chisnall096428b2010-10-13 21:44:48 +00003921 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003922 CXTok.int_data[0] = CXToken_Keyword;
3923 }
3924 else {
3925 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3926 CXToken_Identifier
3927 : CXToken_Keyword;
3928 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003929 CXTok.ptr_data = II;
3930 } else if (Tok.is(tok::comment)) {
3931 CXTok.int_data[0] = CXToken_Comment;
3932 CXTok.ptr_data = 0;
3933 } else {
3934 CXTok.int_data[0] = CXToken_Punctuation;
3935 CXTok.ptr_data = 0;
3936 }
3937 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003938 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003939 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003940
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003941 if (CXTokens.empty())
3942 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003943
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003944 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3945 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3946 *NumTokens = CXTokens.size();
3947}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003948
Ted Kremenek6db61092010-05-05 00:55:15 +00003949void clang_disposeTokens(CXTranslationUnit TU,
3950 CXToken *Tokens, unsigned NumTokens) {
3951 free(Tokens);
3952}
3953
3954} // end: extern "C"
3955
3956//===----------------------------------------------------------------------===//
3957// Token annotation APIs.
3958//===----------------------------------------------------------------------===//
3959
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003960typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003961static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3962 CXCursor parent,
3963 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003964namespace {
3965class AnnotateTokensWorker {
3966 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003967 CXToken *Tokens;
3968 CXCursor *Cursors;
3969 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003970 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003971 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003972 CursorVisitor AnnotateVis;
3973 SourceManager &SrcMgr;
3974
3975 bool MoreTokens() const { return TokIdx < NumTokens; }
3976 unsigned NextToken() const { return TokIdx; }
3977 void AdvanceToken() { ++TokIdx; }
3978 SourceLocation GetTokenLoc(unsigned tokI) {
3979 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3980 }
3981
Ted Kremenek6db61092010-05-05 00:55:15 +00003982public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003983 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003984 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003985 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003986 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003987 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003988 AnnotateVis(tu,
3989 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003990 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003991 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003992
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003993 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003994 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003995 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003996 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003997 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00003998 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003999};
4000}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004001
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004002void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4003 // Walk the AST within the region of interest, annotating tokens
4004 // along the way.
4005 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004006
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004007 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4008 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004009 if (Pos != Annotated.end() &&
4010 (clang_isInvalid(Cursors[I].kind) ||
4011 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004012 Cursors[I] = Pos->second;
4013 }
4014
4015 // Finish up annotating any tokens left.
4016 if (!MoreTokens())
4017 return;
4018
4019 const CXCursor &C = clang_getNullCursor();
4020 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4021 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4022 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004023 }
4024}
4025
Ted Kremenek6db61092010-05-05 00:55:15 +00004026enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004027AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004028 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004029 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004030 if (cursorRange.isInvalid())
4031 return CXChildVisit_Recurse;
4032
Douglas Gregor4419b672010-10-21 06:10:04 +00004033 if (clang_isPreprocessing(cursor.kind)) {
4034 // For macro instantiations, just note where the beginning of the macro
4035 // instantiation occurs.
4036 if (cursor.kind == CXCursor_MacroInstantiation) {
4037 Annotated[Loc.int_data] = cursor;
4038 return CXChildVisit_Recurse;
4039 }
4040
Douglas Gregor4419b672010-10-21 06:10:04 +00004041 // Items in the preprocessing record are kept separate from items in
4042 // declarations, so we keep a separate token index.
4043 unsigned SavedTokIdx = TokIdx;
4044 TokIdx = PreprocessingTokIdx;
4045
4046 // Skip tokens up until we catch up to the beginning of the preprocessing
4047 // entry.
4048 while (MoreTokens()) {
4049 const unsigned I = NextToken();
4050 SourceLocation TokLoc = GetTokenLoc(I);
4051 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4052 case RangeBefore:
4053 AdvanceToken();
4054 continue;
4055 case RangeAfter:
4056 case RangeOverlap:
4057 break;
4058 }
4059 break;
4060 }
4061
4062 // Look at all of the tokens within this range.
4063 while (MoreTokens()) {
4064 const unsigned I = NextToken();
4065 SourceLocation TokLoc = GetTokenLoc(I);
4066 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4067 case RangeBefore:
4068 assert(0 && "Infeasible");
4069 case RangeAfter:
4070 break;
4071 case RangeOverlap:
4072 Cursors[I] = cursor;
4073 AdvanceToken();
4074 continue;
4075 }
4076 break;
4077 }
4078
4079 // Save the preprocessing token index; restore the non-preprocessing
4080 // token index.
4081 PreprocessingTokIdx = TokIdx;
4082 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004083 return CXChildVisit_Recurse;
4084 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004085
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004086 if (cursorRange.isInvalid())
4087 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004088
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004089 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4090
Ted Kremeneka333c662010-05-12 05:29:33 +00004091 // Adjust the annotated range based specific declarations.
4092 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4093 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004094 Decl *D = cxcursor::getCursorDecl(cursor);
4095 // Don't visit synthesized ObjC methods, since they have no syntatic
4096 // representation in the source.
4097 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4098 if (MD->isSynthesized())
4099 return CXChildVisit_Continue;
4100 }
4101 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004102 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4103 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004104 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004105 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004106 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004107 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004108 }
4109 }
4110 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004111
Ted Kremenek3f404602010-08-14 01:14:06 +00004112 // If the location of the cursor occurs within a macro instantiation, record
4113 // the spelling location of the cursor in our annotation map. We can then
4114 // paper over the token labelings during a post-processing step to try and
4115 // get cursor mappings for tokens that are the *arguments* of a macro
4116 // instantiation.
4117 if (L.isMacroID()) {
4118 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4119 // Only invalidate the old annotation if it isn't part of a preprocessing
4120 // directive. Here we assume that the default construction of CXCursor
4121 // results in CXCursor.kind being an initialized value (i.e., 0). If
4122 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004123
Ted Kremenek3f404602010-08-14 01:14:06 +00004124 CXCursor &oldC = Annotated[rawEncoding];
4125 if (!clang_isPreprocessing(oldC.kind))
4126 oldC = cursor;
4127 }
4128
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004129 const enum CXCursorKind K = clang_getCursorKind(parent);
4130 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004131 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4132 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004133
4134 while (MoreTokens()) {
4135 const unsigned I = NextToken();
4136 SourceLocation TokLoc = GetTokenLoc(I);
4137 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4138 case RangeBefore:
4139 Cursors[I] = updateC;
4140 AdvanceToken();
4141 continue;
4142 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004143 case RangeOverlap:
4144 break;
4145 }
4146 break;
4147 }
4148
4149 // Visit children to get their cursor information.
4150 const unsigned BeforeChildren = NextToken();
4151 VisitChildren(cursor);
4152 const unsigned AfterChildren = NextToken();
4153
4154 // Adjust 'Last' to the last token within the extent of the cursor.
4155 while (MoreTokens()) {
4156 const unsigned I = NextToken();
4157 SourceLocation TokLoc = GetTokenLoc(I);
4158 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4159 case RangeBefore:
4160 assert(0 && "Infeasible");
4161 case RangeAfter:
4162 break;
4163 case RangeOverlap:
4164 Cursors[I] = updateC;
4165 AdvanceToken();
4166 continue;
4167 }
4168 break;
4169 }
4170 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004171
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004172 // Scan the tokens that are at the beginning of the cursor, but are not
4173 // capture by the child cursors.
4174
4175 // For AST elements within macros, rely on a post-annotate pass to
4176 // to correctly annotate the tokens with cursors. Otherwise we can
4177 // get confusing results of having tokens that map to cursors that really
4178 // are expanded by an instantiation.
4179 if (L.isMacroID())
4180 cursor = clang_getNullCursor();
4181
4182 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4183 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4184 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004185
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004186 Cursors[I] = cursor;
4187 }
4188 // Scan the tokens that are at the end of the cursor, but are not captured
4189 // but the child cursors.
4190 for (unsigned I = AfterChildren; I != Last; ++I)
4191 Cursors[I] = cursor;
4192
4193 TokIdx = Last;
4194 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004195}
4196
Ted Kremenek6db61092010-05-05 00:55:15 +00004197static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4198 CXCursor parent,
4199 CXClientData client_data) {
4200 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4201}
4202
Ted Kremenekab979612010-11-11 08:05:23 +00004203// This gets run a separate thread to avoid stack blowout.
4204static void runAnnotateTokensWorker(void *UserData) {
4205 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4206}
4207
Ted Kremenek6db61092010-05-05 00:55:15 +00004208extern "C" {
4209
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004210void clang_annotateTokens(CXTranslationUnit TU,
4211 CXToken *Tokens, unsigned NumTokens,
4212 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004213
4214 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004215 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004216
Douglas Gregor4419b672010-10-21 06:10:04 +00004217 // Any token we don't specifically annotate will have a NULL cursor.
4218 CXCursor C = clang_getNullCursor();
4219 for (unsigned I = 0; I != NumTokens; ++I)
4220 Cursors[I] = C;
4221
Ted Kremeneka60ed472010-11-16 08:15:36 +00004222 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004223 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004224 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004225
Douglas Gregorbdf60622010-03-05 21:16:25 +00004226 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227
Douglas Gregor0396f462010-03-19 05:22:59 +00004228 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004229 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004230 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4231 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004232 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4233 clang_getTokenLocation(TU,
4234 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004235
Douglas Gregor0396f462010-03-19 05:22:59 +00004236 // A mapping from the source locations found when re-lexing or traversing the
4237 // region of interest to the corresponding cursors.
4238 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
4240 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004241 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004242 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4243 std::pair<FileID, unsigned> BeginLocInfo
4244 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4245 std::pair<FileID, unsigned> EndLocInfo
4246 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004247
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004248 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004249 bool Invalid = false;
4250 if (BeginLocInfo.first == EndLocInfo.first &&
4251 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4252 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4254 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004255 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004256 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004257 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004258
4259 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004260 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004261 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004262 Token Tok;
4263 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004264
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004265 reprocess:
4266 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4267 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004268 // don't see it while preprocessing these tokens later, but keep track
4269 // of all of the token locations inside this preprocessing directive so
4270 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004271 //
4272 // FIXME: Some simple tests here could identify macro definitions and
4273 // #undefs, to provide specific cursor kinds for those.
4274 std::vector<SourceLocation> Locations;
4275 do {
4276 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004277 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004278 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004280 using namespace cxcursor;
4281 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004282 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4283 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004284 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004285 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4286 Annotated[Locations[I].getRawEncoding()] = Cursor;
4287 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004288
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004289 if (Tok.isAtStartOfLine())
4290 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004291
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004292 continue;
4293 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004294
Douglas Gregor48072312010-03-18 15:23:44 +00004295 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004296 break;
4297 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004298 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004299
Douglas Gregor0396f462010-03-19 05:22:59 +00004300 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004301 // a specific cursor.
4302 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004303 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004304
4305 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004306 // FIXME: We use a ridiculous stack size here because the data-recursion
4307 // algorithm uses a large stack frame than the non-data recursive version,
4308 // and AnnotationTokensWorker currently transforms the data-recursion
4309 // algorithm back into a traditional recursion by explicitly calling
4310 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004311 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004312 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4313 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004314 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4315 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004316}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004317} // end: extern "C"
4318
4319//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004320// Operations for querying linkage of a cursor.
4321//===----------------------------------------------------------------------===//
4322
4323extern "C" {
4324CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004325 if (!clang_isDeclaration(cursor.kind))
4326 return CXLinkage_Invalid;
4327
Ted Kremenek16b42592010-03-03 06:36:57 +00004328 Decl *D = cxcursor::getCursorDecl(cursor);
4329 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4330 switch (ND->getLinkage()) {
4331 case NoLinkage: return CXLinkage_NoLinkage;
4332 case InternalLinkage: return CXLinkage_Internal;
4333 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4334 case ExternalLinkage: return CXLinkage_External;
4335 };
4336
4337 return CXLinkage_Invalid;
4338}
4339} // end: extern "C"
4340
4341//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004342// Operations for querying language of a cursor.
4343//===----------------------------------------------------------------------===//
4344
4345static CXLanguageKind getDeclLanguage(const Decl *D) {
4346 switch (D->getKind()) {
4347 default:
4348 break;
4349 case Decl::ImplicitParam:
4350 case Decl::ObjCAtDefsField:
4351 case Decl::ObjCCategory:
4352 case Decl::ObjCCategoryImpl:
4353 case Decl::ObjCClass:
4354 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004355 case Decl::ObjCForwardProtocol:
4356 case Decl::ObjCImplementation:
4357 case Decl::ObjCInterface:
4358 case Decl::ObjCIvar:
4359 case Decl::ObjCMethod:
4360 case Decl::ObjCProperty:
4361 case Decl::ObjCPropertyImpl:
4362 case Decl::ObjCProtocol:
4363 return CXLanguage_ObjC;
4364 case Decl::CXXConstructor:
4365 case Decl::CXXConversion:
4366 case Decl::CXXDestructor:
4367 case Decl::CXXMethod:
4368 case Decl::CXXRecord:
4369 case Decl::ClassTemplate:
4370 case Decl::ClassTemplatePartialSpecialization:
4371 case Decl::ClassTemplateSpecialization:
4372 case Decl::Friend:
4373 case Decl::FriendTemplate:
4374 case Decl::FunctionTemplate:
4375 case Decl::LinkageSpec:
4376 case Decl::Namespace:
4377 case Decl::NamespaceAlias:
4378 case Decl::NonTypeTemplateParm:
4379 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004380 case Decl::TemplateTemplateParm:
4381 case Decl::TemplateTypeParm:
4382 case Decl::UnresolvedUsingTypename:
4383 case Decl::UnresolvedUsingValue:
4384 case Decl::Using:
4385 case Decl::UsingDirective:
4386 case Decl::UsingShadow:
4387 return CXLanguage_CPlusPlus;
4388 }
4389
4390 return CXLanguage_C;
4391}
4392
4393extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004394
4395enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4396 if (clang_isDeclaration(cursor.kind))
4397 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4398 if (D->hasAttr<UnavailableAttr>() ||
4399 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4400 return CXAvailability_Available;
4401
4402 if (D->hasAttr<DeprecatedAttr>())
4403 return CXAvailability_Deprecated;
4404 }
4405
4406 return CXAvailability_Available;
4407}
4408
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004409CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4410 if (clang_isDeclaration(cursor.kind))
4411 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4412
4413 return CXLanguage_Invalid;
4414}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004415
4416CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4417 if (clang_isDeclaration(cursor.kind)) {
4418 if (Decl *D = getCursorDecl(cursor)) {
4419 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004420 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004421 }
4422 }
4423
4424 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4425 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004426 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004427 }
4428
4429 return clang_getNullCursor();
4430}
4431
4432CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4433 if (clang_isDeclaration(cursor.kind)) {
4434 if (Decl *D = getCursorDecl(cursor)) {
4435 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004436 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004437 }
4438 }
4439
4440 // FIXME: Note that we can't easily compute the lexical context of a
4441 // statement or expression, so we return nothing.
4442 return clang_getNullCursor();
4443}
4444
Douglas Gregor9f592342010-10-01 20:25:15 +00004445static void CollectOverriddenMethods(DeclContext *Ctx,
4446 ObjCMethodDecl *Method,
4447 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4448 if (!Ctx)
4449 return;
4450
4451 // If we have a class or category implementation, jump straight to the
4452 // interface.
4453 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4454 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4455
4456 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4457 if (!Container)
4458 return;
4459
4460 // Check whether we have a matching method at this level.
4461 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4462 Method->isInstanceMethod()))
4463 if (Method != Overridden) {
4464 // We found an override at this level; there is no need to look
4465 // into other protocols or categories.
4466 Methods.push_back(Overridden);
4467 return;
4468 }
4469
4470 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4471 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4472 PEnd = Protocol->protocol_end();
4473 P != PEnd; ++P)
4474 CollectOverriddenMethods(*P, Method, Methods);
4475 }
4476
4477 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4478 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4479 PEnd = Category->protocol_end();
4480 P != PEnd; ++P)
4481 CollectOverriddenMethods(*P, Method, Methods);
4482 }
4483
4484 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4485 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4486 PEnd = Interface->protocol_end();
4487 P != PEnd; ++P)
4488 CollectOverriddenMethods(*P, Method, Methods);
4489
4490 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4491 Category; Category = Category->getNextClassCategory())
4492 CollectOverriddenMethods(Category, Method, Methods);
4493
4494 // We only look into the superclass if we haven't found anything yet.
4495 if (Methods.empty())
4496 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4497 return CollectOverriddenMethods(Super, Method, Methods);
4498 }
4499}
4500
4501void clang_getOverriddenCursors(CXCursor cursor,
4502 CXCursor **overridden,
4503 unsigned *num_overridden) {
4504 if (overridden)
4505 *overridden = 0;
4506 if (num_overridden)
4507 *num_overridden = 0;
4508 if (!overridden || !num_overridden)
4509 return;
4510
4511 if (!clang_isDeclaration(cursor.kind))
4512 return;
4513
4514 Decl *D = getCursorDecl(cursor);
4515 if (!D)
4516 return;
4517
4518 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004519 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004520 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4521 *num_overridden = CXXMethod->size_overridden_methods();
4522 if (!*num_overridden)
4523 return;
4524
4525 *overridden = new CXCursor [*num_overridden];
4526 unsigned I = 0;
4527 for (CXXMethodDecl::method_iterator
4528 M = CXXMethod->begin_overridden_methods(),
4529 MEnd = CXXMethod->end_overridden_methods();
4530 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004531 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004532 return;
4533 }
4534
4535 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4536 if (!Method)
4537 return;
4538
4539 // Handle Objective-C methods.
4540 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4541 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4542
4543 if (Methods.empty())
4544 return;
4545
4546 *num_overridden = Methods.size();
4547 *overridden = new CXCursor [Methods.size()];
4548 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004549 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004550}
4551
4552void clang_disposeOverriddenCursors(CXCursor *overridden) {
4553 delete [] overridden;
4554}
4555
Douglas Gregorecdcb882010-10-20 22:00:55 +00004556CXFile clang_getIncludedFile(CXCursor cursor) {
4557 if (cursor.kind != CXCursor_InclusionDirective)
4558 return 0;
4559
4560 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4561 return (void *)ID->getFile();
4562}
4563
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004564} // end: extern "C"
4565
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004566
4567//===----------------------------------------------------------------------===//
4568// C++ AST instrospection.
4569//===----------------------------------------------------------------------===//
4570
4571extern "C" {
4572unsigned clang_CXXMethod_isStatic(CXCursor C) {
4573 if (!clang_isDeclaration(C.kind))
4574 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004575
4576 CXXMethodDecl *Method = 0;
4577 Decl *D = cxcursor::getCursorDecl(C);
4578 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4579 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4580 else
4581 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4582 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004583}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004584
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004585} // end: extern "C"
4586
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004587//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004588// Attribute introspection.
4589//===----------------------------------------------------------------------===//
4590
4591extern "C" {
4592CXType clang_getIBOutletCollectionType(CXCursor C) {
4593 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004594 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004595
4596 IBOutletCollectionAttr *A =
4597 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4598
Ted Kremeneka60ed472010-11-16 08:15:36 +00004599 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004600}
4601} // end: extern "C"
4602
4603//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004604// Misc. utility functions.
4605//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004606
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004607/// Default to using an 8 MB stack size on "safety" threads.
4608static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004609
4610namespace clang {
4611
4612bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004613 void (*Fn)(void*), void *UserData,
4614 unsigned Size) {
4615 if (!Size)
4616 Size = GetSafetyThreadStackSize();
4617 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004618 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4619 return CRC.RunSafely(Fn, UserData);
4620}
4621
4622unsigned GetSafetyThreadStackSize() {
4623 return SafetyStackThreadSize;
4624}
4625
4626void SetSafetyThreadStackSize(unsigned Value) {
4627 SafetyStackThreadSize = Value;
4628}
4629
4630}
4631
Ted Kremenek04bb7162010-01-22 22:44:15 +00004632extern "C" {
4633
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004634CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004635 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004636}
4637
4638} // end: extern "C"