blob: e87ec059b58062505e9a6903f3ffd6255b9909c4 [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 Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000126
127class VisitorJob {
128public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000129 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000130 TypeLocVisitKind, OverloadExprPartsKind,
131 DeclRefExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000132protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000133 void *dataA;
134 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135 CXCursor parent;
136 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000137 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
138 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000139public:
140 Kind getKind() const { return K; }
141 const CXCursor &getParent() const { return parent; }
142 static bool classof(VisitorJob *VJ) { return true; }
143};
144
145typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
146
Douglas Gregorb1373d02010-01-20 20:59:29 +0000147// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000148class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000149 public TypeLocVisitor<CursorVisitor, bool>,
150 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000151{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000153 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000154
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000155 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000157
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000158 /// \brief The declaration that serves at the parent of any statement or
159 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000160 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000161
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000162 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000167
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000168 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
169 // to the visitor. Declarations with a PCH level greater than this value will
170 // be suppressed.
171 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172
173 /// \brief When valid, a source range to which the cursor should restrict
174 /// its search.
175 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000177 // FIXME: Eventually remove. This part of a hack to support proper
178 // iteration over all Decls contained lexically within an ObjC container.
179 DeclContext::decl_iterator *DI_current;
180 DeclContext::decl_iterator DE_current;
181
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000183 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000184 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
186 /// \brief Determine whether this particular source range comes before, comes
187 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000189 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000190 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
191
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000192 class SetParentRAII {
193 CXCursor &Parent;
194 Decl *&StmtParent;
195 CXCursor OldParent;
196
197 public:
198 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
199 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
200 {
201 Parent = NewParent;
202 if (clang_isDeclaration(Parent.kind))
203 StmtParent = getCursorDecl(Parent);
204 }
205
206 ~SetParentRAII() {
207 Parent = OldParent;
208 if (clang_isDeclaration(Parent.kind))
209 StmtParent = getCursorDecl(Parent);
210 }
211 };
212
Steve Naroff89922f82009-08-31 00:59:03 +0000213public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
215 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000216 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000218 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
219 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 {
221 Parent.kind = CXCursor_NoDeclFound;
222 Parent.data[0] = 0;
223 Parent.data[1] = 0;
224 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000225 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000226 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000227
Ted Kremenekab979612010-11-11 08:05:23 +0000228 ASTUnit *getASTUnit() const { return TU; }
229
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000230 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000231
232 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
233 getPreprocessedEntities();
234
Douglas Gregorb1373d02010-01-20 20:59:29 +0000235 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000237 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000238 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000239 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000240 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000241 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000243 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
244 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000245 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000246 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000247 bool VisitClassTemplatePartialSpecializationDecl(
248 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000249 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000250 bool VisitEnumConstantDecl(EnumConstantDecl *D);
251 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
252 bool VisitFunctionDecl(FunctionDecl *ND);
253 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000254 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000255 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000256 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000257 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000258 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000259 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
260 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
261 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
262 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000263 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000264 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
265 bool VisitObjCImplDecl(ObjCImplDecl *D);
266 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
267 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000268 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
269 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
270 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000271 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000272 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000273 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000274 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000275 bool VisitUsingDecl(UsingDecl *D);
276 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
277 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000278
Douglas Gregor01829d32010-08-31 14:41:23 +0000279 // Name visitor
280 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000281 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000282
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000283 // Template visitors
284 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000285 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
287
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000288 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000289 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000290 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000291 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000292 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
293 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000294 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000295 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000296 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000297 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
298 bool VisitPointerTypeLoc(PointerTypeLoc TL);
299 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
300 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
301 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
302 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000303 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000304 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000305 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000306 // FIXME: Implement visitors here when the unimplemented TypeLocs get
307 // implemented
308 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
309 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000310
Douglas Gregora59e3902010-01-21 23:27:09 +0000311 // Statement visitors
312 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000313
Douglas Gregor336fd812010-01-23 00:40:08 +0000314 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000315 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000316 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000317 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000318 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
319 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000320 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000321 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000322 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000323 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000324 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000325 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000326 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000327 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000328 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000329 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000330 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000331
332#define DATA_RECURSIVE_VISIT(NAME)\
333bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
334 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenek73d15c42010-11-13 01:09:29 +0000335 DATA_RECURSIVE_VISIT(BlockExpr)
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000336 DATA_RECURSIVE_VISIT(CompoundLiteralExpr)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000337 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000338 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenek73d15c42010-11-13 01:09:29 +0000339 DATA_RECURSIVE_VISIT(CXXTemporaryObjectExpr)
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000340 DATA_RECURSIVE_VISIT(DeclRefExpr)
Ted Kremenek035dc412010-11-13 00:36:50 +0000341 DATA_RECURSIVE_VISIT(DeclStmt)
Ted Kremenek99394242010-11-12 22:24:57 +0000342 DATA_RECURSIVE_VISIT(ExplicitCastExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000343 DATA_RECURSIVE_VISIT(DoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000344 DATA_RECURSIVE_VISIT(IfStmt)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000345 DATA_RECURSIVE_VISIT(InitListExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000346 DATA_RECURSIVE_VISIT(ForStmt)
Ted Kremenek1876bf62010-11-13 00:58:15 +0000347 DATA_RECURSIVE_VISIT(GotoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000348 DATA_RECURSIVE_VISIT(MemberExpr)
Ted Kremenek73d15c42010-11-13 01:09:29 +0000349 DATA_RECURSIVE_VISIT(ObjCEncodeExpr)
Ted Kremenekc373e3c2010-11-12 22:24:55 +0000350 DATA_RECURSIVE_VISIT(ObjCMessageExpr)
Ted Kremenek60458782010-11-12 21:34:16 +0000351 DATA_RECURSIVE_VISIT(OverloadExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000352 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekbb677132010-11-12 18:27:04 +0000353 DATA_RECURSIVE_VISIT(WhileStmt)
Ted Kremenek60458782010-11-12 21:34:16 +0000354 DATA_RECURSIVE_VISIT(UnresolvedMemberExpr)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000355
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000356 // Data-recursive visitor functions.
357 bool IsInRegionOfInterest(CXCursor C);
358 bool RunVisitorWorkList(VisitorWorkList &WL);
359 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
360 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000361};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000362
Ted Kremenekab188932010-01-05 19:32:54 +0000363} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000364
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000365static SourceRange getRawCursorExtent(CXCursor C);
366
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
369}
370
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \brief Visit the given cursor and, if requested by the visitor,
372/// its children.
373///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374/// \param Cursor the cursor to visit.
375///
376/// \param CheckRegionOfInterest if true, then the caller already checked that
377/// this cursor is within the region of interest.
378///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379/// \returns true if the visitation should be aborted, false if it
380/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382 if (clang_isInvalid(Cursor.kind))
383 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000384
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 if (clang_isDeclaration(Cursor.kind)) {
386 Decl *D = getCursorDecl(Cursor);
387 assert(D && "Invalid declaration cursor");
388 if (D->getPCHLevel() > MaxPCHLevel)
389 return false;
390
391 if (D->isImplicit())
392 return false;
393 }
394
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000395 // If we have a range of interest, and this cursor doesn't intersect with it,
396 // we're done.
397 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000398 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000399 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000400 return false;
401 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403 switch (Visitor(Cursor, Parent, ClientData)) {
404 case CXChildVisit_Break:
405 return true;
406
407 case CXChildVisit_Continue:
408 return false;
409
410 case CXChildVisit_Recurse:
411 return VisitChildren(Cursor);
412 }
413
Douglas Gregorfd643772010-01-25 16:45:46 +0000414 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000415}
416
Douglas Gregor788f5a12010-03-20 00:41:21 +0000417std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
418CursorVisitor::getPreprocessedEntities() {
419 PreprocessingRecord &PPRec
420 = *TU->getPreprocessor().getPreprocessingRecord();
421
422 bool OnlyLocalDecls
423 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
424
425 // There is no region of interest; we have to walk everything.
426 if (RegionOfInterest.isInvalid())
427 return std::make_pair(PPRec.begin(OnlyLocalDecls),
428 PPRec.end(OnlyLocalDecls));
429
430 // Find the file in which the region of interest lands.
431 SourceManager &SM = TU->getSourceManager();
432 std::pair<FileID, unsigned> Begin
433 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
434 std::pair<FileID, unsigned> End
435 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
436
437 // The region of interest spans files; we have to walk everything.
438 if (Begin.first != End.first)
439 return std::make_pair(PPRec.begin(OnlyLocalDecls),
440 PPRec.end(OnlyLocalDecls));
441
442 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
443 = TU->getPreprocessedEntitiesByFile();
444 if (ByFileMap.empty()) {
445 // Build the mapping from files to sets of preprocessed entities.
446 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
447 EEnd = PPRec.end(OnlyLocalDecls);
448 E != EEnd; ++E) {
449 std::pair<FileID, unsigned> P
450 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
451 ByFileMap[P.first].push_back(*E);
452 }
453 }
454
455 return std::make_pair(ByFileMap[Begin.first].begin(),
456 ByFileMap[Begin.first].end());
457}
458
Douglas Gregorb1373d02010-01-20 20:59:29 +0000459/// \brief Visit the children of the given cursor.
460///
461/// \returns true if the visitation should be aborted, false if it
462/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000464 if (clang_isReference(Cursor.kind)) {
465 // By definition, references have no children.
466 return false;
467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
469 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000471 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473 if (clang_isDeclaration(Cursor.kind)) {
474 Decl *D = getCursorDecl(Cursor);
475 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000476 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478
Douglas Gregora59e3902010-01-21 23:27:09 +0000479 if (clang_isStatement(Cursor.kind))
480 return Visit(getCursorStmt(Cursor));
481 if (clang_isExpression(Cursor.kind))
482 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000483
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000485 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000486 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
487 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000488 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
489 TLEnd = CXXUnit->top_level_end();
490 TL != TLEnd; ++TL) {
491 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000492 return true;
493 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 } else if (VisitDeclContext(
495 CXXUnit->getASTContext().getTranslationUnitDecl()))
496 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000497
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000499 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 // FIXME: Once we have the ability to deserialize a preprocessing record,
501 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000502 PreprocessingRecord::iterator E, EEnd;
503 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
505 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
506 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000507
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 continue;
509 }
510
511 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
512 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
513 return true;
514
515 continue;
516 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000517
518 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
519 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
520 return true;
521
522 continue;
523 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000524 }
525 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000526 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000528
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000530 return false;
531}
532
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000534 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
535 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000536
Ted Kremenek664cffd2010-07-22 11:30:19 +0000537 if (Stmt *Body = B->getBody())
538 return Visit(MakeCXCursor(Body, StmtParent, TU));
539
540 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000541}
542
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
544 if (RegionOfInterest.isValid()) {
545 SourceRange Range = getRawCursorExtent(Cursor);
546 if (Range.isInvalid())
547 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000548
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000549 switch (CompareRegionOfInterest(Range)) {
550 case RangeBefore:
551 // This declaration comes before the region of interest; skip it.
552 return llvm::Optional<bool>();
553
554 case RangeAfter:
555 // This declaration comes after the region of interest; we're done.
556 return false;
557
558 case RangeOverlap:
559 // This declaration overlaps the region of interest; visit it.
560 break;
561 }
562 }
563 return true;
564}
565
566bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
567 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
568
569 // FIXME: Eventually remove. This part of a hack to support proper
570 // iteration over all Decls contained lexically within an ObjC container.
571 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
572 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
573
574 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000575 Decl *D = *I;
576 if (D->getLexicalDeclContext() != DC)
577 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000578 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000579 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
580 if (!V.hasValue())
581 continue;
582 if (!V.getValue())
583 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585 return true;
586 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000588}
589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
591 llvm_unreachable("Translation units are visited directly by Visit()");
592 return false;
593}
594
595bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
596 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
597 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599 return false;
600}
601
602bool CursorVisitor::VisitTagDecl(TagDecl *D) {
603 return VisitDeclContext(D);
604}
605
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000606bool CursorVisitor::VisitClassTemplateSpecializationDecl(
607 ClassTemplateSpecializationDecl *D) {
608 bool ShouldVisitBody = false;
609 switch (D->getSpecializationKind()) {
610 case TSK_Undeclared:
611 case TSK_ImplicitInstantiation:
612 // Nothing to visit
613 return false;
614
615 case TSK_ExplicitInstantiationDeclaration:
616 case TSK_ExplicitInstantiationDefinition:
617 break;
618
619 case TSK_ExplicitSpecialization:
620 ShouldVisitBody = true;
621 break;
622 }
623
624 // Visit the template arguments used in the specialization.
625 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
626 TypeLoc TL = SpecType->getTypeLoc();
627 if (TemplateSpecializationTypeLoc *TSTLoc
628 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
629 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
630 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
631 return true;
632 }
633 }
634
635 if (ShouldVisitBody && VisitCXXRecordDecl(D))
636 return true;
637
638 return false;
639}
640
Douglas Gregor74dbe642010-08-31 19:31:58 +0000641bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
642 ClassTemplatePartialSpecializationDecl *D) {
643 // FIXME: Visit the "outer" template parameter lists on the TagDecl
644 // before visiting these template parameters.
645 if (VisitTemplateParameters(D->getTemplateParameters()))
646 return true;
647
648 // Visit the partial specialization arguments.
649 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
650 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
651 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
652 return true;
653
654 return VisitCXXRecordDecl(D);
655}
656
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000657bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000658 // Visit the default argument.
659 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
660 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
661 if (Visit(DefArg->getTypeLoc()))
662 return true;
663
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000664 return false;
665}
666
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000667bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
668 if (Expr *Init = D->getInitExpr())
669 return Visit(MakeCXCursor(Init, StmtParent, TU));
670 return false;
671}
672
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000673bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
674 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
675 if (Visit(TSInfo->getTypeLoc()))
676 return true;
677
678 return false;
679}
680
Douglas Gregora67e03f2010-09-09 21:42:20 +0000681/// \brief Compare two base or member initializers based on their source order.
682static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
683 CXXBaseOrMemberInitializer const * const *X
684 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
685 CXXBaseOrMemberInitializer const * const *Y
686 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
687
688 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
689 return -1;
690 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
691 return 1;
692 else
693 return 0;
694}
695
Douglas Gregorb1373d02010-01-20 20:59:29 +0000696bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000697 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
698 // Visit the function declaration's syntactic components in the order
699 // written. This requires a bit of work.
700 TypeLoc TL = TSInfo->getTypeLoc();
701 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
702
703 // If we have a function declared directly (without the use of a typedef),
704 // visit just the return type. Otherwise, just visit the function's type
705 // now.
706 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
707 (!FTL && Visit(TL)))
708 return true;
709
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000710 // Visit the nested-name-specifier, if present.
711 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
712 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
713 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000714
715 // Visit the declaration name.
716 if (VisitDeclarationNameInfo(ND->getNameInfo()))
717 return true;
718
719 // FIXME: Visit explicitly-specified template arguments!
720
721 // Visit the function parameters, if we have a function type.
722 if (FTL && VisitFunctionTypeLoc(*FTL, true))
723 return true;
724
725 // FIXME: Attributes?
726 }
727
Douglas Gregora67e03f2010-09-09 21:42:20 +0000728 if (ND->isThisDeclarationADefinition()) {
729 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
730 // Find the initializers that were written in the source.
731 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
732 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
733 IEnd = Constructor->init_end();
734 I != IEnd; ++I) {
735 if (!(*I)->isWritten())
736 continue;
737
738 WrittenInits.push_back(*I);
739 }
740
741 // Sort the initializers in source order
742 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
743 &CompareCXXBaseOrMemberInitializers);
744
745 // Visit the initializers in source order
746 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
747 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
748 if (Init->isMemberInitializer()) {
749 if (Visit(MakeCursorMemberRef(Init->getMember(),
750 Init->getMemberLocation(), TU)))
751 return true;
752 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
753 if (Visit(BaseInfo->getTypeLoc()))
754 return true;
755 }
756
757 // Visit the initializer value.
758 if (Expr *Initializer = Init->getInit())
759 if (Visit(MakeCXCursor(Initializer, ND, TU)))
760 return true;
761 }
762 }
763
764 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
765 return true;
766 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000767
Douglas Gregorb1373d02010-01-20 20:59:29 +0000768 return false;
769}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000770
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000771bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
772 if (VisitDeclaratorDecl(D))
773 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000774
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000775 if (Expr *BitWidth = D->getBitWidth())
776 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000778 return false;
779}
780
781bool CursorVisitor::VisitVarDecl(VarDecl *D) {
782 if (VisitDeclaratorDecl(D))
783 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785 if (Expr *Init = D->getInit())
786 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788 return false;
789}
790
Douglas Gregor84b51d72010-09-01 20:16:53 +0000791bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
792 if (VisitDeclaratorDecl(D))
793 return true;
794
795 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
796 if (Expr *DefArg = D->getDefaultArgument())
797 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
798
799 return false;
800}
801
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000802bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
803 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
804 // before visiting these template parameters.
805 if (VisitTemplateParameters(D->getTemplateParameters()))
806 return true;
807
808 return VisitFunctionDecl(D->getTemplatedDecl());
809}
810
Douglas Gregor39d6f072010-08-31 19:02:00 +0000811bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
812 // FIXME: Visit the "outer" template parameter lists on the TagDecl
813 // before visiting these template parameters.
814 if (VisitTemplateParameters(D->getTemplateParameters()))
815 return true;
816
817 return VisitCXXRecordDecl(D->getTemplatedDecl());
818}
819
Douglas Gregor84b51d72010-09-01 20:16:53 +0000820bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
821 if (VisitTemplateParameters(D->getTemplateParameters()))
822 return true;
823
824 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
825 VisitTemplateArgumentLoc(D->getDefaultArgument()))
826 return true;
827
828 return false;
829}
830
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000831bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000832 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
833 if (Visit(TSInfo->getTypeLoc()))
834 return true;
835
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000836 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000837 PEnd = ND->param_end();
838 P != PEnd; ++P) {
839 if (Visit(MakeCXCursor(*P, TU)))
840 return true;
841 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 if (ND->isThisDeclarationADefinition() &&
844 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
845 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000846
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000847 return false;
848}
849
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000850namespace {
851 struct ContainerDeclsSort {
852 SourceManager &SM;
853 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
854 bool operator()(Decl *A, Decl *B) {
855 SourceLocation L_A = A->getLocStart();
856 SourceLocation L_B = B->getLocStart();
857 assert(L_A.isValid() && L_B.isValid());
858 return SM.isBeforeInTranslationUnit(L_A, L_B);
859 }
860 };
861}
862
Douglas Gregora59e3902010-01-21 23:27:09 +0000863bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000864 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
865 // an @implementation can lexically contain Decls that are not properly
866 // nested in the AST. When we identify such cases, we need to retrofit
867 // this nesting here.
868 if (!DI_current)
869 return VisitDeclContext(D);
870
871 // Scan the Decls that immediately come after the container
872 // in the current DeclContext. If any fall within the
873 // container's lexical region, stash them into a vector
874 // for later processing.
875 llvm::SmallVector<Decl *, 24> DeclsInContainer;
876 SourceLocation EndLoc = D->getSourceRange().getEnd();
877 SourceManager &SM = TU->getSourceManager();
878 if (EndLoc.isValid()) {
879 DeclContext::decl_iterator next = *DI_current;
880 while (++next != DE_current) {
881 Decl *D_next = *next;
882 if (!D_next)
883 break;
884 SourceLocation L = D_next->getLocStart();
885 if (!L.isValid())
886 break;
887 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
888 *DI_current = next;
889 DeclsInContainer.push_back(D_next);
890 continue;
891 }
892 break;
893 }
894 }
895
896 // The common case.
897 if (DeclsInContainer.empty())
898 return VisitDeclContext(D);
899
900 // Get all the Decls in the DeclContext, and sort them with the
901 // additional ones we've collected. Then visit them.
902 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
903 I!=E; ++I) {
904 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000905 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
906 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000907 continue;
908 DeclsInContainer.push_back(subDecl);
909 }
910
911 // Now sort the Decls so that they appear in lexical order.
912 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
913 ContainerDeclsSort(SM));
914
915 // Now visit the decls.
916 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
917 E = DeclsInContainer.end(); I != E; ++I) {
918 CXCursor Cursor = MakeCXCursor(*I, TU);
919 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
920 if (!V.hasValue())
921 continue;
922 if (!V.getValue())
923 return false;
924 if (Visit(Cursor, true))
925 return true;
926 }
927 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000928}
929
Douglas Gregorb1373d02010-01-20 20:59:29 +0000930bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000931 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
932 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000935 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
936 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
937 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000938 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000939 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000940
Douglas Gregora59e3902010-01-21 23:27:09 +0000941 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000942}
943
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000944bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
945 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
946 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
947 E = PID->protocol_end(); I != E; ++I, ++PL)
948 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000951 return VisitObjCContainerDecl(PID);
952}
953
Ted Kremenek23173d72010-05-18 21:09:07 +0000954bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000955 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000956 return true;
957
Ted Kremenek23173d72010-05-18 21:09:07 +0000958 // FIXME: This implements a workaround with @property declarations also being
959 // installed in the DeclContext for the @interface. Eventually this code
960 // should be removed.
961 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
962 if (!CDecl || !CDecl->IsClassExtension())
963 return false;
964
965 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
966 if (!ID)
967 return false;
968
969 IdentifierInfo *PropertyId = PD->getIdentifier();
970 ObjCPropertyDecl *prevDecl =
971 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
972
973 if (!prevDecl)
974 return false;
975
976 // Visit synthesized methods since they will be skipped when visiting
977 // the @interface.
978 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000979 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000980 if (Visit(MakeCXCursor(MD, TU)))
981 return true;
982
983 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000984 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000985 if (Visit(MakeCXCursor(MD, TU)))
986 return true;
987
988 return false;
989}
990
Douglas Gregorb1373d02010-01-20 20:59:29 +0000991bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000992 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000993 if (D->getSuperClass() &&
994 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000996 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000997 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000999 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1000 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1001 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001002 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001004
Douglas Gregora59e3902010-01-21 23:27:09 +00001005 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001006}
1007
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001008bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1009 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001010}
1011
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001012bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001013 // 'ID' could be null when dealing with invalid code.
1014 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1015 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1016 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001017
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018 return VisitObjCImplDecl(D);
1019}
1020
1021bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1022#if 0
1023 // Issue callbacks for super class.
1024 // FIXME: No source location information!
1025 if (D->getSuperClass() &&
1026 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028 TU)))
1029 return true;
1030#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001032 return VisitObjCImplDecl(D);
1033}
1034
1035bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1036 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1037 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1038 E = D->protocol_end();
1039 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001040 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001041 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042
1043 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001044}
1045
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1047 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1048 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1049 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001050
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001051 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001052}
1053
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001054bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1055 return VisitDeclContext(D);
1056}
1057
Douglas Gregor69319002010-08-31 23:48:11 +00001058bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001059 // Visit nested-name-specifier.
1060 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1061 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1062 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001063
1064 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1065 D->getTargetNameLoc(), TU));
1066}
1067
Douglas Gregor7e242562010-09-01 19:52:22 +00001068bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001069 // Visit nested-name-specifier.
1070 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1071 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1072 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001073
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001074 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1075 return true;
1076
Douglas Gregor7e242562010-09-01 19:52:22 +00001077 return VisitDeclarationNameInfo(D->getNameInfo());
1078}
1079
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001080bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001081 // Visit nested-name-specifier.
1082 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1083 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1084 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001085
1086 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1087 D->getIdentLocation(), TU));
1088}
1089
Douglas Gregor7e242562010-09-01 19:52:22 +00001090bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001091 // Visit nested-name-specifier.
1092 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1093 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1094 return true;
1095
Douglas Gregor7e242562010-09-01 19:52:22 +00001096 return VisitDeclarationNameInfo(D->getNameInfo());
1097}
1098
1099bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1100 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001101 // Visit nested-name-specifier.
1102 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1103 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1104 return true;
1105
Douglas Gregor7e242562010-09-01 19:52:22 +00001106 return false;
1107}
1108
Douglas Gregor01829d32010-08-31 14:41:23 +00001109bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1110 switch (Name.getName().getNameKind()) {
1111 case clang::DeclarationName::Identifier:
1112 case clang::DeclarationName::CXXLiteralOperatorName:
1113 case clang::DeclarationName::CXXOperatorName:
1114 case clang::DeclarationName::CXXUsingDirective:
1115 return false;
1116
1117 case clang::DeclarationName::CXXConstructorName:
1118 case clang::DeclarationName::CXXDestructorName:
1119 case clang::DeclarationName::CXXConversionFunctionName:
1120 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1121 return Visit(TSInfo->getTypeLoc());
1122 return false;
1123
1124 case clang::DeclarationName::ObjCZeroArgSelector:
1125 case clang::DeclarationName::ObjCOneArgSelector:
1126 case clang::DeclarationName::ObjCMultiArgSelector:
1127 // FIXME: Per-identifier location info?
1128 return false;
1129 }
1130
1131 return false;
1132}
1133
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001134bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1135 SourceRange Range) {
1136 // FIXME: This whole routine is a hack to work around the lack of proper
1137 // source information in nested-name-specifiers (PR5791). Since we do have
1138 // a beginning source location, we can visit the first component of the
1139 // nested-name-specifier, if it's a single-token component.
1140 if (!NNS)
1141 return false;
1142
1143 // Get the first component in the nested-name-specifier.
1144 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1145 NNS = Prefix;
1146
1147 switch (NNS->getKind()) {
1148 case NestedNameSpecifier::Namespace:
1149 // FIXME: The token at this source location might actually have been a
1150 // namespace alias, but we don't model that. Lame!
1151 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1152 TU));
1153
1154 case NestedNameSpecifier::TypeSpec: {
1155 // If the type has a form where we know that the beginning of the source
1156 // range matches up with a reference cursor. Visit the appropriate reference
1157 // cursor.
1158 Type *T = NNS->getAsType();
1159 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1160 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1161 if (const TagType *Tag = dyn_cast<TagType>(T))
1162 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1163 if (const TemplateSpecializationType *TST
1164 = dyn_cast<TemplateSpecializationType>(T))
1165 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1166 break;
1167 }
1168
1169 case NestedNameSpecifier::TypeSpecWithTemplate:
1170 case NestedNameSpecifier::Global:
1171 case NestedNameSpecifier::Identifier:
1172 break;
1173 }
1174
1175 return false;
1176}
1177
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001178bool CursorVisitor::VisitTemplateParameters(
1179 const TemplateParameterList *Params) {
1180 if (!Params)
1181 return false;
1182
1183 for (TemplateParameterList::const_iterator P = Params->begin(),
1184 PEnd = Params->end();
1185 P != PEnd; ++P) {
1186 if (Visit(MakeCXCursor(*P, TU)))
1187 return true;
1188 }
1189
1190 return false;
1191}
1192
Douglas Gregor0b36e612010-08-31 20:37:03 +00001193bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1194 switch (Name.getKind()) {
1195 case TemplateName::Template:
1196 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1197
1198 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001199 // Visit the overloaded template set.
1200 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1201 return true;
1202
Douglas Gregor0b36e612010-08-31 20:37:03 +00001203 return false;
1204
1205 case TemplateName::DependentTemplate:
1206 // FIXME: Visit nested-name-specifier.
1207 return false;
1208
1209 case TemplateName::QualifiedTemplate:
1210 // FIXME: Visit nested-name-specifier.
1211 return Visit(MakeCursorTemplateRef(
1212 Name.getAsQualifiedTemplateName()->getDecl(),
1213 Loc, TU));
1214 }
1215
1216 return false;
1217}
1218
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001219bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1220 switch (TAL.getArgument().getKind()) {
1221 case TemplateArgument::Null:
1222 case TemplateArgument::Integral:
1223 return false;
1224
1225 case TemplateArgument::Pack:
1226 // FIXME: Implement when variadic templates come along.
1227 return false;
1228
1229 case TemplateArgument::Type:
1230 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1231 return Visit(TSInfo->getTypeLoc());
1232 return false;
1233
1234 case TemplateArgument::Declaration:
1235 if (Expr *E = TAL.getSourceDeclExpression())
1236 return Visit(MakeCXCursor(E, StmtParent, TU));
1237 return false;
1238
1239 case TemplateArgument::Expression:
1240 if (Expr *E = TAL.getSourceExpression())
1241 return Visit(MakeCXCursor(E, StmtParent, TU));
1242 return false;
1243
1244 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001245 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1246 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001247 }
1248
1249 return false;
1250}
1251
Ted Kremeneka0536d82010-05-07 01:04:29 +00001252bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1253 return VisitDeclContext(D);
1254}
1255
Douglas Gregor01829d32010-08-31 14:41:23 +00001256bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1257 return Visit(TL.getUnqualifiedLoc());
1258}
1259
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001260bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1261 ASTContext &Context = TU->getASTContext();
1262
1263 // Some builtin types (such as Objective-C's "id", "sel", and
1264 // "Class") have associated declarations. Create cursors for those.
1265 QualType VisitType;
1266 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001267 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001268 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001269 case BuiltinType::Char_U:
1270 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001271 case BuiltinType::Char16:
1272 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001273 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001274 case BuiltinType::UInt:
1275 case BuiltinType::ULong:
1276 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277 case BuiltinType::UInt128:
1278 case BuiltinType::Char_S:
1279 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001280 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001281 case BuiltinType::Short:
1282 case BuiltinType::Int:
1283 case BuiltinType::Long:
1284 case BuiltinType::LongLong:
1285 case BuiltinType::Int128:
1286 case BuiltinType::Float:
1287 case BuiltinType::Double:
1288 case BuiltinType::LongDouble:
1289 case BuiltinType::NullPtr:
1290 case BuiltinType::Overload:
1291 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001292 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001293
1294 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001295 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001296
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001297 case BuiltinType::ObjCId:
1298 VisitType = Context.getObjCIdType();
1299 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001300
1301 case BuiltinType::ObjCClass:
1302 VisitType = Context.getObjCClassType();
1303 break;
1304
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001305 case BuiltinType::ObjCSel:
1306 VisitType = Context.getObjCSelType();
1307 break;
1308 }
1309
1310 if (!VisitType.isNull()) {
1311 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001312 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001313 TU));
1314 }
1315
1316 return false;
1317}
1318
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001319bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1320 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1321}
1322
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1324 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1325}
1326
1327bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1328 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1329}
1330
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001331bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001332 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001333 // no context information with which we can match up the depth/index in the
1334 // type to the appropriate
1335 return false;
1336}
1337
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1339 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1340 return true;
1341
John McCallc12c5bb2010-05-15 11:32:37 +00001342 return false;
1343}
1344
1345bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1346 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1347 return true;
1348
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001349 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1350 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1351 TU)))
1352 return true;
1353 }
1354
1355 return false;
1356}
1357
1358bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001359 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001360}
1361
1362bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1363 return Visit(TL.getPointeeLoc());
1364}
1365
1366bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1367 return Visit(TL.getPointeeLoc());
1368}
1369
1370bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1371 return Visit(TL.getPointeeLoc());
1372}
1373
1374bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001375 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376}
1377
1378bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001379 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380}
1381
Douglas Gregor01829d32010-08-31 14:41:23 +00001382bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1383 bool SkipResultType) {
1384 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385 return true;
1386
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001388 if (Decl *D = TL.getArg(I))
1389 if (Visit(MakeCXCursor(D, TU)))
1390 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001391
1392 return false;
1393}
1394
1395bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1396 if (Visit(TL.getElementLoc()))
1397 return true;
1398
1399 if (Expr *Size = TL.getSizeExpr())
1400 return Visit(MakeCXCursor(Size, StmtParent, TU));
1401
1402 return false;
1403}
1404
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001405bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1406 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001407 // Visit the template name.
1408 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1409 TL.getTemplateNameLoc()))
1410 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001411
1412 // Visit the template arguments.
1413 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1414 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1415 return true;
1416
1417 return false;
1418}
1419
Douglas Gregor2332c112010-01-21 20:48:56 +00001420bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1421 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1422}
1423
1424bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1425 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1426 return Visit(TSInfo->getTypeLoc());
1427
1428 return false;
1429}
1430
Douglas Gregora59e3902010-01-21 23:27:09 +00001431bool CursorVisitor::VisitStmt(Stmt *S) {
1432 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1433 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001434 if (Stmt *C = *Child)
1435 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1436 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438
Douglas Gregora59e3902010-01-21 23:27:09 +00001439 return false;
1440}
1441
Ted Kremenek3064ef92010-08-27 21:34:58 +00001442bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1443 if (D->isDefinition()) {
1444 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1445 E = D->bases_end(); I != E; ++I) {
1446 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1447 return true;
1448 }
1449 }
1450
1451 return VisitTagDecl(D);
1452}
1453
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001454bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001455 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001456 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1457 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001458
1459 // Visit the components of the offsetof expression.
1460 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1461 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1462 const OffsetOfNode &Node = E->getComponent(I);
1463 switch (Node.getKind()) {
1464 case OffsetOfNode::Array:
1465 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1466 StmtParent, TU)))
1467 return true;
1468 break;
1469
1470 case OffsetOfNode::Field:
1471 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1472 TU)))
1473 return true;
1474 break;
1475
1476 case OffsetOfNode::Identifier:
1477 case OffsetOfNode::Base:
1478 continue;
1479 }
1480 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001481
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001482 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001483}
1484
Douglas Gregor336fd812010-01-23 00:40:08 +00001485bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1486 if (E->isArgumentType()) {
1487 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1488 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001489
Douglas Gregor336fd812010-01-23 00:40:08 +00001490 return false;
1491 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001492
Douglas Gregor336fd812010-01-23 00:40:08 +00001493 return VisitExpr(E);
1494}
1495
Douglas Gregor36897b02010-09-10 00:22:18 +00001496bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1497 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1498}
1499
Douglas Gregor648220e2010-08-10 15:02:34 +00001500bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1501 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1502 Visit(E->getArgTInfo2()->getTypeLoc());
1503}
1504
1505bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1506 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1507 return true;
1508
1509 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1510}
1511
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001512bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1513 // Visit the designators.
1514 typedef DesignatedInitExpr::Designator Designator;
1515 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1516 DEnd = E->designators_end();
1517 D != DEnd; ++D) {
1518 if (D->isFieldDesignator()) {
1519 if (FieldDecl *Field = D->getField())
1520 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1521 return true;
1522
1523 continue;
1524 }
1525
1526 if (D->isArrayDesignator()) {
1527 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1528 return true;
1529
1530 continue;
1531 }
1532
1533 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1534 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1535 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1536 return true;
1537 }
1538
1539 // Visit the initializer value itself.
1540 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1541}
1542
Douglas Gregor94802292010-09-02 21:20:16 +00001543bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1544 if (E->isTypeOperand()) {
1545 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1546 return Visit(TSInfo->getTypeLoc());
1547
1548 return false;
1549 }
1550
1551 return VisitExpr(E);
1552}
1553
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001554bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1555 if (E->isTypeOperand()) {
1556 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1557 return Visit(TSInfo->getTypeLoc());
1558
1559 return false;
1560 }
1561
1562 return VisitExpr(E);
1563}
1564
Douglas Gregorab6677e2010-09-08 00:15:04 +00001565bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1566 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1567 return Visit(TSInfo->getTypeLoc());
1568
1569 return false;
1570}
1571
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001572bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1573 // Visit placement arguments.
1574 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1575 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1576 return true;
1577
1578 // Visit the allocated type.
1579 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1580 if (Visit(TSInfo->getTypeLoc()))
1581 return true;
1582
1583 // Visit the array size, if any.
1584 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1585 return true;
1586
1587 // Visit the initializer or constructor arguments.
1588 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1589 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1590 return true;
1591
1592 return false;
1593}
1594
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001595bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1596 // Visit base expression.
1597 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1598 return true;
1599
1600 // Visit the nested-name-specifier.
1601 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1602 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1603 return true;
1604
1605 // Visit the scope type that looks disturbingly like the nested-name-specifier
1606 // but isn't.
1607 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1608 if (Visit(TSInfo->getTypeLoc()))
1609 return true;
1610
1611 // Visit the name of the type being destroyed.
1612 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1613 if (Visit(TSInfo->getTypeLoc()))
1614 return true;
1615
1616 return false;
1617}
1618
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001619bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1620 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1621}
1622
Douglas Gregorbfebed22010-09-03 17:24:10 +00001623bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1624 DependentScopeDeclRefExpr *E) {
1625 // Visit the nested-name-specifier.
1626 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1627 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1628 return true;
1629
1630 // Visit the declaration name.
1631 if (VisitDeclarationNameInfo(E->getNameInfo()))
1632 return true;
1633
1634 // Visit the explicitly-specified template arguments.
1635 if (const ExplicitTemplateArgumentList *ArgList
1636 = E->getOptionalExplicitTemplateArgs()) {
1637 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1638 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1639 Arg != ArgEnd; ++Arg) {
1640 if (VisitTemplateArgumentLoc(*Arg))
1641 return true;
1642 }
1643 }
1644
1645 return false;
1646}
1647
Douglas Gregorab6677e2010-09-08 00:15:04 +00001648bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1649 CXXUnresolvedConstructExpr *E) {
1650 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1651 if (Visit(TSInfo->getTypeLoc()))
1652 return true;
1653
1654 return VisitExpr(E);
1655}
1656
Douglas Gregor25d63622010-09-03 17:35:34 +00001657bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1658 CXXDependentScopeMemberExpr *E) {
1659 // Visit the base expression, if there is one.
1660 if (!E->isImplicitAccess() &&
1661 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1662 return true;
1663
1664 // Visit the nested-name-specifier.
1665 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1666 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1667 return true;
1668
1669 // Visit the declaration name.
1670 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1671 return true;
1672
1673 // Visit the explicitly-specified template arguments.
1674 if (const ExplicitTemplateArgumentList *ArgList
1675 = E->getOptionalExplicitTemplateArgs()) {
1676 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1677 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1678 Arg != ArgEnd; ++Arg) {
1679 if (VisitTemplateArgumentLoc(*Arg))
1680 return true;
1681 }
1682 }
1683
1684 return false;
1685}
1686
Ted Kremenek09dfa372010-02-18 05:46:33 +00001687bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001688 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1689 i != e; ++i)
1690 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001691 return true;
1692
1693 return false;
1694}
1695
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001696//===----------------------------------------------------------------------===//
1697// Data-recursive visitor methods.
1698//===----------------------------------------------------------------------===//
1699
Ted Kremenek28a71942010-11-13 00:36:47 +00001700namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001701#define DEF_JOB(NAME, DATA, KIND)\
1702class NAME : public VisitorJob {\
1703public:\
1704 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1705 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1706 DATA *get() const { return static_cast<DATA*>(dataA); }\
1707};
1708
1709DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1710DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001711DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001712DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1713#undef DEF_JOB
1714
1715class DeclVisit : public VisitorJob {
1716public:
1717 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1718 VisitorJob(parent, VisitorJob::DeclVisitKind,
1719 d, isFirst ? (void*) 1 : (void*) 0) {}
1720 static bool classof(const VisitorJob *VJ) {
1721 return VJ->getKind () == DeclVisitKind;
1722 }
1723 Decl *get() { return static_cast<Decl*>(dataA);}
1724 bool isFirst() const { return dataB ? true : false; }
1725};
1726
1727class TypeLocVisit : public VisitorJob {
1728public:
1729 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1730 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1731 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1732
1733 static bool classof(const VisitorJob *VJ) {
1734 return VJ->getKind() == TypeLocVisitKind;
1735 }
1736
1737 TypeLoc get() {
1738 QualType T = QualType::getFromOpaquePtr(dataA);
1739 return TypeLoc(T, dataB);
1740 }
1741};
1742
Ted Kremenek28a71942010-11-13 00:36:47 +00001743class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1744 VisitorWorkList &WL;
1745 CXCursor Parent;
1746public:
1747 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1748 : WL(wl), Parent(parent) {}
1749
Ted Kremenek73d15c42010-11-13 01:09:29 +00001750 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001752 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001753 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001754 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001755 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001756 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001757 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1758 void VisitForStmt(ForStmt *FS);
1759 void VisitIfStmt(IfStmt *If);
1760 void VisitInitListExpr(InitListExpr *IE);
1761 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001762 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001763 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1764 void VisitOverloadExpr(OverloadExpr *E);
1765 void VisitStmt(Stmt *S);
1766 void VisitSwitchStmt(SwitchStmt *S);
1767 void VisitWhileStmt(WhileStmt *W);
1768 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1769
1770private:
1771 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001772 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001773 void AddTypeLoc(TypeSourceInfo *TI);
1774 void EnqueueChildren(Stmt *S);
1775};
1776} // end anonyous namespace
1777
1778void EnqueueVisitor::AddStmt(Stmt *S) {
1779 if (S)
1780 WL.push_back(StmtVisit(S, Parent));
1781}
Ted Kremenek035dc412010-11-13 00:36:50 +00001782void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001783 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001784 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001785}
1786void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1787 if (TI)
1788 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1789 }
1790void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001791 unsigned size = WL.size();
1792 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1793 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001794 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001795 }
1796 if (size == WL.size())
1797 return;
1798 // Now reverse the entries we just added. This will match the DFS
1799 // ordering performed by the worklist.
1800 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1801 std::reverse(I, E);
1802}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001803void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1804 AddDecl(B->getBlockDecl());
1805}
Ted Kremenek28a71942010-11-13 00:36:47 +00001806void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1807 EnqueueChildren(E);
1808 AddTypeLoc(E->getTypeSourceInfo());
1809}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001810void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1811 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1812 E = S->body_rend(); I != E; ++I) {
1813 AddStmt(*I);
1814 }
1815}
Ted Kremenek28a71942010-11-13 00:36:47 +00001816void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1817 // Note that we enqueue things in reverse order so that
1818 // they are visited correctly by the DFS.
1819 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
1820 AddStmt(CE->getArg(N-I));
1821 AddStmt(CE->getCallee());
1822 AddStmt(CE->getArg(0));
1823}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001824void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1825 EnqueueChildren(E);
1826 AddTypeLoc(E->getTypeSourceInfo());
1827}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001828void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1829 WL.push_back(DeclRefExprParts(DR, Parent));
1830}
Ted Kremenek035dc412010-11-13 00:36:50 +00001831void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1832 unsigned size = WL.size();
1833 bool isFirst = true;
1834 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1835 D != DEnd; ++D) {
1836 AddDecl(*D, isFirst);
1837 isFirst = false;
1838 }
1839 if (size == WL.size())
1840 return;
1841 // Now reverse the entries we just added. This will match the DFS
1842 // ordering performed by the worklist.
1843 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1844 std::reverse(I, E);
1845}
Ted Kremenek28a71942010-11-13 00:36:47 +00001846void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1847 EnqueueChildren(E);
1848 AddTypeLoc(E->getTypeInfoAsWritten());
1849}
1850void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1851 AddStmt(FS->getBody());
1852 AddStmt(FS->getInc());
1853 AddStmt(FS->getCond());
1854 AddDecl(FS->getConditionVariable());
1855 AddStmt(FS->getInit());
1856}
1857void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1858 AddStmt(If->getElse());
1859 AddStmt(If->getThen());
1860 AddStmt(If->getCond());
1861 AddDecl(If->getConditionVariable());
1862}
1863void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1864 // We care about the syntactic form of the initializer list, only.
1865 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1866 IE = Syntactic;
1867 EnqueueChildren(IE);
1868}
1869void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1870 WL.push_back(MemberExprParts(M, Parent));
1871 AddStmt(M->getBase());
1872}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001873void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1874 AddTypeLoc(E->getEncodedTypeSourceInfo());
1875}
Ted Kremenek28a71942010-11-13 00:36:47 +00001876void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1877 EnqueueChildren(M);
1878 AddTypeLoc(M->getClassReceiverTypeInfo());
1879}
1880void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001881 WL.push_back(OverloadExprParts(E, Parent));
1882}
Ted Kremenek28a71942010-11-13 00:36:47 +00001883void EnqueueVisitor::VisitStmt(Stmt *S) {
1884 EnqueueChildren(S);
1885}
1886void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1887 AddStmt(S->getBody());
1888 AddStmt(S->getCond());
1889 AddDecl(S->getConditionVariable());
1890}
1891void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1892 AddStmt(W->getBody());
1893 AddStmt(W->getCond());
1894 AddDecl(W->getConditionVariable());
1895}
1896void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1897 VisitOverloadExpr(U);
1898 if (!U->isImplicitAccess())
1899 AddStmt(U->getBase());
1900}
Ted Kremenek60458782010-11-12 21:34:16 +00001901
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001902void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001903 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001904}
1905
1906bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1907 if (RegionOfInterest.isValid()) {
1908 SourceRange Range = getRawCursorExtent(C);
1909 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1910 return false;
1911 }
1912 return true;
1913}
1914
1915bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1916 while (!WL.empty()) {
1917 // Dequeue the worklist item.
1918 VisitorJob LI = WL.back(); WL.pop_back();
1919
1920 // Set the Parent field, then back to its old value once we're done.
1921 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1922
1923 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001924 case VisitorJob::DeclVisitKind: {
1925 Decl *D = cast<DeclVisit>(LI).get();
1926 if (!D)
1927 continue;
1928
1929 // For now, perform default visitation for Decls.
Ted Kremenek035dc412010-11-13 00:36:50 +00001930 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(LI).isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001931 return true;
1932
1933 continue;
1934 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001935 case VisitorJob::TypeLocVisitKind: {
1936 // Perform default visitation for TypeLocs.
1937 if (Visit(cast<TypeLocVisit>(LI).get()))
1938 return true;
1939 continue;
1940 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001941 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001942 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001943 if (!S)
1944 continue;
1945
Ted Kremenekf1107452010-11-12 18:26:56 +00001946 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001947 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1948
1949 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001950 case Stmt::GotoStmtClass: {
1951 GotoStmt *GS = cast<GotoStmt>(S);
1952 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1953 GS->getLabelLoc(), TU))) {
1954 return true;
1955 }
1956 continue;
1957 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001958 default: {
Ted Kremenek99394242010-11-12 22:24:57 +00001959 // FIXME: this entire switch stmt will eventually
1960 // go away.
1961 if (!isa<ExplicitCastExpr>(S)) {
1962 // Perform default visitation for other cases.
1963 if (Visit(Cursor))
1964 return true;
1965 continue;
1966 }
1967 // Fall-through.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001968 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001969 case Stmt::BinaryOperatorClass:
Ted Kremenek73d15c42010-11-13 01:09:29 +00001970 case Stmt::BlockExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001971 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001972 case Stmt::CaseStmtClass:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001973 case Stmt::CompoundLiteralExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001974 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001975 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001976 case Stmt::CXXOperatorCallExprClass:
Ted Kremenek73d15c42010-11-13 01:09:29 +00001977 case Stmt::CXXTemporaryObjectExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001978 case Stmt::DefaultStmtClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001979 case Stmt::DoStmtClass:
1980 case Stmt::ForStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001981 case Stmt::IfStmtClass:
Ted Kremeneka6b70432010-11-12 21:34:09 +00001982 case Stmt::InitListExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001983 case Stmt::MemberExprClass:
Ted Kremenek73d15c42010-11-13 01:09:29 +00001984 case Stmt::ObjCEncodeExprClass:
Ted Kremenekc373e3c2010-11-12 22:24:55 +00001985 case Stmt::ObjCMessageExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001986 case Stmt::ParenExprClass:
1987 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00001988 case Stmt::UnaryOperatorClass:
Ted Kremenek60458782010-11-12 21:34:16 +00001989 case Stmt::UnresolvedLookupExprClass:
1990 case Stmt::UnresolvedMemberExprClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001991 case Stmt::WhileStmtClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001992 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001993 if (!IsInRegionOfInterest(Cursor))
1994 continue;
1995 switch (Visitor(Cursor, Parent, ClientData)) {
1996 case CXChildVisit_Break:
1997 return true;
1998 case CXChildVisit_Continue:
1999 break;
2000 case CXChildVisit_Recurse:
2001 EnqueueWorkList(WL, S);
2002 break;
2003 }
2004 }
2005 }
2006 continue;
2007 }
2008 case VisitorJob::MemberExprPartsKind: {
2009 // Handle the other pieces in the MemberExpr besides the base.
2010 MemberExpr *M = cast<MemberExprParts>(LI).get();
2011
2012 // Visit the nested-name-specifier
2013 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2014 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2015 return true;
2016
2017 // Visit the declaration name.
2018 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2019 return true;
2020
2021 // Visit the explicitly-specified template arguments, if any.
2022 if (M->hasExplicitTemplateArgs()) {
2023 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2024 *ArgEnd = Arg + M->getNumTemplateArgs();
2025 Arg != ArgEnd; ++Arg) {
2026 if (VisitTemplateArgumentLoc(*Arg))
2027 return true;
2028 }
2029 }
2030 continue;
2031 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002032 case VisitorJob::DeclRefExprPartsKind: {
2033 DeclRefExpr *DR = cast<DeclRefExprParts>(LI).get();
2034 // Visit nested-name-specifier, if present.
2035 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2036 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2037 return true;
2038 // Visit declaration name.
2039 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2040 return true;
2041 // Visit explicitly-specified template arguments.
2042 if (DR->hasExplicitTemplateArgs()) {
2043 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2044 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2045 *ArgEnd = Arg + Args.NumTemplateArgs;
2046 Arg != ArgEnd; ++Arg)
2047 if (VisitTemplateArgumentLoc(*Arg))
2048 return true;
2049 }
2050 continue;
2051 }
Ted Kremenek60458782010-11-12 21:34:16 +00002052 case VisitorJob::OverloadExprPartsKind: {
2053 OverloadExpr *O = cast<OverloadExprParts>(LI).get();
2054 // Visit the nested-name-specifier.
2055 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2056 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2057 return true;
2058 // Visit the declaration name.
2059 if (VisitDeclarationNameInfo(O->getNameInfo()))
2060 return true;
2061 // Visit the overloaded declaration reference.
2062 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2063 return true;
2064 // Visit the explicitly-specified template arguments.
2065 if (const ExplicitTemplateArgumentList *ArgList
2066 = O->getOptionalExplicitTemplateArgs()) {
2067 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2068 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2069 Arg != ArgEnd; ++Arg) {
2070 if (VisitTemplateArgumentLoc(*Arg))
2071 return true;
2072 }
2073 }
2074 continue;
2075 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002076 }
2077 }
2078 return false;
2079}
2080
2081bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2082 VisitorWorkList WL;
2083 EnqueueWorkList(WL, S);
2084 return RunVisitorWorkList(WL);
2085}
2086
2087//===----------------------------------------------------------------------===//
2088// Misc. API hooks.
2089//===----------------------------------------------------------------------===//
2090
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002091static llvm::sys::Mutex EnableMultithreadingMutex;
2092static bool EnabledMultithreading;
2093
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002094extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002095CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2096 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002097 // Disable pretty stack trace functionality, which will otherwise be a very
2098 // poor citizen of the world and set up all sorts of signal handlers.
2099 llvm::DisablePrettyStackTrace = true;
2100
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002101 // We use crash recovery to make some of our APIs more reliable, implicitly
2102 // enable it.
2103 llvm::CrashRecoveryContext::Enable();
2104
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002105 // Enable support for multithreading in LLVM.
2106 {
2107 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2108 if (!EnabledMultithreading) {
2109 llvm::llvm_start_multithreaded();
2110 EnabledMultithreading = true;
2111 }
2112 }
2113
Douglas Gregora030b7c2010-01-22 20:35:53 +00002114 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002115 if (excludeDeclarationsFromPCH)
2116 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002117 if (displayDiagnostics)
2118 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002119 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002120}
2121
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002122void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002123 if (CIdx)
2124 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002125}
2126
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002127CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002128 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002129 if (!CIdx)
2130 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002131
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002132 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002133 FileSystemOptions FileSystemOpts;
2134 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002135
Douglas Gregor28019772010-04-05 23:52:57 +00002136 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002137 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002138 CXXIdx->getOnlyLocalDecls(),
2139 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002140}
2141
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002142unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002143 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002144 CXTranslationUnit_CacheCompletionResults |
2145 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002146}
2147
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002148CXTranslationUnit
2149clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2150 const char *source_filename,
2151 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002152 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002153 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002154 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002155 return clang_parseTranslationUnit(CIdx, source_filename,
2156 command_line_args, num_command_line_args,
2157 unsaved_files, num_unsaved_files,
2158 CXTranslationUnit_DetailedPreprocessingRecord);
2159}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002160
2161struct ParseTranslationUnitInfo {
2162 CXIndex CIdx;
2163 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002164 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002165 int num_command_line_args;
2166 struct CXUnsavedFile *unsaved_files;
2167 unsigned num_unsaved_files;
2168 unsigned options;
2169 CXTranslationUnit result;
2170};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002171static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002172 ParseTranslationUnitInfo *PTUI =
2173 static_cast<ParseTranslationUnitInfo*>(UserData);
2174 CXIndex CIdx = PTUI->CIdx;
2175 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002176 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002177 int num_command_line_args = PTUI->num_command_line_args;
2178 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2179 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2180 unsigned options = PTUI->options;
2181 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002182
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002183 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002184 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002185
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002186 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2187
Douglas Gregor44c181a2010-07-23 00:33:23 +00002188 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002189 bool CompleteTranslationUnit
2190 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002191 bool CacheCodeCompetionResults
2192 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002193 bool CXXPrecompilePreamble
2194 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2195 bool CXXChainedPCH
2196 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002197
Douglas Gregor5352ac02010-01-28 00:27:43 +00002198 // Configure the diagnostics.
2199 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002200 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2201 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
Douglas Gregor4db64a42010-01-23 00:14:00 +00002203 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2204 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002205 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002206 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002207 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002208 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2209 Buffer));
2210 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002211
Douglas Gregorb10daed2010-10-11 16:52:23 +00002212 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002213
Ted Kremenek139ba862009-10-22 00:03:57 +00002214 // The 'source_filename' argument is optional. If the caller does not
2215 // specify it then it is assumed that the source file is specified
2216 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002217 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002219
2220 // Since the Clang C library is primarily used by batch tools dealing with
2221 // (often very broken) source code, where spell-checking can have a
2222 // significant negative impact on performance (particularly when
2223 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002224 // Only do this if we haven't found a spell-checking-related argument.
2225 bool FoundSpellCheckingArgument = false;
2226 for (int I = 0; I != num_command_line_args; ++I) {
2227 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2228 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2229 FoundSpellCheckingArgument = true;
2230 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002231 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002232 }
2233 if (!FoundSpellCheckingArgument)
2234 Args.push_back("-fno-spell-checking");
2235
2236 Args.insert(Args.end(), command_line_args,
2237 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002238
Douglas Gregor44c181a2010-07-23 00:33:23 +00002239 // Do we need the detailed preprocessing record?
2240 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002241 Args.push_back("-Xclang");
2242 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002243 }
2244
Douglas Gregorb10daed2010-10-11 16:52:23 +00002245 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002246 llvm::OwningPtr<ASTUnit> Unit(
2247 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2248 Diags,
2249 CXXIdx->getClangResourcesPath(),
2250 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002251 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002252 RemappedFiles.data(),
2253 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002254 PrecompilePreamble,
2255 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002256 CacheCodeCompetionResults,
2257 CXXPrecompilePreamble,
2258 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002259
Douglas Gregorb10daed2010-10-11 16:52:23 +00002260 if (NumErrors != Diags->getNumErrors()) {
2261 // Make sure to check that 'Unit' is non-NULL.
2262 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2263 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2264 DEnd = Unit->stored_diag_end();
2265 D != DEnd; ++D) {
2266 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2267 CXString Msg = clang_formatDiagnostic(&Diag,
2268 clang_defaultDiagnosticDisplayOptions());
2269 fprintf(stderr, "%s\n", clang_getCString(Msg));
2270 clang_disposeString(Msg);
2271 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002272#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002273 // On Windows, force a flush, since there may be multiple copies of
2274 // stderr and stdout in the file system, all with different buffers
2275 // but writing to the same device.
2276 fflush(stderr);
2277#endif
2278 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002279 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002280
Douglas Gregorb10daed2010-10-11 16:52:23 +00002281 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002282}
2283CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2284 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002285 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002286 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002287 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002288 unsigned num_unsaved_files,
2289 unsigned options) {
2290 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002291 num_command_line_args, unsaved_files,
2292 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002293 llvm::CrashRecoveryContext CRC;
2294
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002295 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002296 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2297 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2298 fprintf(stderr, " 'command_line_args' : [");
2299 for (int i = 0; i != num_command_line_args; ++i) {
2300 if (i)
2301 fprintf(stderr, ", ");
2302 fprintf(stderr, "'%s'", command_line_args[i]);
2303 }
2304 fprintf(stderr, "],\n");
2305 fprintf(stderr, " 'unsaved_files' : [");
2306 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2307 if (i)
2308 fprintf(stderr, ", ");
2309 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2310 unsaved_files[i].Length);
2311 }
2312 fprintf(stderr, "],\n");
2313 fprintf(stderr, " 'options' : %d,\n", options);
2314 fprintf(stderr, "}\n");
2315
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002316 return 0;
2317 }
2318
2319 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002320}
2321
Douglas Gregor19998442010-08-13 15:35:05 +00002322unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2323 return CXSaveTranslationUnit_None;
2324}
2325
2326int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2327 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002328 if (!TU)
2329 return 1;
2330
2331 return static_cast<ASTUnit *>(TU)->Save(FileName);
2332}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002333
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002334void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002335 if (CTUnit) {
2336 // If the translation unit has been marked as unsafe to free, just discard
2337 // it.
2338 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2339 return;
2340
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002341 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002342 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002343}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002344
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002345unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2346 return CXReparse_None;
2347}
2348
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002349struct ReparseTranslationUnitInfo {
2350 CXTranslationUnit TU;
2351 unsigned num_unsaved_files;
2352 struct CXUnsavedFile *unsaved_files;
2353 unsigned options;
2354 int result;
2355};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002356
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002357static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002358 ReparseTranslationUnitInfo *RTUI =
2359 static_cast<ReparseTranslationUnitInfo*>(UserData);
2360 CXTranslationUnit TU = RTUI->TU;
2361 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2362 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2363 unsigned options = RTUI->options;
2364 (void) options;
2365 RTUI->result = 1;
2366
Douglas Gregorabc563f2010-07-19 21:46:24 +00002367 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002368 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002369
2370 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2371 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002372
2373 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2374 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2375 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2376 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002377 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002378 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2379 Buffer));
2380 }
2381
Douglas Gregor593b0c12010-09-23 18:47:53 +00002382 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2383 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002384}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002385
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002386int clang_reparseTranslationUnit(CXTranslationUnit TU,
2387 unsigned num_unsaved_files,
2388 struct CXUnsavedFile *unsaved_files,
2389 unsigned options) {
2390 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2391 options, 0 };
2392 llvm::CrashRecoveryContext CRC;
2393
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002394 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002395 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002396 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2397 return 1;
2398 }
2399
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002400
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002401 return RTUI.result;
2402}
2403
Douglas Gregordf95a132010-08-09 20:45:32 +00002404
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002405CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002406 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002407 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002408
Steve Naroff77accc12009-09-03 18:19:54 +00002409 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002410 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002411}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002412
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002413CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002414 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002415 return Result;
2416}
2417
Ted Kremenekfb480492010-01-13 21:46:36 +00002418} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002419
Ted Kremenekfb480492010-01-13 21:46:36 +00002420//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002421// CXSourceLocation and CXSourceRange Operations.
2422//===----------------------------------------------------------------------===//
2423
Douglas Gregorb9790342010-01-22 21:44:22 +00002424extern "C" {
2425CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002426 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002427 return Result;
2428}
2429
2430unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002431 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2432 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2433 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002434}
2435
2436CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2437 CXFile file,
2438 unsigned line,
2439 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002440 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002441 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002442
Douglas Gregorb9790342010-01-22 21:44:22 +00002443 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2444 SourceLocation SLoc
2445 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002446 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002447 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002448 if (SLoc.isInvalid()) return clang_getNullLocation();
2449
2450 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2451}
2452
2453CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2454 CXFile file,
2455 unsigned offset) {
2456 if (!tu || !file)
2457 return clang_getNullLocation();
2458
2459 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2460 SourceLocation Start
2461 = CXXUnit->getSourceManager().getLocation(
2462 static_cast<const FileEntry *>(file),
2463 1, 1);
2464 if (Start.isInvalid()) return clang_getNullLocation();
2465
2466 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2467
2468 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002469
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002470 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002471}
2472
Douglas Gregor5352ac02010-01-28 00:27:43 +00002473CXSourceRange clang_getNullRange() {
2474 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2475 return Result;
2476}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002477
Douglas Gregor5352ac02010-01-28 00:27:43 +00002478CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2479 if (begin.ptr_data[0] != end.ptr_data[0] ||
2480 begin.ptr_data[1] != end.ptr_data[1])
2481 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002482
2483 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002484 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002485 return Result;
2486}
2487
Douglas Gregor46766dc2010-01-26 19:19:08 +00002488void clang_getInstantiationLocation(CXSourceLocation location,
2489 CXFile *file,
2490 unsigned *line,
2491 unsigned *column,
2492 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002493 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2494
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002495 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002496 if (file)
2497 *file = 0;
2498 if (line)
2499 *line = 0;
2500 if (column)
2501 *column = 0;
2502 if (offset)
2503 *offset = 0;
2504 return;
2505 }
2506
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002507 const SourceManager &SM =
2508 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002509 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002510
2511 if (file)
2512 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2513 if (line)
2514 *line = SM.getInstantiationLineNumber(InstLoc);
2515 if (column)
2516 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002517 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002518 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002519}
2520
Douglas Gregora9b06d42010-11-09 06:24:54 +00002521void clang_getSpellingLocation(CXSourceLocation location,
2522 CXFile *file,
2523 unsigned *line,
2524 unsigned *column,
2525 unsigned *offset) {
2526 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2527
2528 if (!location.ptr_data[0] || Loc.isInvalid()) {
2529 if (file)
2530 *file = 0;
2531 if (line)
2532 *line = 0;
2533 if (column)
2534 *column = 0;
2535 if (offset)
2536 *offset = 0;
2537 return;
2538 }
2539
2540 const SourceManager &SM =
2541 *static_cast<const SourceManager*>(location.ptr_data[0]);
2542 SourceLocation SpellLoc = Loc;
2543 if (SpellLoc.isMacroID()) {
2544 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2545 if (SimpleSpellingLoc.isFileID() &&
2546 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2547 SpellLoc = SimpleSpellingLoc;
2548 else
2549 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2550 }
2551
2552 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2553 FileID FID = LocInfo.first;
2554 unsigned FileOffset = LocInfo.second;
2555
2556 if (file)
2557 *file = (void *)SM.getFileEntryForID(FID);
2558 if (line)
2559 *line = SM.getLineNumber(FID, FileOffset);
2560 if (column)
2561 *column = SM.getColumnNumber(FID, FileOffset);
2562 if (offset)
2563 *offset = FileOffset;
2564}
2565
Douglas Gregor1db19de2010-01-19 21:36:55 +00002566CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002567 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002568 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002569 return Result;
2570}
2571
2572CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002573 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002574 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002575 return Result;
2576}
2577
Douglas Gregorb9790342010-01-22 21:44:22 +00002578} // end: extern "C"
2579
Douglas Gregor1db19de2010-01-19 21:36:55 +00002580//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002581// CXFile Operations.
2582//===----------------------------------------------------------------------===//
2583
2584extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002585CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002586 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002587 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002588
Steve Naroff88145032009-10-27 14:35:18 +00002589 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002590 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002591}
2592
2593time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002594 if (!SFile)
2595 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002596
Steve Naroff88145032009-10-27 14:35:18 +00002597 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2598 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002599}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002600
Douglas Gregorb9790342010-01-22 21:44:22 +00002601CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2602 if (!tu)
2603 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002604
Douglas Gregorb9790342010-01-22 21:44:22 +00002605 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002606
Douglas Gregorb9790342010-01-22 21:44:22 +00002607 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002608 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2609 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002610 return const_cast<FileEntry *>(File);
2611}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002612
Ted Kremenekfb480492010-01-13 21:46:36 +00002613} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002614
Ted Kremenekfb480492010-01-13 21:46:36 +00002615//===----------------------------------------------------------------------===//
2616// CXCursor Operations.
2617//===----------------------------------------------------------------------===//
2618
Ted Kremenekfb480492010-01-13 21:46:36 +00002619static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002620 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2621 return getDeclFromExpr(CE->getSubExpr());
2622
Ted Kremenekfb480492010-01-13 21:46:36 +00002623 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2624 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002625 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2626 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002627 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2628 return ME->getMemberDecl();
2629 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2630 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002631 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2632 return PRE->getProperty();
2633
Ted Kremenekfb480492010-01-13 21:46:36 +00002634 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2635 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002636 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2637 if (!CE->isElidable())
2638 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002639 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2640 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002641
Douglas Gregordb1314e2010-10-01 21:11:22 +00002642 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2643 return PE->getProtocol();
2644
Ted Kremenekfb480492010-01-13 21:46:36 +00002645 return 0;
2646}
2647
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002648static SourceLocation getLocationFromExpr(Expr *E) {
2649 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2650 return /*FIXME:*/Msg->getLeftLoc();
2651 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2652 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002653 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2654 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002655 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2656 return Member->getMemberLoc();
2657 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2658 return Ivar->getLocation();
2659 return E->getLocStart();
2660}
2661
Ted Kremenekfb480492010-01-13 21:46:36 +00002662extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002663
2664unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002665 CXCursorVisitor visitor,
2666 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002667 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002668
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002669 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2670 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002671 return CursorVis.VisitChildren(parent);
2672}
2673
David Chisnall3387c652010-11-03 14:12:26 +00002674#ifndef __has_feature
2675#define __has_feature(x) 0
2676#endif
2677#if __has_feature(blocks)
2678typedef enum CXChildVisitResult
2679 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2680
2681static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2682 CXClientData client_data) {
2683 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2684 return block(cursor, parent);
2685}
2686#else
2687// If we are compiled with a compiler that doesn't have native blocks support,
2688// define and call the block manually, so the
2689typedef struct _CXChildVisitResult
2690{
2691 void *isa;
2692 int flags;
2693 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002694 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2695 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002696} *CXCursorVisitorBlock;
2697
2698static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2699 CXClientData client_data) {
2700 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2701 return block->invoke(block, cursor, parent);
2702}
2703#endif
2704
2705
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002706unsigned clang_visitChildrenWithBlock(CXCursor parent,
2707 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002708 return clang_visitChildren(parent, visitWithBlock, block);
2709}
2710
Douglas Gregor78205d42010-01-20 21:45:58 +00002711static CXString getDeclSpelling(Decl *D) {
2712 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2713 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002714 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715
Douglas Gregor78205d42010-01-20 21:45:58 +00002716 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002717 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002718
Douglas Gregor78205d42010-01-20 21:45:58 +00002719 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2720 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2721 // and returns different names. NamedDecl returns the class name and
2722 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002723 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002724
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002725 if (isa<UsingDirectiveDecl>(D))
2726 return createCXString("");
2727
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002728 llvm::SmallString<1024> S;
2729 llvm::raw_svector_ostream os(S);
2730 ND->printName(os);
2731
2732 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002733}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002734
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002735CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002736 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002737 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002738
Steve Narofff334b4e2009-09-02 18:26:48 +00002739 if (clang_isReference(C.kind)) {
2740 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002741 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002742 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002743 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002744 }
2745 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002746 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002747 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002748 }
2749 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002750 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002751 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002752 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002753 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002754 case CXCursor_CXXBaseSpecifier: {
2755 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2756 return createCXString(B->getType().getAsString());
2757 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002758 case CXCursor_TypeRef: {
2759 TypeDecl *Type = getCursorTypeRef(C).first;
2760 assert(Type && "Missing type decl");
2761
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002762 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2763 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002764 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002765 case CXCursor_TemplateRef: {
2766 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002767 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002768
2769 return createCXString(Template->getNameAsString());
2770 }
Douglas Gregor69319002010-08-31 23:48:11 +00002771
2772 case CXCursor_NamespaceRef: {
2773 NamedDecl *NS = getCursorNamespaceRef(C).first;
2774 assert(NS && "Missing namespace decl");
2775
2776 return createCXString(NS->getNameAsString());
2777 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002778
Douglas Gregora67e03f2010-09-09 21:42:20 +00002779 case CXCursor_MemberRef: {
2780 FieldDecl *Field = getCursorMemberRef(C).first;
2781 assert(Field && "Missing member decl");
2782
2783 return createCXString(Field->getNameAsString());
2784 }
2785
Douglas Gregor36897b02010-09-10 00:22:18 +00002786 case CXCursor_LabelRef: {
2787 LabelStmt *Label = getCursorLabelRef(C).first;
2788 assert(Label && "Missing label");
2789
2790 return createCXString(Label->getID()->getName());
2791 }
2792
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002793 case CXCursor_OverloadedDeclRef: {
2794 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2795 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2796 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2797 return createCXString(ND->getNameAsString());
2798 return createCXString("");
2799 }
2800 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2801 return createCXString(E->getName().getAsString());
2802 OverloadedTemplateStorage *Ovl
2803 = Storage.get<OverloadedTemplateStorage*>();
2804 if (Ovl->size() == 0)
2805 return createCXString("");
2806 return createCXString((*Ovl->begin())->getNameAsString());
2807 }
2808
Daniel Dunbaracca7252009-11-30 20:42:49 +00002809 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002810 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002811 }
2812 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002813
2814 if (clang_isExpression(C.kind)) {
2815 Decl *D = getDeclFromExpr(getCursorExpr(C));
2816 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002817 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002818 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002819 }
2820
Douglas Gregor36897b02010-09-10 00:22:18 +00002821 if (clang_isStatement(C.kind)) {
2822 Stmt *S = getCursorStmt(C);
2823 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2824 return createCXString(Label->getID()->getName());
2825
2826 return createCXString("");
2827 }
2828
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002829 if (C.kind == CXCursor_MacroInstantiation)
2830 return createCXString(getCursorMacroInstantiation(C)->getName()
2831 ->getNameStart());
2832
Douglas Gregor572feb22010-03-18 18:04:21 +00002833 if (C.kind == CXCursor_MacroDefinition)
2834 return createCXString(getCursorMacroDefinition(C)->getName()
2835 ->getNameStart());
2836
Douglas Gregorecdcb882010-10-20 22:00:55 +00002837 if (C.kind == CXCursor_InclusionDirective)
2838 return createCXString(getCursorInclusionDirective(C)->getFileName());
2839
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002840 if (clang_isDeclaration(C.kind))
2841 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002842
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002843 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002844}
2845
Douglas Gregor358559d2010-10-02 22:49:11 +00002846CXString clang_getCursorDisplayName(CXCursor C) {
2847 if (!clang_isDeclaration(C.kind))
2848 return clang_getCursorSpelling(C);
2849
2850 Decl *D = getCursorDecl(C);
2851 if (!D)
2852 return createCXString("");
2853
2854 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2855 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2856 D = FunTmpl->getTemplatedDecl();
2857
2858 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2859 llvm::SmallString<64> Str;
2860 llvm::raw_svector_ostream OS(Str);
2861 OS << Function->getNameAsString();
2862 if (Function->getPrimaryTemplate())
2863 OS << "<>";
2864 OS << "(";
2865 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2866 if (I)
2867 OS << ", ";
2868 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2869 }
2870
2871 if (Function->isVariadic()) {
2872 if (Function->getNumParams())
2873 OS << ", ";
2874 OS << "...";
2875 }
2876 OS << ")";
2877 return createCXString(OS.str());
2878 }
2879
2880 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2881 llvm::SmallString<64> Str;
2882 llvm::raw_svector_ostream OS(Str);
2883 OS << ClassTemplate->getNameAsString();
2884 OS << "<";
2885 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2886 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2887 if (I)
2888 OS << ", ";
2889
2890 NamedDecl *Param = Params->getParam(I);
2891 if (Param->getIdentifier()) {
2892 OS << Param->getIdentifier()->getName();
2893 continue;
2894 }
2895
2896 // There is no parameter name, which makes this tricky. Try to come up
2897 // with something useful that isn't too long.
2898 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2899 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2900 else if (NonTypeTemplateParmDecl *NTTP
2901 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2902 OS << NTTP->getType().getAsString(Policy);
2903 else
2904 OS << "template<...> class";
2905 }
2906
2907 OS << ">";
2908 return createCXString(OS.str());
2909 }
2910
2911 if (ClassTemplateSpecializationDecl *ClassSpec
2912 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2913 // If the type was explicitly written, use that.
2914 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2915 return createCXString(TSInfo->getType().getAsString(Policy));
2916
2917 llvm::SmallString<64> Str;
2918 llvm::raw_svector_ostream OS(Str);
2919 OS << ClassSpec->getNameAsString();
2920 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002921 ClassSpec->getTemplateArgs().data(),
2922 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002923 Policy);
2924 return createCXString(OS.str());
2925 }
2926
2927 return clang_getCursorSpelling(C);
2928}
2929
Ted Kremeneke68fff62010-02-17 00:41:32 +00002930CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002931 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002932 case CXCursor_FunctionDecl:
2933 return createCXString("FunctionDecl");
2934 case CXCursor_TypedefDecl:
2935 return createCXString("TypedefDecl");
2936 case CXCursor_EnumDecl:
2937 return createCXString("EnumDecl");
2938 case CXCursor_EnumConstantDecl:
2939 return createCXString("EnumConstantDecl");
2940 case CXCursor_StructDecl:
2941 return createCXString("StructDecl");
2942 case CXCursor_UnionDecl:
2943 return createCXString("UnionDecl");
2944 case CXCursor_ClassDecl:
2945 return createCXString("ClassDecl");
2946 case CXCursor_FieldDecl:
2947 return createCXString("FieldDecl");
2948 case CXCursor_VarDecl:
2949 return createCXString("VarDecl");
2950 case CXCursor_ParmDecl:
2951 return createCXString("ParmDecl");
2952 case CXCursor_ObjCInterfaceDecl:
2953 return createCXString("ObjCInterfaceDecl");
2954 case CXCursor_ObjCCategoryDecl:
2955 return createCXString("ObjCCategoryDecl");
2956 case CXCursor_ObjCProtocolDecl:
2957 return createCXString("ObjCProtocolDecl");
2958 case CXCursor_ObjCPropertyDecl:
2959 return createCXString("ObjCPropertyDecl");
2960 case CXCursor_ObjCIvarDecl:
2961 return createCXString("ObjCIvarDecl");
2962 case CXCursor_ObjCInstanceMethodDecl:
2963 return createCXString("ObjCInstanceMethodDecl");
2964 case CXCursor_ObjCClassMethodDecl:
2965 return createCXString("ObjCClassMethodDecl");
2966 case CXCursor_ObjCImplementationDecl:
2967 return createCXString("ObjCImplementationDecl");
2968 case CXCursor_ObjCCategoryImplDecl:
2969 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002970 case CXCursor_CXXMethod:
2971 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002972 case CXCursor_UnexposedDecl:
2973 return createCXString("UnexposedDecl");
2974 case CXCursor_ObjCSuperClassRef:
2975 return createCXString("ObjCSuperClassRef");
2976 case CXCursor_ObjCProtocolRef:
2977 return createCXString("ObjCProtocolRef");
2978 case CXCursor_ObjCClassRef:
2979 return createCXString("ObjCClassRef");
2980 case CXCursor_TypeRef:
2981 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002982 case CXCursor_TemplateRef:
2983 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002984 case CXCursor_NamespaceRef:
2985 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002986 case CXCursor_MemberRef:
2987 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002988 case CXCursor_LabelRef:
2989 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002990 case CXCursor_OverloadedDeclRef:
2991 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002992 case CXCursor_UnexposedExpr:
2993 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002994 case CXCursor_BlockExpr:
2995 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002996 case CXCursor_DeclRefExpr:
2997 return createCXString("DeclRefExpr");
2998 case CXCursor_MemberRefExpr:
2999 return createCXString("MemberRefExpr");
3000 case CXCursor_CallExpr:
3001 return createCXString("CallExpr");
3002 case CXCursor_ObjCMessageExpr:
3003 return createCXString("ObjCMessageExpr");
3004 case CXCursor_UnexposedStmt:
3005 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003006 case CXCursor_LabelStmt:
3007 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003008 case CXCursor_InvalidFile:
3009 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003010 case CXCursor_InvalidCode:
3011 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003012 case CXCursor_NoDeclFound:
3013 return createCXString("NoDeclFound");
3014 case CXCursor_NotImplemented:
3015 return createCXString("NotImplemented");
3016 case CXCursor_TranslationUnit:
3017 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003018 case CXCursor_UnexposedAttr:
3019 return createCXString("UnexposedAttr");
3020 case CXCursor_IBActionAttr:
3021 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003022 case CXCursor_IBOutletAttr:
3023 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003024 case CXCursor_IBOutletCollectionAttr:
3025 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003026 case CXCursor_PreprocessingDirective:
3027 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003028 case CXCursor_MacroDefinition:
3029 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003030 case CXCursor_MacroInstantiation:
3031 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003032 case CXCursor_InclusionDirective:
3033 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003034 case CXCursor_Namespace:
3035 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003036 case CXCursor_LinkageSpec:
3037 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003038 case CXCursor_CXXBaseSpecifier:
3039 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003040 case CXCursor_Constructor:
3041 return createCXString("CXXConstructor");
3042 case CXCursor_Destructor:
3043 return createCXString("CXXDestructor");
3044 case CXCursor_ConversionFunction:
3045 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003046 case CXCursor_TemplateTypeParameter:
3047 return createCXString("TemplateTypeParameter");
3048 case CXCursor_NonTypeTemplateParameter:
3049 return createCXString("NonTypeTemplateParameter");
3050 case CXCursor_TemplateTemplateParameter:
3051 return createCXString("TemplateTemplateParameter");
3052 case CXCursor_FunctionTemplate:
3053 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003054 case CXCursor_ClassTemplate:
3055 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003056 case CXCursor_ClassTemplatePartialSpecialization:
3057 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003058 case CXCursor_NamespaceAlias:
3059 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003060 case CXCursor_UsingDirective:
3061 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003062 case CXCursor_UsingDeclaration:
3063 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003064 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003065
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003066 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003067 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003068}
Steve Naroff89922f82009-08-31 00:59:03 +00003069
Ted Kremeneke68fff62010-02-17 00:41:32 +00003070enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3071 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003072 CXClientData client_data) {
3073 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003074
3075 // If our current best cursor is the construction of a temporary object,
3076 // don't replace that cursor with a type reference, because we want
3077 // clang_getCursor() to point at the constructor.
3078 if (clang_isExpression(BestCursor->kind) &&
3079 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3080 cursor.kind == CXCursor_TypeRef)
3081 return CXChildVisit_Recurse;
3082
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003083 *BestCursor = cursor;
3084 return CXChildVisit_Recurse;
3085}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003086
Douglas Gregorb9790342010-01-22 21:44:22 +00003087CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3088 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003089 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003090
Douglas Gregorb9790342010-01-22 21:44:22 +00003091 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003092 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3093
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003094 // Translate the given source location to make it point at the beginning of
3095 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003096 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003097
3098 // Guard against an invalid SourceLocation, or we may assert in one
3099 // of the following calls.
3100 if (SLoc.isInvalid())
3101 return clang_getNullCursor();
3102
Douglas Gregor40749ee2010-11-03 00:35:38 +00003103 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003104 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3105 CXXUnit->getASTContext().getLangOptions());
3106
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003107 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3108 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003109 // FIXME: Would be great to have a "hint" cursor, then walk from that
3110 // hint cursor upward until we find a cursor whose source range encloses
3111 // the region of interest, rather than starting from the translation unit.
3112 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003113 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003114 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003115 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003116 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003117
3118 if (Logging) {
3119 CXFile SearchFile;
3120 unsigned SearchLine, SearchColumn;
3121 CXFile ResultFile;
3122 unsigned ResultLine, ResultColumn;
3123 CXString SearchFileName, ResultFileName, KindSpelling;
3124 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3125
3126 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3127 0);
3128 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3129 &ResultColumn, 0);
3130 SearchFileName = clang_getFileName(SearchFile);
3131 ResultFileName = clang_getFileName(ResultFile);
3132 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3133 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3134 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3135 clang_getCString(KindSpelling),
3136 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3137 clang_disposeString(SearchFileName);
3138 clang_disposeString(ResultFileName);
3139 clang_disposeString(KindSpelling);
3140 }
3141
Ted Kremeneke68fff62010-02-17 00:41:32 +00003142 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003143}
3144
Ted Kremenek73885552009-11-17 19:28:59 +00003145CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003146 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003147}
3148
3149unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003150 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003151}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003152
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003153unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003154 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3155}
3156
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003157unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003158 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3159}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003160
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003161unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003162 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3163}
3164
Douglas Gregor97b98722010-01-19 23:20:36 +00003165unsigned clang_isExpression(enum CXCursorKind K) {
3166 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3167}
3168
3169unsigned clang_isStatement(enum CXCursorKind K) {
3170 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3171}
3172
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003173unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3174 return K == CXCursor_TranslationUnit;
3175}
3176
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003177unsigned clang_isPreprocessing(enum CXCursorKind K) {
3178 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3179}
3180
Ted Kremenekad6eff62010-03-08 21:17:29 +00003181unsigned clang_isUnexposed(enum CXCursorKind K) {
3182 switch (K) {
3183 case CXCursor_UnexposedDecl:
3184 case CXCursor_UnexposedExpr:
3185 case CXCursor_UnexposedStmt:
3186 case CXCursor_UnexposedAttr:
3187 return true;
3188 default:
3189 return false;
3190 }
3191}
3192
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003193CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003194 return C.kind;
3195}
3196
Douglas Gregor98258af2010-01-18 22:46:11 +00003197CXSourceLocation clang_getCursorLocation(CXCursor C) {
3198 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003199 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003200 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003201 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3202 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003203 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003204 }
3205
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003206 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003207 std::pair<ObjCProtocolDecl *, SourceLocation> P
3208 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003209 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003210 }
3211
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003212 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003213 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3214 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003215 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003216 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003217
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003218 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003219 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003220 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003221 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003222
3223 case CXCursor_TemplateRef: {
3224 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3225 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3226 }
3227
Douglas Gregor69319002010-08-31 23:48:11 +00003228 case CXCursor_NamespaceRef: {
3229 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3230 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3231 }
3232
Douglas Gregora67e03f2010-09-09 21:42:20 +00003233 case CXCursor_MemberRef: {
3234 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3235 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3236 }
3237
Ted Kremenek3064ef92010-08-27 21:34:58 +00003238 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003239 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3240 if (!BaseSpec)
3241 return clang_getNullLocation();
3242
3243 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3244 return cxloc::translateSourceLocation(getCursorContext(C),
3245 TSInfo->getTypeLoc().getBeginLoc());
3246
3247 return cxloc::translateSourceLocation(getCursorContext(C),
3248 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003249 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003250
Douglas Gregor36897b02010-09-10 00:22:18 +00003251 case CXCursor_LabelRef: {
3252 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3253 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3254 }
3255
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003256 case CXCursor_OverloadedDeclRef:
3257 return cxloc::translateSourceLocation(getCursorContext(C),
3258 getCursorOverloadedDeclRef(C).second);
3259
Douglas Gregorf46034a2010-01-18 23:41:10 +00003260 default:
3261 // FIXME: Need a way to enumerate all non-reference cases.
3262 llvm_unreachable("Missed a reference kind");
3263 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003264 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003265
3266 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003267 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003268 getLocationFromExpr(getCursorExpr(C)));
3269
Douglas Gregor36897b02010-09-10 00:22:18 +00003270 if (clang_isStatement(C.kind))
3271 return cxloc::translateSourceLocation(getCursorContext(C),
3272 getCursorStmt(C)->getLocStart());
3273
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003274 if (C.kind == CXCursor_PreprocessingDirective) {
3275 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3276 return cxloc::translateSourceLocation(getCursorContext(C), L);
3277 }
Douglas Gregor48072312010-03-18 15:23:44 +00003278
3279 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003280 SourceLocation L
3281 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003282 return cxloc::translateSourceLocation(getCursorContext(C), L);
3283 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003284
3285 if (C.kind == CXCursor_MacroDefinition) {
3286 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3287 return cxloc::translateSourceLocation(getCursorContext(C), L);
3288 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003289
3290 if (C.kind == CXCursor_InclusionDirective) {
3291 SourceLocation L
3292 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3293 return cxloc::translateSourceLocation(getCursorContext(C), L);
3294 }
3295
Ted Kremenek9a700d22010-05-12 06:16:13 +00003296 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003297 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003298
Douglas Gregorf46034a2010-01-18 23:41:10 +00003299 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003300 SourceLocation Loc = D->getLocation();
3301 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3302 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003303 // FIXME: Multiple variables declared in a single declaration
3304 // currently lack the information needed to correctly determine their
3305 // ranges when accounting for the type-specifier. We use context
3306 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3307 // and if so, whether it is the first decl.
3308 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3309 if (!cxcursor::isFirstInDeclGroup(C))
3310 Loc = VD->getLocation();
3311 }
3312
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003313 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003314}
Douglas Gregora7bde202010-01-19 00:34:46 +00003315
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003316} // end extern "C"
3317
3318static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003319 if (clang_isReference(C.kind)) {
3320 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003321 case CXCursor_ObjCSuperClassRef:
3322 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003323
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003324 case CXCursor_ObjCProtocolRef:
3325 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003326
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003327 case CXCursor_ObjCClassRef:
3328 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003329
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003330 case CXCursor_TypeRef:
3331 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003332
3333 case CXCursor_TemplateRef:
3334 return getCursorTemplateRef(C).second;
3335
Douglas Gregor69319002010-08-31 23:48:11 +00003336 case CXCursor_NamespaceRef:
3337 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003338
3339 case CXCursor_MemberRef:
3340 return getCursorMemberRef(C).second;
3341
Ted Kremenek3064ef92010-08-27 21:34:58 +00003342 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003343 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003344
Douglas Gregor36897b02010-09-10 00:22:18 +00003345 case CXCursor_LabelRef:
3346 return getCursorLabelRef(C).second;
3347
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003348 case CXCursor_OverloadedDeclRef:
3349 return getCursorOverloadedDeclRef(C).second;
3350
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003351 default:
3352 // FIXME: Need a way to enumerate all non-reference cases.
3353 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003354 }
3355 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003356
3357 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003358 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003359
3360 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003361 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003362
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003363 if (C.kind == CXCursor_PreprocessingDirective)
3364 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003365
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003366 if (C.kind == CXCursor_MacroInstantiation)
3367 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003368
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003369 if (C.kind == CXCursor_MacroDefinition)
3370 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003371
3372 if (C.kind == CXCursor_InclusionDirective)
3373 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3374
Ted Kremenek007a7c92010-11-01 23:26:51 +00003375 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3376 Decl *D = cxcursor::getCursorDecl(C);
3377 SourceRange R = D->getSourceRange();
3378 // FIXME: Multiple variables declared in a single declaration
3379 // currently lack the information needed to correctly determine their
3380 // ranges when accounting for the type-specifier. We use context
3381 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3382 // and if so, whether it is the first decl.
3383 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3384 if (!cxcursor::isFirstInDeclGroup(C))
3385 R.setBegin(VD->getLocation());
3386 }
3387 return R;
3388 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003389 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003390
3391extern "C" {
3392
3393CXSourceRange clang_getCursorExtent(CXCursor C) {
3394 SourceRange R = getRawCursorExtent(C);
3395 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003396 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003397
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003398 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003399}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003400
3401CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003402 if (clang_isInvalid(C.kind))
3403 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003404
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003405 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003406 if (clang_isDeclaration(C.kind)) {
3407 Decl *D = getCursorDecl(C);
3408 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3409 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3410 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3411 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3412 if (ObjCForwardProtocolDecl *Protocols
3413 = dyn_cast<ObjCForwardProtocolDecl>(D))
3414 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3415
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003416 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003417 }
3418
Douglas Gregor97b98722010-01-19 23:20:36 +00003419 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003420 Expr *E = getCursorExpr(C);
3421 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003422 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003423 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003424
3425 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3426 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3427
Douglas Gregor97b98722010-01-19 23:20:36 +00003428 return clang_getNullCursor();
3429 }
3430
Douglas Gregor36897b02010-09-10 00:22:18 +00003431 if (clang_isStatement(C.kind)) {
3432 Stmt *S = getCursorStmt(C);
3433 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3434 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3435 getCursorASTUnit(C));
3436
3437 return clang_getNullCursor();
3438 }
3439
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003440 if (C.kind == CXCursor_MacroInstantiation) {
3441 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3442 return MakeMacroDefinitionCursor(Def, CXXUnit);
3443 }
3444
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003445 if (!clang_isReference(C.kind))
3446 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003447
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003448 switch (C.kind) {
3449 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003450 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003451
3452 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003453 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003454
3455 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003456 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003457
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003458 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003459 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003460
3461 case CXCursor_TemplateRef:
3462 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3463
Douglas Gregor69319002010-08-31 23:48:11 +00003464 case CXCursor_NamespaceRef:
3465 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3466
Douglas Gregora67e03f2010-09-09 21:42:20 +00003467 case CXCursor_MemberRef:
3468 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3469
Ted Kremenek3064ef92010-08-27 21:34:58 +00003470 case CXCursor_CXXBaseSpecifier: {
3471 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3472 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3473 CXXUnit));
3474 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003475
Douglas Gregor36897b02010-09-10 00:22:18 +00003476 case CXCursor_LabelRef:
3477 // FIXME: We end up faking the "parent" declaration here because we
3478 // don't want to make CXCursor larger.
3479 return MakeCXCursor(getCursorLabelRef(C).first,
3480 CXXUnit->getASTContext().getTranslationUnitDecl(),
3481 CXXUnit);
3482
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003483 case CXCursor_OverloadedDeclRef:
3484 return C;
3485
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003486 default:
3487 // We would prefer to enumerate all non-reference cursor kinds here.
3488 llvm_unreachable("Unhandled reference cursor kind");
3489 break;
3490 }
3491 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003492
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003493 return clang_getNullCursor();
3494}
3495
Douglas Gregorb6998662010-01-19 19:34:47 +00003496CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003497 if (clang_isInvalid(C.kind))
3498 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003499
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003500 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003501
Douglas Gregorb6998662010-01-19 19:34:47 +00003502 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003503 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003504 C = clang_getCursorReferenced(C);
3505 WasReference = true;
3506 }
3507
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003508 if (C.kind == CXCursor_MacroInstantiation)
3509 return clang_getCursorReferenced(C);
3510
Douglas Gregorb6998662010-01-19 19:34:47 +00003511 if (!clang_isDeclaration(C.kind))
3512 return clang_getNullCursor();
3513
3514 Decl *D = getCursorDecl(C);
3515 if (!D)
3516 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003517
Douglas Gregorb6998662010-01-19 19:34:47 +00003518 switch (D->getKind()) {
3519 // Declaration kinds that don't really separate the notions of
3520 // declaration and definition.
3521 case Decl::Namespace:
3522 case Decl::Typedef:
3523 case Decl::TemplateTypeParm:
3524 case Decl::EnumConstant:
3525 case Decl::Field:
3526 case Decl::ObjCIvar:
3527 case Decl::ObjCAtDefsField:
3528 case Decl::ImplicitParam:
3529 case Decl::ParmVar:
3530 case Decl::NonTypeTemplateParm:
3531 case Decl::TemplateTemplateParm:
3532 case Decl::ObjCCategoryImpl:
3533 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003534 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003535 case Decl::LinkageSpec:
3536 case Decl::ObjCPropertyImpl:
3537 case Decl::FileScopeAsm:
3538 case Decl::StaticAssert:
3539 case Decl::Block:
3540 return C;
3541
3542 // Declaration kinds that don't make any sense here, but are
3543 // nonetheless harmless.
3544 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003545 break;
3546
3547 // Declaration kinds for which the definition is not resolvable.
3548 case Decl::UnresolvedUsingTypename:
3549 case Decl::UnresolvedUsingValue:
3550 break;
3551
3552 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003553 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3554 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003555
3556 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003557 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003558
3559 case Decl::Enum:
3560 case Decl::Record:
3561 case Decl::CXXRecord:
3562 case Decl::ClassTemplateSpecialization:
3563 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003564 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003565 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003566 return clang_getNullCursor();
3567
3568 case Decl::Function:
3569 case Decl::CXXMethod:
3570 case Decl::CXXConstructor:
3571 case Decl::CXXDestructor:
3572 case Decl::CXXConversion: {
3573 const FunctionDecl *Def = 0;
3574 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003575 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003576 return clang_getNullCursor();
3577 }
3578
3579 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003580 // Ask the variable if it has a definition.
3581 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3582 return MakeCXCursor(Def, CXXUnit);
3583 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585
Douglas Gregorb6998662010-01-19 19:34:47 +00003586 case Decl::FunctionTemplate: {
3587 const FunctionDecl *Def = 0;
3588 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003589 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003590 return clang_getNullCursor();
3591 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003592
Douglas Gregorb6998662010-01-19 19:34:47 +00003593 case Decl::ClassTemplate: {
3594 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003595 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003596 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003597 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003598 return clang_getNullCursor();
3599 }
3600
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003601 case Decl::Using:
3602 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3603 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003604
3605 case Decl::UsingShadow:
3606 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003607 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003608 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003609
3610 case Decl::ObjCMethod: {
3611 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3612 if (Method->isThisDeclarationADefinition())
3613 return C;
3614
3615 // Dig out the method definition in the associated
3616 // @implementation, if we have it.
3617 // FIXME: The ASTs should make finding the definition easier.
3618 if (ObjCInterfaceDecl *Class
3619 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3620 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3621 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3622 Method->isInstanceMethod()))
3623 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003624 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003625
3626 return clang_getNullCursor();
3627 }
3628
3629 case Decl::ObjCCategory:
3630 if (ObjCCategoryImplDecl *Impl
3631 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003632 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003633 return clang_getNullCursor();
3634
3635 case Decl::ObjCProtocol:
3636 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3637 return C;
3638 return clang_getNullCursor();
3639
3640 case Decl::ObjCInterface:
3641 // There are two notions of a "definition" for an Objective-C
3642 // class: the interface and its implementation. When we resolved a
3643 // reference to an Objective-C class, produce the @interface as
3644 // the definition; when we were provided with the interface,
3645 // produce the @implementation as the definition.
3646 if (WasReference) {
3647 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3648 return C;
3649 } else if (ObjCImplementationDecl *Impl
3650 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003651 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003652 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003653
Douglas Gregorb6998662010-01-19 19:34:47 +00003654 case Decl::ObjCProperty:
3655 // FIXME: We don't really know where to find the
3656 // ObjCPropertyImplDecls that implement this property.
3657 return clang_getNullCursor();
3658
3659 case Decl::ObjCCompatibleAlias:
3660 if (ObjCInterfaceDecl *Class
3661 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3662 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003663 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003664
Douglas Gregorb6998662010-01-19 19:34:47 +00003665 return clang_getNullCursor();
3666
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003667 case Decl::ObjCForwardProtocol:
3668 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3669 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003670
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003671 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003672 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003673 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003674
3675 case Decl::Friend:
3676 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003677 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003678 return clang_getNullCursor();
3679
3680 case Decl::FriendTemplate:
3681 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003682 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003683 return clang_getNullCursor();
3684 }
3685
3686 return clang_getNullCursor();
3687}
3688
3689unsigned clang_isCursorDefinition(CXCursor C) {
3690 if (!clang_isDeclaration(C.kind))
3691 return 0;
3692
3693 return clang_getCursorDefinition(C) == C;
3694}
3695
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003696unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003697 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003698 return 0;
3699
3700 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3701 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3702 return E->getNumDecls();
3703
3704 if (OverloadedTemplateStorage *S
3705 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3706 return S->size();
3707
3708 Decl *D = Storage.get<Decl*>();
3709 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003710 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003711 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3712 return Classes->size();
3713 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3714 return Protocols->protocol_size();
3715
3716 return 0;
3717}
3718
3719CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003720 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003721 return clang_getNullCursor();
3722
3723 if (index >= clang_getNumOverloadedDecls(cursor))
3724 return clang_getNullCursor();
3725
3726 ASTUnit *Unit = getCursorASTUnit(cursor);
3727 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3728 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3729 return MakeCXCursor(E->decls_begin()[index], Unit);
3730
3731 if (OverloadedTemplateStorage *S
3732 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3733 return MakeCXCursor(S->begin()[index], Unit);
3734
3735 Decl *D = Storage.get<Decl*>();
3736 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3737 // FIXME: This is, unfortunately, linear time.
3738 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3739 std::advance(Pos, index);
3740 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3741 }
3742
3743 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3744 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3745
3746 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3747 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3748
3749 return clang_getNullCursor();
3750}
3751
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003752void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003753 const char **startBuf,
3754 const char **endBuf,
3755 unsigned *startLine,
3756 unsigned *startColumn,
3757 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003758 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003759 assert(getCursorDecl(C) && "CXCursor has null decl");
3760 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003761 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3762 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003763
Steve Naroff4ade6d62009-09-23 17:52:52 +00003764 SourceManager &SM = FD->getASTContext().getSourceManager();
3765 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3766 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3767 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3768 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3769 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3770 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3771}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003772
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003773void clang_enableStackTraces(void) {
3774 llvm::sys::PrintStackTraceOnErrorSignal();
3775}
3776
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003777void clang_executeOnThread(void (*fn)(void*), void *user_data,
3778 unsigned stack_size) {
3779 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3780}
3781
Ted Kremenekfb480492010-01-13 21:46:36 +00003782} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003783
Ted Kremenekfb480492010-01-13 21:46:36 +00003784//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003785// Token-based Operations.
3786//===----------------------------------------------------------------------===//
3787
3788/* CXToken layout:
3789 * int_data[0]: a CXTokenKind
3790 * int_data[1]: starting token location
3791 * int_data[2]: token length
3792 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003793 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003794 * otherwise unused.
3795 */
3796extern "C" {
3797
3798CXTokenKind clang_getTokenKind(CXToken CXTok) {
3799 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3800}
3801
3802CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3803 switch (clang_getTokenKind(CXTok)) {
3804 case CXToken_Identifier:
3805 case CXToken_Keyword:
3806 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003807 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3808 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003809
3810 case CXToken_Literal: {
3811 // We have stashed the starting pointer in the ptr_data field. Use it.
3812 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003813 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003814 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003815
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003816 case CXToken_Punctuation:
3817 case CXToken_Comment:
3818 break;
3819 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003820
3821 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003822 // deconstructing the source location.
3823 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3824 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003825 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003826
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003827 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3828 std::pair<FileID, unsigned> LocInfo
3829 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003830 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003831 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003832 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3833 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003834 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003835
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003836 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003838
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003839CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3840 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3841 if (!CXXUnit)
3842 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003844 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3845 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3846}
3847
3848CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3849 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003850 if (!CXXUnit)
3851 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003852
3853 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003854 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3855}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003856
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003857void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3858 CXToken **Tokens, unsigned *NumTokens) {
3859 if (Tokens)
3860 *Tokens = 0;
3861 if (NumTokens)
3862 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3865 if (!CXXUnit || !Tokens || !NumTokens)
3866 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003867
Douglas Gregorbdf60622010-03-05 21:16:25 +00003868 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3869
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003870 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003871 if (R.isInvalid())
3872 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003873
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3875 std::pair<FileID, unsigned> BeginLocInfo
3876 = SourceMgr.getDecomposedLoc(R.getBegin());
3877 std::pair<FileID, unsigned> EndLocInfo
3878 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003879
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003880 // Cannot tokenize across files.
3881 if (BeginLocInfo.first != EndLocInfo.first)
3882 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003883
3884 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003885 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003886 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003887 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003888 if (Invalid)
3889 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003890
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3892 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003893 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003895
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003896 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003897 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003898 llvm::SmallVector<CXToken, 32> CXTokens;
3899 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003900 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003901 do {
3902 // Lex the next token
3903 Lex.LexFromRawLexer(Tok);
3904 if (Tok.is(tok::eof))
3905 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003906
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003907 // Initialize the CXToken.
3908 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003909
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003910 // - Common fields
3911 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3912 CXTok.int_data[2] = Tok.getLength();
3913 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003914
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003915 // - Kind-specific fields
3916 if (Tok.isLiteral()) {
3917 CXTok.int_data[0] = CXToken_Literal;
3918 CXTok.ptr_data = (void *)Tok.getLiteralData();
3919 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003920 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003921 std::pair<FileID, unsigned> LocInfo
3922 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003923 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003924 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003925 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3926 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003927 return;
3928
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003929 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003930 IdentifierInfo *II
3931 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003932
David Chisnall096428b2010-10-13 21:44:48 +00003933 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003934 CXTok.int_data[0] = CXToken_Keyword;
3935 }
3936 else {
3937 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3938 CXToken_Identifier
3939 : CXToken_Keyword;
3940 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003941 CXTok.ptr_data = II;
3942 } else if (Tok.is(tok::comment)) {
3943 CXTok.int_data[0] = CXToken_Comment;
3944 CXTok.ptr_data = 0;
3945 } else {
3946 CXTok.int_data[0] = CXToken_Punctuation;
3947 CXTok.ptr_data = 0;
3948 }
3949 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003950 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003951 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003952
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003953 if (CXTokens.empty())
3954 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003955
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003956 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3957 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3958 *NumTokens = CXTokens.size();
3959}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003960
Ted Kremenek6db61092010-05-05 00:55:15 +00003961void clang_disposeTokens(CXTranslationUnit TU,
3962 CXToken *Tokens, unsigned NumTokens) {
3963 free(Tokens);
3964}
3965
3966} // end: extern "C"
3967
3968//===----------------------------------------------------------------------===//
3969// Token annotation APIs.
3970//===----------------------------------------------------------------------===//
3971
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003972typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003973static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3974 CXCursor parent,
3975 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003976namespace {
3977class AnnotateTokensWorker {
3978 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003979 CXToken *Tokens;
3980 CXCursor *Cursors;
3981 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003982 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003983 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003984 CursorVisitor AnnotateVis;
3985 SourceManager &SrcMgr;
3986
3987 bool MoreTokens() const { return TokIdx < NumTokens; }
3988 unsigned NextToken() const { return TokIdx; }
3989 void AdvanceToken() { ++TokIdx; }
3990 SourceLocation GetTokenLoc(unsigned tokI) {
3991 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3992 }
3993
Ted Kremenek6db61092010-05-05 00:55:15 +00003994public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003995 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003996 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3997 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003998 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003999 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004000 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
4001 Decl::MaxPCHLevel, RegionOfInterest),
4002 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004003
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004005 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004006 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004007 void AnnotateTokens() {
4008 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
4009 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004010};
4011}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004012
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004013void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4014 // Walk the AST within the region of interest, annotating tokens
4015 // along the way.
4016 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004017
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004018 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4019 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004020 if (Pos != Annotated.end() &&
4021 (clang_isInvalid(Cursors[I].kind) ||
4022 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004023 Cursors[I] = Pos->second;
4024 }
4025
4026 // Finish up annotating any tokens left.
4027 if (!MoreTokens())
4028 return;
4029
4030 const CXCursor &C = clang_getNullCursor();
4031 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4032 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4033 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004034 }
4035}
4036
Ted Kremenek6db61092010-05-05 00:55:15 +00004037enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004038AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004039 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004040 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004041 if (cursorRange.isInvalid())
4042 return CXChildVisit_Recurse;
4043
Douglas Gregor4419b672010-10-21 06:10:04 +00004044 if (clang_isPreprocessing(cursor.kind)) {
4045 // For macro instantiations, just note where the beginning of the macro
4046 // instantiation occurs.
4047 if (cursor.kind == CXCursor_MacroInstantiation) {
4048 Annotated[Loc.int_data] = cursor;
4049 return CXChildVisit_Recurse;
4050 }
4051
Douglas Gregor4419b672010-10-21 06:10:04 +00004052 // Items in the preprocessing record are kept separate from items in
4053 // declarations, so we keep a separate token index.
4054 unsigned SavedTokIdx = TokIdx;
4055 TokIdx = PreprocessingTokIdx;
4056
4057 // Skip tokens up until we catch up to the beginning of the preprocessing
4058 // entry.
4059 while (MoreTokens()) {
4060 const unsigned I = NextToken();
4061 SourceLocation TokLoc = GetTokenLoc(I);
4062 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4063 case RangeBefore:
4064 AdvanceToken();
4065 continue;
4066 case RangeAfter:
4067 case RangeOverlap:
4068 break;
4069 }
4070 break;
4071 }
4072
4073 // Look at all of the tokens within this range.
4074 while (MoreTokens()) {
4075 const unsigned I = NextToken();
4076 SourceLocation TokLoc = GetTokenLoc(I);
4077 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4078 case RangeBefore:
4079 assert(0 && "Infeasible");
4080 case RangeAfter:
4081 break;
4082 case RangeOverlap:
4083 Cursors[I] = cursor;
4084 AdvanceToken();
4085 continue;
4086 }
4087 break;
4088 }
4089
4090 // Save the preprocessing token index; restore the non-preprocessing
4091 // token index.
4092 PreprocessingTokIdx = TokIdx;
4093 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004094 return CXChildVisit_Recurse;
4095 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004096
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004097 if (cursorRange.isInvalid())
4098 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004099
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004100 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4101
Ted Kremeneka333c662010-05-12 05:29:33 +00004102 // Adjust the annotated range based specific declarations.
4103 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4104 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004105 Decl *D = cxcursor::getCursorDecl(cursor);
4106 // Don't visit synthesized ObjC methods, since they have no syntatic
4107 // representation in the source.
4108 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4109 if (MD->isSynthesized())
4110 return CXChildVisit_Continue;
4111 }
4112 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004113 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4114 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004115 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004116 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004117 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004118 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004119 }
4120 }
4121 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004122
Ted Kremenek3f404602010-08-14 01:14:06 +00004123 // If the location of the cursor occurs within a macro instantiation, record
4124 // the spelling location of the cursor in our annotation map. We can then
4125 // paper over the token labelings during a post-processing step to try and
4126 // get cursor mappings for tokens that are the *arguments* of a macro
4127 // instantiation.
4128 if (L.isMacroID()) {
4129 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4130 // Only invalidate the old annotation if it isn't part of a preprocessing
4131 // directive. Here we assume that the default construction of CXCursor
4132 // results in CXCursor.kind being an initialized value (i.e., 0). If
4133 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004134
Ted Kremenek3f404602010-08-14 01:14:06 +00004135 CXCursor &oldC = Annotated[rawEncoding];
4136 if (!clang_isPreprocessing(oldC.kind))
4137 oldC = cursor;
4138 }
4139
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004140 const enum CXCursorKind K = clang_getCursorKind(parent);
4141 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004142 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4143 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004144
4145 while (MoreTokens()) {
4146 const unsigned I = NextToken();
4147 SourceLocation TokLoc = GetTokenLoc(I);
4148 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4149 case RangeBefore:
4150 Cursors[I] = updateC;
4151 AdvanceToken();
4152 continue;
4153 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004154 case RangeOverlap:
4155 break;
4156 }
4157 break;
4158 }
4159
4160 // Visit children to get their cursor information.
4161 const unsigned BeforeChildren = NextToken();
4162 VisitChildren(cursor);
4163 const unsigned AfterChildren = NextToken();
4164
4165 // Adjust 'Last' to the last token within the extent of the cursor.
4166 while (MoreTokens()) {
4167 const unsigned I = NextToken();
4168 SourceLocation TokLoc = GetTokenLoc(I);
4169 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4170 case RangeBefore:
4171 assert(0 && "Infeasible");
4172 case RangeAfter:
4173 break;
4174 case RangeOverlap:
4175 Cursors[I] = updateC;
4176 AdvanceToken();
4177 continue;
4178 }
4179 break;
4180 }
4181 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004182
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004183 // Scan the tokens that are at the beginning of the cursor, but are not
4184 // capture by the child cursors.
4185
4186 // For AST elements within macros, rely on a post-annotate pass to
4187 // to correctly annotate the tokens with cursors. Otherwise we can
4188 // get confusing results of having tokens that map to cursors that really
4189 // are expanded by an instantiation.
4190 if (L.isMacroID())
4191 cursor = clang_getNullCursor();
4192
4193 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4194 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4195 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004196
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004197 Cursors[I] = cursor;
4198 }
4199 // Scan the tokens that are at the end of the cursor, but are not captured
4200 // but the child cursors.
4201 for (unsigned I = AfterChildren; I != Last; ++I)
4202 Cursors[I] = cursor;
4203
4204 TokIdx = Last;
4205 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004206}
4207
Ted Kremenek6db61092010-05-05 00:55:15 +00004208static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4209 CXCursor parent,
4210 CXClientData client_data) {
4211 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4212}
4213
Ted Kremenekab979612010-11-11 08:05:23 +00004214// This gets run a separate thread to avoid stack blowout.
4215static void runAnnotateTokensWorker(void *UserData) {
4216 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4217}
4218
Ted Kremenek6db61092010-05-05 00:55:15 +00004219extern "C" {
4220
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004221void clang_annotateTokens(CXTranslationUnit TU,
4222 CXToken *Tokens, unsigned NumTokens,
4223 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004224
4225 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004226 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227
Douglas Gregor4419b672010-10-21 06:10:04 +00004228 // Any token we don't specifically annotate will have a NULL cursor.
4229 CXCursor C = clang_getNullCursor();
4230 for (unsigned I = 0; I != NumTokens; ++I)
4231 Cursors[I] = C;
4232
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004233 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004234 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004235 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004236
Douglas Gregorbdf60622010-03-05 21:16:25 +00004237 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238
Douglas Gregor0396f462010-03-19 05:22:59 +00004239 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004240 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004241 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4242 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004243 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4244 clang_getTokenLocation(TU,
4245 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004246
Douglas Gregor0396f462010-03-19 05:22:59 +00004247 // A mapping from the source locations found when re-lexing or traversing the
4248 // region of interest to the corresponding cursors.
4249 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004250
4251 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004252 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4254 std::pair<FileID, unsigned> BeginLocInfo
4255 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4256 std::pair<FileID, unsigned> EndLocInfo
4257 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004258
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004259 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004260 bool Invalid = false;
4261 if (BeginLocInfo.first == EndLocInfo.first &&
4262 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4263 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004264 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4265 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004266 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004267 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004268 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004269
4270 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004271 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004272 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004273 Token Tok;
4274 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004275
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004276 reprocess:
4277 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4278 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004279 // don't see it while preprocessing these tokens later, but keep track
4280 // of all of the token locations inside this preprocessing directive so
4281 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004282 //
4283 // FIXME: Some simple tests here could identify macro definitions and
4284 // #undefs, to provide specific cursor kinds for those.
4285 std::vector<SourceLocation> Locations;
4286 do {
4287 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004288 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004289 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004290
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004291 using namespace cxcursor;
4292 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004293 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4294 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004295 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004296 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4297 Annotated[Locations[I].getRawEncoding()] = Cursor;
4298 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004299
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004300 if (Tok.isAtStartOfLine())
4301 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004302
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004303 continue;
4304 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004305
Douglas Gregor48072312010-03-18 15:23:44 +00004306 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004307 break;
4308 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004309 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004310
Douglas Gregor0396f462010-03-19 05:22:59 +00004311 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004312 // a specific cursor.
4313 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4314 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004315
4316 // Run the worker within a CrashRecoveryContext.
4317 llvm::CrashRecoveryContext CRC;
4318 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4319 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4320 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004321}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004322} // end: extern "C"
4323
4324//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004325// Operations for querying linkage of a cursor.
4326//===----------------------------------------------------------------------===//
4327
4328extern "C" {
4329CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004330 if (!clang_isDeclaration(cursor.kind))
4331 return CXLinkage_Invalid;
4332
Ted Kremenek16b42592010-03-03 06:36:57 +00004333 Decl *D = cxcursor::getCursorDecl(cursor);
4334 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4335 switch (ND->getLinkage()) {
4336 case NoLinkage: return CXLinkage_NoLinkage;
4337 case InternalLinkage: return CXLinkage_Internal;
4338 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4339 case ExternalLinkage: return CXLinkage_External;
4340 };
4341
4342 return CXLinkage_Invalid;
4343}
4344} // end: extern "C"
4345
4346//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004347// Operations for querying language of a cursor.
4348//===----------------------------------------------------------------------===//
4349
4350static CXLanguageKind getDeclLanguage(const Decl *D) {
4351 switch (D->getKind()) {
4352 default:
4353 break;
4354 case Decl::ImplicitParam:
4355 case Decl::ObjCAtDefsField:
4356 case Decl::ObjCCategory:
4357 case Decl::ObjCCategoryImpl:
4358 case Decl::ObjCClass:
4359 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004360 case Decl::ObjCForwardProtocol:
4361 case Decl::ObjCImplementation:
4362 case Decl::ObjCInterface:
4363 case Decl::ObjCIvar:
4364 case Decl::ObjCMethod:
4365 case Decl::ObjCProperty:
4366 case Decl::ObjCPropertyImpl:
4367 case Decl::ObjCProtocol:
4368 return CXLanguage_ObjC;
4369 case Decl::CXXConstructor:
4370 case Decl::CXXConversion:
4371 case Decl::CXXDestructor:
4372 case Decl::CXXMethod:
4373 case Decl::CXXRecord:
4374 case Decl::ClassTemplate:
4375 case Decl::ClassTemplatePartialSpecialization:
4376 case Decl::ClassTemplateSpecialization:
4377 case Decl::Friend:
4378 case Decl::FriendTemplate:
4379 case Decl::FunctionTemplate:
4380 case Decl::LinkageSpec:
4381 case Decl::Namespace:
4382 case Decl::NamespaceAlias:
4383 case Decl::NonTypeTemplateParm:
4384 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004385 case Decl::TemplateTemplateParm:
4386 case Decl::TemplateTypeParm:
4387 case Decl::UnresolvedUsingTypename:
4388 case Decl::UnresolvedUsingValue:
4389 case Decl::Using:
4390 case Decl::UsingDirective:
4391 case Decl::UsingShadow:
4392 return CXLanguage_CPlusPlus;
4393 }
4394
4395 return CXLanguage_C;
4396}
4397
4398extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004399
4400enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4401 if (clang_isDeclaration(cursor.kind))
4402 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4403 if (D->hasAttr<UnavailableAttr>() ||
4404 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4405 return CXAvailability_Available;
4406
4407 if (D->hasAttr<DeprecatedAttr>())
4408 return CXAvailability_Deprecated;
4409 }
4410
4411 return CXAvailability_Available;
4412}
4413
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004414CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4415 if (clang_isDeclaration(cursor.kind))
4416 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4417
4418 return CXLanguage_Invalid;
4419}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004420
4421CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4422 if (clang_isDeclaration(cursor.kind)) {
4423 if (Decl *D = getCursorDecl(cursor)) {
4424 DeclContext *DC = D->getDeclContext();
4425 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4426 }
4427 }
4428
4429 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4430 if (Decl *D = getCursorDecl(cursor))
4431 return MakeCXCursor(D, getCursorASTUnit(cursor));
4432 }
4433
4434 return clang_getNullCursor();
4435}
4436
4437CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4438 if (clang_isDeclaration(cursor.kind)) {
4439 if (Decl *D = getCursorDecl(cursor)) {
4440 DeclContext *DC = D->getLexicalDeclContext();
4441 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4442 }
4443 }
4444
4445 // FIXME: Note that we can't easily compute the lexical context of a
4446 // statement or expression, so we return nothing.
4447 return clang_getNullCursor();
4448}
4449
Douglas Gregor9f592342010-10-01 20:25:15 +00004450static void CollectOverriddenMethods(DeclContext *Ctx,
4451 ObjCMethodDecl *Method,
4452 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4453 if (!Ctx)
4454 return;
4455
4456 // If we have a class or category implementation, jump straight to the
4457 // interface.
4458 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4459 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4460
4461 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4462 if (!Container)
4463 return;
4464
4465 // Check whether we have a matching method at this level.
4466 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4467 Method->isInstanceMethod()))
4468 if (Method != Overridden) {
4469 // We found an override at this level; there is no need to look
4470 // into other protocols or categories.
4471 Methods.push_back(Overridden);
4472 return;
4473 }
4474
4475 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4476 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4477 PEnd = Protocol->protocol_end();
4478 P != PEnd; ++P)
4479 CollectOverriddenMethods(*P, Method, Methods);
4480 }
4481
4482 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4483 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4484 PEnd = Category->protocol_end();
4485 P != PEnd; ++P)
4486 CollectOverriddenMethods(*P, Method, Methods);
4487 }
4488
4489 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4490 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4491 PEnd = Interface->protocol_end();
4492 P != PEnd; ++P)
4493 CollectOverriddenMethods(*P, Method, Methods);
4494
4495 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4496 Category; Category = Category->getNextClassCategory())
4497 CollectOverriddenMethods(Category, Method, Methods);
4498
4499 // We only look into the superclass if we haven't found anything yet.
4500 if (Methods.empty())
4501 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4502 return CollectOverriddenMethods(Super, Method, Methods);
4503 }
4504}
4505
4506void clang_getOverriddenCursors(CXCursor cursor,
4507 CXCursor **overridden,
4508 unsigned *num_overridden) {
4509 if (overridden)
4510 *overridden = 0;
4511 if (num_overridden)
4512 *num_overridden = 0;
4513 if (!overridden || !num_overridden)
4514 return;
4515
4516 if (!clang_isDeclaration(cursor.kind))
4517 return;
4518
4519 Decl *D = getCursorDecl(cursor);
4520 if (!D)
4521 return;
4522
4523 // Handle C++ member functions.
4524 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4525 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4526 *num_overridden = CXXMethod->size_overridden_methods();
4527 if (!*num_overridden)
4528 return;
4529
4530 *overridden = new CXCursor [*num_overridden];
4531 unsigned I = 0;
4532 for (CXXMethodDecl::method_iterator
4533 M = CXXMethod->begin_overridden_methods(),
4534 MEnd = CXXMethod->end_overridden_methods();
4535 M != MEnd; (void)++M, ++I)
4536 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4537 return;
4538 }
4539
4540 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4541 if (!Method)
4542 return;
4543
4544 // Handle Objective-C methods.
4545 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4546 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4547
4548 if (Methods.empty())
4549 return;
4550
4551 *num_overridden = Methods.size();
4552 *overridden = new CXCursor [Methods.size()];
4553 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4554 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4555}
4556
4557void clang_disposeOverriddenCursors(CXCursor *overridden) {
4558 delete [] overridden;
4559}
4560
Douglas Gregorecdcb882010-10-20 22:00:55 +00004561CXFile clang_getIncludedFile(CXCursor cursor) {
4562 if (cursor.kind != CXCursor_InclusionDirective)
4563 return 0;
4564
4565 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4566 return (void *)ID->getFile();
4567}
4568
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004569} // end: extern "C"
4570
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004571
4572//===----------------------------------------------------------------------===//
4573// C++ AST instrospection.
4574//===----------------------------------------------------------------------===//
4575
4576extern "C" {
4577unsigned clang_CXXMethod_isStatic(CXCursor C) {
4578 if (!clang_isDeclaration(C.kind))
4579 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004580
4581 CXXMethodDecl *Method = 0;
4582 Decl *D = cxcursor::getCursorDecl(C);
4583 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4584 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4585 else
4586 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4587 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004588}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004589
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004590} // end: extern "C"
4591
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004592//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004593// Attribute introspection.
4594//===----------------------------------------------------------------------===//
4595
4596extern "C" {
4597CXType clang_getIBOutletCollectionType(CXCursor C) {
4598 if (C.kind != CXCursor_IBOutletCollectionAttr)
4599 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4600
4601 IBOutletCollectionAttr *A =
4602 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4603
4604 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4605}
4606} // end: extern "C"
4607
4608//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004609// CXString Operations.
4610//===----------------------------------------------------------------------===//
4611
4612extern "C" {
4613const char *clang_getCString(CXString string) {
4614 return string.Spelling;
4615}
4616
4617void clang_disposeString(CXString string) {
4618 if (string.MustFreeString && string.Spelling)
4619 free((void*)string.Spelling);
4620}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004621
Ted Kremenekfb480492010-01-13 21:46:36 +00004622} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004623
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004624namespace clang { namespace cxstring {
4625CXString createCXString(const char *String, bool DupString){
4626 CXString Str;
4627 if (DupString) {
4628 Str.Spelling = strdup(String);
4629 Str.MustFreeString = 1;
4630 } else {
4631 Str.Spelling = String;
4632 Str.MustFreeString = 0;
4633 }
4634 return Str;
4635}
4636
4637CXString createCXString(llvm::StringRef String, bool DupString) {
4638 CXString Result;
4639 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4640 char *Spelling = (char *)malloc(String.size() + 1);
4641 memmove(Spelling, String.data(), String.size());
4642 Spelling[String.size()] = 0;
4643 Result.Spelling = Spelling;
4644 Result.MustFreeString = 1;
4645 } else {
4646 Result.Spelling = String.data();
4647 Result.MustFreeString = 0;
4648 }
4649 return Result;
4650}
4651}}
4652
Ted Kremenek04bb7162010-01-22 22:44:15 +00004653//===----------------------------------------------------------------------===//
4654// Misc. utility functions.
4655//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004656
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004657/// Default to using an 8 MB stack size on "safety" threads.
4658static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004659
4660namespace clang {
4661
4662bool RunSafely(llvm::CrashRecoveryContext &CRC,
4663 void (*Fn)(void*), void *UserData) {
4664 if (unsigned Size = GetSafetyThreadStackSize())
4665 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4666 return CRC.RunSafely(Fn, UserData);
4667}
4668
4669unsigned GetSafetyThreadStackSize() {
4670 return SafetyStackThreadSize;
4671}
4672
4673void SetSafetyThreadStackSize(unsigned Value) {
4674 SafetyStackThreadSize = Value;
4675}
4676
4677}
4678
Ted Kremenek04bb7162010-01-22 22:44:15 +00004679extern "C" {
4680
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004681CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004682 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004683}
4684
4685} // end: extern "C"