blob: 4f551b4190e1a9e0415cf8deaed8b4026c171d66 [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"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000034#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor02465752009-10-16 21:24:31 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000036#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000037#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000038#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000039#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000040#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000041
Benjamin Kramerc2a98162010-03-13 21:22:49 +000042// Needed to define L_TMPNAM on some systems.
43#include <cstdio>
44
Steve Naroff50398192009-08-28 15:28:48 +000045using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000046using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000047using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000048
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000049//===----------------------------------------------------------------------===//
50// Crash Reporting.
51//===----------------------------------------------------------------------===//
52
Ted Kremenekd7ffd082010-05-22 00:06:46 +000053#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000054#include "clang/Analysis/Support/SaveAndRestore.h"
55// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000056static const char *__crashreporter_info__ = 0;
57asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000058#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000059static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000060static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000061static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
62static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
63
64static unsigned SetCrashTracerInfo(const char *str,
65 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000066
Ted Kremenek254ba7c2010-01-07 23:13:53 +000067 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000068 while (crashtracer_strings[slot]) {
69 if (++slot == NUM_CRASH_STRINGS)
70 slot = 0;
71 }
72 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000073 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000074
75 // We need to create an aggregate string because multiple threads
76 // may be in this method at one time. The crash reporter string
77 // will attempt to overapproximate the set of in-flight invocations
78 // of this function. Race conditions can still cause this goal
79 // to not be achieved.
80 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000081 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000082 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
83 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
84 }
85 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
86 return slot;
87}
88
89static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000090 unsigned max_slot = 0;
91 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000092
Ted Kremenek254ba7c2010-01-07 23:13:53 +000093 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
94
95 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
96 if (agg_crashtracer_strings[i] &&
97 crashtracer_counter_id[i] > max_value) {
98 max_slot = i;
99 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +0000100 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +0000101
102 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +0000103}
104
105namespace {
106class ArgsCrashTracerInfo {
107 llvm::SmallString<1024> CrashString;
108 llvm::SmallString<1024> AggregateString;
109 unsigned crashtracerSlot;
110public:
111 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
112 : crashtracerSlot(0)
113 {
114 {
115 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000116 Out << "ClangCIndex [" << getClangFullVersion() << "]"
117 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000118 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
119 E=Args.end(); I!=E; ++I)
120 Out << ' ' << *I;
121 }
122 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
123 AggregateString);
124 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000125
Ted Kremenek29b72842010-01-07 22:49:05 +0000126 ~ArgsCrashTracerInfo() {
127 ResetCrashTracerInfo(crashtracerSlot);
128 }
129};
130}
131#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000133/// \brief The result of comparing two source ranges.
134enum RangeComparisonResult {
135 /// \brief Either the ranges overlap or one of the ranges is invalid.
136 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000137
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000138 /// \brief The first range ends before the second range starts.
139 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000140
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141 /// \brief The first range starts after the second range ends.
142 RangeAfter
143};
144
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000145/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000146/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000147static RangeComparisonResult RangeCompare(SourceManager &SM,
148 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000149 SourceRange R2) {
150 assert(R1.isValid() && "First range is invalid?");
151 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000152 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000153 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000154 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000155 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000156 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000157 return RangeAfter;
158 return RangeOverlap;
159}
160
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000161/// \brief Determine if a source location falls within, before, or after a
162/// a given source range.
163static RangeComparisonResult LocationCompare(SourceManager &SM,
164 SourceLocation L, SourceRange R) {
165 assert(R.isValid() && "First range is invalid?");
166 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000167 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000168 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000169 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
170 return RangeBefore;
171 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
172 return RangeAfter;
173 return RangeOverlap;
174}
175
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000176/// \brief Translate a Clang source range into a CIndex source range.
177///
178/// Clang internally represents ranges where the end location points to the
179/// start of the token at the end. However, for external clients it is more
180/// useful to have a CXSourceRange be a proper half-open interval. This routine
181/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000183 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000184 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000186 // location accordingly.
187 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000188 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000189 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000190 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000191 EndLoc = EndLoc.getFileLocWithOffset(Length);
192 }
193
194 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
195 R.getBegin().getRawEncoding(),
196 EndLoc.getRawEncoding() };
197 return Result;
198}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000199
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000200//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000201// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000202//===----------------------------------------------------------------------===//
203
Steve Naroff89922f82009-08-31 00:59:03 +0000204namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
Douglas Gregorb1373d02010-01-20 20:59:29 +0000206// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000207class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000208 public TypeLocVisitor<CursorVisitor, bool>,
209 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000210{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000212 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000213
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000215 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000216
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000217 /// \brief The declaration that serves at the parent of any statement or
218 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000219 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000221 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000222 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000224 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000225 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000226
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000227 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
228 // to the visitor. Declarations with a PCH level greater than this value will
229 // be suppressed.
230 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000231
232 /// \brief When valid, a source range to which the cursor should restrict
233 /// its search.
234 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
Douglas Gregorb1373d02010-01-20 20:59:29 +0000236 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000237 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000238 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000239
240 /// \brief Determine whether this particular source range comes before, comes
241 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000242 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000243 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000244 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
245
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000246 class SetParentRAII {
247 CXCursor &Parent;
248 Decl *&StmtParent;
249 CXCursor OldParent;
250
251 public:
252 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
253 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
254 {
255 Parent = NewParent;
256 if (clang_isDeclaration(Parent.kind))
257 StmtParent = getCursorDecl(Parent);
258 }
259
260 ~SetParentRAII() {
261 Parent = OldParent;
262 if (clang_isDeclaration(Parent.kind))
263 StmtParent = getCursorDecl(Parent);
264 }
265 };
266
Steve Naroff89922f82009-08-31 00:59:03 +0000267public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000268 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
269 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000270 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000271 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000272 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 {
274 Parent.kind = CXCursor_NoDeclFound;
275 Parent.data[0] = 0;
276 Parent.data[1] = 0;
277 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000278 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000279 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000280
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000281 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000282
283 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
284 getPreprocessedEntities();
285
Douglas Gregorb1373d02010-01-20 20:59:29 +0000286 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000287
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000288 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000289 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000290 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000291 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000292 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000293 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
294 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000295 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000296 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000297 bool VisitClassTemplatePartialSpecializationDecl(
298 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000299 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000300 bool VisitEnumConstantDecl(EnumConstantDecl *D);
301 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
302 bool VisitFunctionDecl(FunctionDecl *ND);
303 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000304 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000305 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000306 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000307 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000308 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000309 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
310 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
311 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
312 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000313 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000314 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
315 bool VisitObjCImplDecl(ObjCImplDecl *D);
316 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
317 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000318 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
319 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
320 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000321 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000322 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000323 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000324 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000325 bool VisitUsingDecl(UsingDecl *D);
326 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
327 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000328
Douglas Gregor01829d32010-08-31 14:41:23 +0000329 // Name visitor
330 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000331 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000332
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000333 // Template visitors
334 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000335 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000336 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
337
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000338 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000339 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000340 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000341 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000342 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
343 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000344 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000345 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000346 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000347 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
348 bool VisitPointerTypeLoc(PointerTypeLoc TL);
349 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
350 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
351 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
352 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000353 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000354 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000355 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000356 // FIXME: Implement visitors here when the unimplemented TypeLocs get
357 // implemented
358 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
359 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000360
Douglas Gregora59e3902010-01-21 23:27:09 +0000361 // Statement visitors
362 bool VisitStmt(Stmt *S);
363 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000364 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000365 bool VisitIfStmt(IfStmt *S);
366 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000367 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000368 bool VisitWhileStmt(WhileStmt *S);
369 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000370
Douglas Gregor336fd812010-01-23 00:40:08 +0000371 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000372 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000373 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000374 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000375 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000376 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000377 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000378 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000379 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000380 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000381 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000382 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000383 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
384 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000385 bool VisitInitListExpr(InitListExpr *E);
386 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000387 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000388 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000389 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000390 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
391 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000392 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000393 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000394 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000395 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000396 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000397 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000398 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000399 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000400};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000401
Ted Kremenekab188932010-01-05 19:32:54 +0000402} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000403
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000404static SourceRange getRawCursorExtent(CXCursor C);
405
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000406RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000407 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
408}
409
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410/// \brief Visit the given cursor and, if requested by the visitor,
411/// its children.
412///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000413/// \param Cursor the cursor to visit.
414///
415/// \param CheckRegionOfInterest if true, then the caller already checked that
416/// this cursor is within the region of interest.
417///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418/// \returns true if the visitation should be aborted, false if it
419/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000420bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 if (clang_isInvalid(Cursor.kind))
422 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000423
Douglas Gregorb1373d02010-01-20 20:59:29 +0000424 if (clang_isDeclaration(Cursor.kind)) {
425 Decl *D = getCursorDecl(Cursor);
426 assert(D && "Invalid declaration cursor");
427 if (D->getPCHLevel() > MaxPCHLevel)
428 return false;
429
430 if (D->isImplicit())
431 return false;
432 }
433
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000434 // If we have a range of interest, and this cursor doesn't intersect with it,
435 // we're done.
436 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000437 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000438 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000439 return false;
440 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000441
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 switch (Visitor(Cursor, Parent, ClientData)) {
443 case CXChildVisit_Break:
444 return true;
445
446 case CXChildVisit_Continue:
447 return false;
448
449 case CXChildVisit_Recurse:
450 return VisitChildren(Cursor);
451 }
452
Douglas Gregorfd643772010-01-25 16:45:46 +0000453 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454}
455
Douglas Gregor788f5a12010-03-20 00:41:21 +0000456std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
457CursorVisitor::getPreprocessedEntities() {
458 PreprocessingRecord &PPRec
459 = *TU->getPreprocessor().getPreprocessingRecord();
460
461 bool OnlyLocalDecls
462 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
463
464 // There is no region of interest; we have to walk everything.
465 if (RegionOfInterest.isInvalid())
466 return std::make_pair(PPRec.begin(OnlyLocalDecls),
467 PPRec.end(OnlyLocalDecls));
468
469 // Find the file in which the region of interest lands.
470 SourceManager &SM = TU->getSourceManager();
471 std::pair<FileID, unsigned> Begin
472 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
473 std::pair<FileID, unsigned> End
474 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
475
476 // The region of interest spans files; we have to walk everything.
477 if (Begin.first != End.first)
478 return std::make_pair(PPRec.begin(OnlyLocalDecls),
479 PPRec.end(OnlyLocalDecls));
480
481 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
482 = TU->getPreprocessedEntitiesByFile();
483 if (ByFileMap.empty()) {
484 // Build the mapping from files to sets of preprocessed entities.
485 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
486 EEnd = PPRec.end(OnlyLocalDecls);
487 E != EEnd; ++E) {
488 std::pair<FileID, unsigned> P
489 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
490 ByFileMap[P.first].push_back(*E);
491 }
492 }
493
494 return std::make_pair(ByFileMap[Begin.first].begin(),
495 ByFileMap[Begin.first].end());
496}
497
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498/// \brief Visit the children of the given cursor.
499///
500/// \returns true if the visitation should be aborted, false if it
501/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000502bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000503 if (clang_isReference(Cursor.kind)) {
504 // By definition, references have no children.
505 return false;
506 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000507
508 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000510 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 if (clang_isDeclaration(Cursor.kind)) {
513 Decl *D = getCursorDecl(Cursor);
514 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000515 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000517
Douglas Gregora59e3902010-01-21 23:27:09 +0000518 if (clang_isStatement(Cursor.kind))
519 return Visit(getCursorStmt(Cursor));
520 if (clang_isExpression(Cursor.kind))
521 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000522
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000524 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000525 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
526 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000527 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
528 TLEnd = CXXUnit->top_level_end();
529 TL != TLEnd; ++TL) {
530 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000531 return true;
532 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000533 } else if (VisitDeclContext(
534 CXXUnit->getASTContext().getTranslationUnitDecl()))
535 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000536
Douglas Gregor0396f462010-03-19 05:22:59 +0000537 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000538 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000539 // FIXME: Once we have the ability to deserialize a preprocessing record,
540 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000541 PreprocessingRecord::iterator E, EEnd;
542 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000543 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
544 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
545 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000546
Douglas Gregor0396f462010-03-19 05:22:59 +0000547 continue;
548 }
549
550 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
551 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
552 return true;
553
554 continue;
555 }
556 }
557 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000558 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000560
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000562 return false;
563}
564
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000565bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000566 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
567 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000568
Ted Kremenek664cffd2010-07-22 11:30:19 +0000569 if (Stmt *Body = B->getBody())
570 return Visit(MakeCXCursor(Body, StmtParent, TU));
571
572 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000573}
574
Douglas Gregorb1373d02010-01-20 20:59:29 +0000575bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000576 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000577 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000578
Ted Kremenek23173d72010-05-18 21:09:07 +0000579 Decl *D = *I;
580 if (D->getLexicalDeclContext() != DC)
581 continue;
582
583 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000585 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000586 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000587 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000588 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000589
590 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000591 case RangeBefore:
592 // This declaration comes before the region of interest; skip it.
593 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000594
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000595 case RangeAfter:
596 // This declaration comes after the region of interest; we're done.
597 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000599 case RangeOverlap:
600 // This declaration overlaps the region of interest; visit it.
601 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000602 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000603 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604
Daniel Dunbard52864b2010-02-14 10:02:57 +0000605 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000606 return true;
607 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000608
Douglas Gregorb1373d02010-01-20 20:59:29 +0000609 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000610}
611
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000612bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
613 llvm_unreachable("Translation units are visited directly by Visit()");
614 return false;
615}
616
617bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
618 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
619 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000620
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000621 return false;
622}
623
624bool CursorVisitor::VisitTagDecl(TagDecl *D) {
625 return VisitDeclContext(D);
626}
627
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000628bool CursorVisitor::VisitClassTemplateSpecializationDecl(
629 ClassTemplateSpecializationDecl *D) {
630 bool ShouldVisitBody = false;
631 switch (D->getSpecializationKind()) {
632 case TSK_Undeclared:
633 case TSK_ImplicitInstantiation:
634 // Nothing to visit
635 return false;
636
637 case TSK_ExplicitInstantiationDeclaration:
638 case TSK_ExplicitInstantiationDefinition:
639 break;
640
641 case TSK_ExplicitSpecialization:
642 ShouldVisitBody = true;
643 break;
644 }
645
646 // Visit the template arguments used in the specialization.
647 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
648 TypeLoc TL = SpecType->getTypeLoc();
649 if (TemplateSpecializationTypeLoc *TSTLoc
650 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
651 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
652 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
653 return true;
654 }
655 }
656
657 if (ShouldVisitBody && VisitCXXRecordDecl(D))
658 return true;
659
660 return false;
661}
662
Douglas Gregor74dbe642010-08-31 19:31:58 +0000663bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
664 ClassTemplatePartialSpecializationDecl *D) {
665 // FIXME: Visit the "outer" template parameter lists on the TagDecl
666 // before visiting these template parameters.
667 if (VisitTemplateParameters(D->getTemplateParameters()))
668 return true;
669
670 // Visit the partial specialization arguments.
671 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
672 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
673 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
674 return true;
675
676 return VisitCXXRecordDecl(D);
677}
678
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000679bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000680 // Visit the default argument.
681 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
682 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
683 if (Visit(DefArg->getTypeLoc()))
684 return true;
685
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000686 return false;
687}
688
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000689bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
690 if (Expr *Init = D->getInitExpr())
691 return Visit(MakeCXCursor(Init, StmtParent, TU));
692 return false;
693}
694
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000695bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
696 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
697 if (Visit(TSInfo->getTypeLoc()))
698 return true;
699
700 return false;
701}
702
Douglas Gregora67e03f2010-09-09 21:42:20 +0000703/// \brief Compare two base or member initializers based on their source order.
704static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
705 CXXBaseOrMemberInitializer const * const *X
706 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
707 CXXBaseOrMemberInitializer const * const *Y
708 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
709
710 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
711 return -1;
712 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
713 return 1;
714 else
715 return 0;
716}
717
Douglas Gregorb1373d02010-01-20 20:59:29 +0000718bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000719 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
720 // Visit the function declaration's syntactic components in the order
721 // written. This requires a bit of work.
722 TypeLoc TL = TSInfo->getTypeLoc();
723 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
724
725 // If we have a function declared directly (without the use of a typedef),
726 // visit just the return type. Otherwise, just visit the function's type
727 // now.
728 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
729 (!FTL && Visit(TL)))
730 return true;
731
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000732 // Visit the nested-name-specifier, if present.
733 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
734 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
735 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000736
737 // Visit the declaration name.
738 if (VisitDeclarationNameInfo(ND->getNameInfo()))
739 return true;
740
741 // FIXME: Visit explicitly-specified template arguments!
742
743 // Visit the function parameters, if we have a function type.
744 if (FTL && VisitFunctionTypeLoc(*FTL, true))
745 return true;
746
747 // FIXME: Attributes?
748 }
749
Douglas Gregora67e03f2010-09-09 21:42:20 +0000750 if (ND->isThisDeclarationADefinition()) {
751 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
752 // Find the initializers that were written in the source.
753 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
754 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
755 IEnd = Constructor->init_end();
756 I != IEnd; ++I) {
757 if (!(*I)->isWritten())
758 continue;
759
760 WrittenInits.push_back(*I);
761 }
762
763 // Sort the initializers in source order
764 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
765 &CompareCXXBaseOrMemberInitializers);
766
767 // Visit the initializers in source order
768 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
769 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
770 if (Init->isMemberInitializer()) {
771 if (Visit(MakeCursorMemberRef(Init->getMember(),
772 Init->getMemberLocation(), TU)))
773 return true;
774 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
775 if (Visit(BaseInfo->getTypeLoc()))
776 return true;
777 }
778
779 // Visit the initializer value.
780 if (Expr *Initializer = Init->getInit())
781 if (Visit(MakeCXCursor(Initializer, ND, TU)))
782 return true;
783 }
784 }
785
786 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
787 return true;
788 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000789
Douglas Gregorb1373d02010-01-20 20:59:29 +0000790 return false;
791}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000792
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000793bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
794 if (VisitDeclaratorDecl(D))
795 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 if (Expr *BitWidth = D->getBitWidth())
798 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000799
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000800 return false;
801}
802
803bool CursorVisitor::VisitVarDecl(VarDecl *D) {
804 if (VisitDeclaratorDecl(D))
805 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000807 if (Expr *Init = D->getInit())
808 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000809
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000810 return false;
811}
812
Douglas Gregor84b51d72010-09-01 20:16:53 +0000813bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
814 if (VisitDeclaratorDecl(D))
815 return true;
816
817 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
818 if (Expr *DefArg = D->getDefaultArgument())
819 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
820
821 return false;
822}
823
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000824bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
825 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
826 // before visiting these template parameters.
827 if (VisitTemplateParameters(D->getTemplateParameters()))
828 return true;
829
830 return VisitFunctionDecl(D->getTemplatedDecl());
831}
832
Douglas Gregor39d6f072010-08-31 19:02:00 +0000833bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
834 // FIXME: Visit the "outer" template parameter lists on the TagDecl
835 // before visiting these template parameters.
836 if (VisitTemplateParameters(D->getTemplateParameters()))
837 return true;
838
839 return VisitCXXRecordDecl(D->getTemplatedDecl());
840}
841
Douglas Gregor84b51d72010-09-01 20:16:53 +0000842bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
843 if (VisitTemplateParameters(D->getTemplateParameters()))
844 return true;
845
846 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
847 VisitTemplateArgumentLoc(D->getDefaultArgument()))
848 return true;
849
850 return false;
851}
852
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000854 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
855 if (Visit(TSInfo->getTypeLoc()))
856 return true;
857
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000858 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000859 PEnd = ND->param_end();
860 P != PEnd; ++P) {
861 if (Visit(MakeCXCursor(*P, TU)))
862 return true;
863 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000864
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000865 if (ND->isThisDeclarationADefinition() &&
866 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
867 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000868
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000869 return false;
870}
871
Douglas Gregora59e3902010-01-21 23:27:09 +0000872bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
873 return VisitDeclContext(D);
874}
875
Douglas Gregorb1373d02010-01-20 20:59:29 +0000876bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000877 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
878 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000879 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000880
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000881 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
882 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
883 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000884 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000885 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000886
Douglas Gregora59e3902010-01-21 23:27:09 +0000887 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000888}
889
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000890bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
891 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
892 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
893 E = PID->protocol_end(); I != E; ++I, ++PL)
894 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
895 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000896
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000897 return VisitObjCContainerDecl(PID);
898}
899
Ted Kremenek23173d72010-05-18 21:09:07 +0000900bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000901 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000902 return true;
903
Ted Kremenek23173d72010-05-18 21:09:07 +0000904 // FIXME: This implements a workaround with @property declarations also being
905 // installed in the DeclContext for the @interface. Eventually this code
906 // should be removed.
907 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
908 if (!CDecl || !CDecl->IsClassExtension())
909 return false;
910
911 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
912 if (!ID)
913 return false;
914
915 IdentifierInfo *PropertyId = PD->getIdentifier();
916 ObjCPropertyDecl *prevDecl =
917 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
918
919 if (!prevDecl)
920 return false;
921
922 // Visit synthesized methods since they will be skipped when visiting
923 // the @interface.
924 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000925 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000926 if (Visit(MakeCXCursor(MD, TU)))
927 return true;
928
929 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000930 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000931 if (Visit(MakeCXCursor(MD, TU)))
932 return true;
933
934 return false;
935}
936
Douglas Gregorb1373d02010-01-20 20:59:29 +0000937bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000938 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000939 if (D->getSuperClass() &&
940 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000941 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000942 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000943 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000944
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000945 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
946 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
947 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000948 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregora59e3902010-01-21 23:27:09 +0000951 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000952}
953
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000954bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
955 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000956}
957
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000958bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000959 // 'ID' could be null when dealing with invalid code.
960 if (ObjCInterfaceDecl *ID = D->getClassInterface())
961 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
962 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000963
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000964 return VisitObjCImplDecl(D);
965}
966
967bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
968#if 0
969 // Issue callbacks for super class.
970 // FIXME: No source location information!
971 if (D->getSuperClass() &&
972 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000973 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000974 TU)))
975 return true;
976#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000977
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000978 return VisitObjCImplDecl(D);
979}
980
981bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
982 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
983 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
984 E = D->protocol_end();
985 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000986 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000987 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000988
989 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000990}
991
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000992bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
993 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
994 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
995 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000996
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000997 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000998}
999
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001000bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1001 return VisitDeclContext(D);
1002}
1003
Douglas Gregor69319002010-08-31 23:48:11 +00001004bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001005 // Visit nested-name-specifier.
1006 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1007 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1008 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001009
1010 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1011 D->getTargetNameLoc(), TU));
1012}
1013
Douglas Gregor7e242562010-09-01 19:52:22 +00001014bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001015 // Visit nested-name-specifier.
1016 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1017 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1018 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001019
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001020 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1021 return true;
1022
Douglas Gregor7e242562010-09-01 19:52:22 +00001023 return VisitDeclarationNameInfo(D->getNameInfo());
1024}
1025
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001026bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001027 // Visit nested-name-specifier.
1028 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1029 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1030 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001031
1032 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1033 D->getIdentLocation(), TU));
1034}
1035
Douglas Gregor7e242562010-09-01 19:52:22 +00001036bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001037 // Visit nested-name-specifier.
1038 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1039 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1040 return true;
1041
Douglas Gregor7e242562010-09-01 19:52:22 +00001042 return VisitDeclarationNameInfo(D->getNameInfo());
1043}
1044
1045bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1046 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001047 // Visit nested-name-specifier.
1048 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1049 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1050 return true;
1051
Douglas Gregor7e242562010-09-01 19:52:22 +00001052 return false;
1053}
1054
Douglas Gregor01829d32010-08-31 14:41:23 +00001055bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1056 switch (Name.getName().getNameKind()) {
1057 case clang::DeclarationName::Identifier:
1058 case clang::DeclarationName::CXXLiteralOperatorName:
1059 case clang::DeclarationName::CXXOperatorName:
1060 case clang::DeclarationName::CXXUsingDirective:
1061 return false;
1062
1063 case clang::DeclarationName::CXXConstructorName:
1064 case clang::DeclarationName::CXXDestructorName:
1065 case clang::DeclarationName::CXXConversionFunctionName:
1066 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1067 return Visit(TSInfo->getTypeLoc());
1068 return false;
1069
1070 case clang::DeclarationName::ObjCZeroArgSelector:
1071 case clang::DeclarationName::ObjCOneArgSelector:
1072 case clang::DeclarationName::ObjCMultiArgSelector:
1073 // FIXME: Per-identifier location info?
1074 return false;
1075 }
1076
1077 return false;
1078}
1079
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1081 SourceRange Range) {
1082 // FIXME: This whole routine is a hack to work around the lack of proper
1083 // source information in nested-name-specifiers (PR5791). Since we do have
1084 // a beginning source location, we can visit the first component of the
1085 // nested-name-specifier, if it's a single-token component.
1086 if (!NNS)
1087 return false;
1088
1089 // Get the first component in the nested-name-specifier.
1090 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1091 NNS = Prefix;
1092
1093 switch (NNS->getKind()) {
1094 case NestedNameSpecifier::Namespace:
1095 // FIXME: The token at this source location might actually have been a
1096 // namespace alias, but we don't model that. Lame!
1097 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1098 TU));
1099
1100 case NestedNameSpecifier::TypeSpec: {
1101 // If the type has a form where we know that the beginning of the source
1102 // range matches up with a reference cursor. Visit the appropriate reference
1103 // cursor.
1104 Type *T = NNS->getAsType();
1105 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1106 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1107 if (const TagType *Tag = dyn_cast<TagType>(T))
1108 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1109 if (const TemplateSpecializationType *TST
1110 = dyn_cast<TemplateSpecializationType>(T))
1111 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1112 break;
1113 }
1114
1115 case NestedNameSpecifier::TypeSpecWithTemplate:
1116 case NestedNameSpecifier::Global:
1117 case NestedNameSpecifier::Identifier:
1118 break;
1119 }
1120
1121 return false;
1122}
1123
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001124bool CursorVisitor::VisitTemplateParameters(
1125 const TemplateParameterList *Params) {
1126 if (!Params)
1127 return false;
1128
1129 for (TemplateParameterList::const_iterator P = Params->begin(),
1130 PEnd = Params->end();
1131 P != PEnd; ++P) {
1132 if (Visit(MakeCXCursor(*P, TU)))
1133 return true;
1134 }
1135
1136 return false;
1137}
1138
Douglas Gregor0b36e612010-08-31 20:37:03 +00001139bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1140 switch (Name.getKind()) {
1141 case TemplateName::Template:
1142 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1143
1144 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001145 // Visit the overloaded template set.
1146 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1147 return true;
1148
Douglas Gregor0b36e612010-08-31 20:37:03 +00001149 return false;
1150
1151 case TemplateName::DependentTemplate:
1152 // FIXME: Visit nested-name-specifier.
1153 return false;
1154
1155 case TemplateName::QualifiedTemplate:
1156 // FIXME: Visit nested-name-specifier.
1157 return Visit(MakeCursorTemplateRef(
1158 Name.getAsQualifiedTemplateName()->getDecl(),
1159 Loc, TU));
1160 }
1161
1162 return false;
1163}
1164
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001165bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1166 switch (TAL.getArgument().getKind()) {
1167 case TemplateArgument::Null:
1168 case TemplateArgument::Integral:
1169 return false;
1170
1171 case TemplateArgument::Pack:
1172 // FIXME: Implement when variadic templates come along.
1173 return false;
1174
1175 case TemplateArgument::Type:
1176 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1177 return Visit(TSInfo->getTypeLoc());
1178 return false;
1179
1180 case TemplateArgument::Declaration:
1181 if (Expr *E = TAL.getSourceDeclExpression())
1182 return Visit(MakeCXCursor(E, StmtParent, TU));
1183 return false;
1184
1185 case TemplateArgument::Expression:
1186 if (Expr *E = TAL.getSourceExpression())
1187 return Visit(MakeCXCursor(E, StmtParent, TU));
1188 return false;
1189
1190 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001191 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1192 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001193 }
1194
1195 return false;
1196}
1197
Ted Kremeneka0536d82010-05-07 01:04:29 +00001198bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1199 return VisitDeclContext(D);
1200}
1201
Douglas Gregor01829d32010-08-31 14:41:23 +00001202bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1203 return Visit(TL.getUnqualifiedLoc());
1204}
1205
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001206bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1207 ASTContext &Context = TU->getASTContext();
1208
1209 // Some builtin types (such as Objective-C's "id", "sel", and
1210 // "Class") have associated declarations. Create cursors for those.
1211 QualType VisitType;
1212 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001213 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001214 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001215 case BuiltinType::Char_U:
1216 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001217 case BuiltinType::Char16:
1218 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001219 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001220 case BuiltinType::UInt:
1221 case BuiltinType::ULong:
1222 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001223 case BuiltinType::UInt128:
1224 case BuiltinType::Char_S:
1225 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001226 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001227 case BuiltinType::Short:
1228 case BuiltinType::Int:
1229 case BuiltinType::Long:
1230 case BuiltinType::LongLong:
1231 case BuiltinType::Int128:
1232 case BuiltinType::Float:
1233 case BuiltinType::Double:
1234 case BuiltinType::LongDouble:
1235 case BuiltinType::NullPtr:
1236 case BuiltinType::Overload:
1237 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001238 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001239
1240 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001241 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001242
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001243 case BuiltinType::ObjCId:
1244 VisitType = Context.getObjCIdType();
1245 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001246
1247 case BuiltinType::ObjCClass:
1248 VisitType = Context.getObjCClassType();
1249 break;
1250
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001251 case BuiltinType::ObjCSel:
1252 VisitType = Context.getObjCSelType();
1253 break;
1254 }
1255
1256 if (!VisitType.isNull()) {
1257 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001258 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001259 TU));
1260 }
1261
1262 return false;
1263}
1264
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001265bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1266 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1267}
1268
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001269bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1270 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1271}
1272
1273bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1274 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1275}
1276
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001277bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001278 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001279 // no context information with which we can match up the depth/index in the
1280 // type to the appropriate
1281 return false;
1282}
1283
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001284bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1285 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1286 return true;
1287
John McCallc12c5bb2010-05-15 11:32:37 +00001288 return false;
1289}
1290
1291bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1292 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1293 return true;
1294
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001295 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1296 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1297 TU)))
1298 return true;
1299 }
1300
1301 return false;
1302}
1303
1304bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001305 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001306}
1307
1308bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1309 return Visit(TL.getPointeeLoc());
1310}
1311
1312bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1313 return Visit(TL.getPointeeLoc());
1314}
1315
1316bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1317 return Visit(TL.getPointeeLoc());
1318}
1319
1320bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001321 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001322}
1323
1324bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001325 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001326}
1327
Douglas Gregor01829d32010-08-31 14:41:23 +00001328bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1329 bool SkipResultType) {
1330 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331 return true;
1332
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001334 if (Decl *D = TL.getArg(I))
1335 if (Visit(MakeCXCursor(D, TU)))
1336 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337
1338 return false;
1339}
1340
1341bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1342 if (Visit(TL.getElementLoc()))
1343 return true;
1344
1345 if (Expr *Size = TL.getSizeExpr())
1346 return Visit(MakeCXCursor(Size, StmtParent, TU));
1347
1348 return false;
1349}
1350
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001351bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1352 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001353 // Visit the template name.
1354 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1355 TL.getTemplateNameLoc()))
1356 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001357
1358 // Visit the template arguments.
1359 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1360 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1361 return true;
1362
1363 return false;
1364}
1365
Douglas Gregor2332c112010-01-21 20:48:56 +00001366bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1367 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1368}
1369
1370bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1371 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1372 return Visit(TSInfo->getTypeLoc());
1373
1374 return false;
1375}
1376
Douglas Gregora59e3902010-01-21 23:27:09 +00001377bool CursorVisitor::VisitStmt(Stmt *S) {
1378 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1379 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001380 if (Stmt *C = *Child)
1381 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1382 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001383 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384
Douglas Gregora59e3902010-01-21 23:27:09 +00001385 return false;
1386}
1387
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001388bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1389 // Specially handle CaseStmts because they can be nested, e.g.:
1390 //
1391 // case 1:
1392 // case 2:
1393 //
1394 // In this case the second CaseStmt is the child of the first. Walking
1395 // these recursively can blow out the stack.
1396 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1397 while (true) {
1398 // Set the Parent field to Cursor, then back to its old value once we're
1399 // done.
1400 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1401
1402 if (Stmt *LHS = S->getLHS())
1403 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1404 return true;
1405 if (Stmt *RHS = S->getRHS())
1406 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1407 return true;
1408 if (Stmt *SubStmt = S->getSubStmt()) {
1409 if (!isa<CaseStmt>(SubStmt))
1410 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1411
1412 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1413 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1414 Cursor = MakeCXCursor(CS, StmtParent, TU);
1415 if (RegionOfInterest.isValid()) {
1416 SourceRange Range = CS->getSourceRange();
1417 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1418 return false;
1419 }
1420
1421 switch (Visitor(Cursor, Parent, ClientData)) {
1422 case CXChildVisit_Break: return true;
1423 case CXChildVisit_Continue: return false;
1424 case CXChildVisit_Recurse:
1425 // Perform tail-recursion manually.
1426 S = CS;
1427 continue;
1428 }
1429 }
1430 return false;
1431 }
1432}
1433
Douglas Gregora59e3902010-01-21 23:27:09 +00001434bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1435 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1436 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001437 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001438 return true;
1439 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001440
Douglas Gregora59e3902010-01-21 23:27:09 +00001441 return false;
1442}
1443
Douglas Gregor36897b02010-09-10 00:22:18 +00001444bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1445 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1446}
1447
Douglas Gregorf5bab412010-01-22 01:00:11 +00001448bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1449 if (VarDecl *Var = S->getConditionVariable()) {
1450 if (Visit(MakeCXCursor(Var, TU)))
1451 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001452 }
1453
Douglas Gregor263b47b2010-01-25 16:12:32 +00001454 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1455 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001456 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1457 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001458 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1459 return true;
1460
1461 return false;
1462}
1463
1464bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1465 if (VarDecl *Var = S->getConditionVariable()) {
1466 if (Visit(MakeCXCursor(Var, TU)))
1467 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001468 }
1469
Douglas Gregor263b47b2010-01-25 16:12:32 +00001470 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1471 return true;
1472 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1473 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001474
Douglas Gregor263b47b2010-01-25 16:12:32 +00001475 return false;
1476}
1477
1478bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1479 if (VarDecl *Var = S->getConditionVariable()) {
1480 if (Visit(MakeCXCursor(Var, TU)))
1481 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001482 }
1483
Douglas Gregor263b47b2010-01-25 16:12:32 +00001484 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1485 return true;
1486 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001487 return true;
1488
Douglas Gregor263b47b2010-01-25 16:12:32 +00001489 return false;
1490}
1491
1492bool CursorVisitor::VisitForStmt(ForStmt *S) {
1493 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1494 return true;
1495 if (VarDecl *Var = S->getConditionVariable()) {
1496 if (Visit(MakeCXCursor(Var, TU)))
1497 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001498 }
1499
Douglas Gregor263b47b2010-01-25 16:12:32 +00001500 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1501 return true;
1502 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1503 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001504 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1505 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001506
Douglas Gregorf5bab412010-01-22 01:00:11 +00001507 return false;
1508}
1509
Douglas Gregor8947a752010-09-02 20:35:02 +00001510bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1511 // Visit nested-name-specifier, if present.
1512 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1513 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1514 return true;
1515
1516 // Visit declaration name.
1517 if (VisitDeclarationNameInfo(E->getNameInfo()))
1518 return true;
1519
1520 // Visit explicitly-specified template arguments.
1521 if (E->hasExplicitTemplateArgs()) {
1522 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1523 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1524 *ArgEnd = Arg + Args.NumTemplateArgs;
1525 Arg != ArgEnd; ++Arg)
1526 if (VisitTemplateArgumentLoc(*Arg))
1527 return true;
1528 }
1529
1530 return false;
1531}
1532
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001533bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1534 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1535 return true;
1536
1537 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1538 return true;
1539
1540 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1541 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1542 return true;
1543
1544 return false;
1545}
1546
Ted Kremenek3064ef92010-08-27 21:34:58 +00001547bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1548 if (D->isDefinition()) {
1549 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1550 E = D->bases_end(); I != E; ++I) {
1551 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1552 return true;
1553 }
1554 }
1555
1556 return VisitTagDecl(D);
1557}
1558
1559
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001560bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1561 return Visit(B->getBlockDecl());
1562}
1563
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001564bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001565 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001566 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1567 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001568
1569 // Visit the components of the offsetof expression.
1570 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1571 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1572 const OffsetOfNode &Node = E->getComponent(I);
1573 switch (Node.getKind()) {
1574 case OffsetOfNode::Array:
1575 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1576 StmtParent, TU)))
1577 return true;
1578 break;
1579
1580 case OffsetOfNode::Field:
1581 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1582 TU)))
1583 return true;
1584 break;
1585
1586 case OffsetOfNode::Identifier:
1587 case OffsetOfNode::Base:
1588 continue;
1589 }
1590 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001591
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001592 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001593}
1594
Douglas Gregor336fd812010-01-23 00:40:08 +00001595bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1596 if (E->isArgumentType()) {
1597 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1598 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001599
Douglas Gregor336fd812010-01-23 00:40:08 +00001600 return false;
1601 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001602
Douglas Gregor336fd812010-01-23 00:40:08 +00001603 return VisitExpr(E);
1604}
1605
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001606bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1607 // Visit the base expression.
1608 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1609 return true;
1610
1611 // Visit the nested-name-specifier
1612 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1613 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1614 return true;
1615
1616 // Visit the declaration name.
1617 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1618 return true;
1619
1620 // Visit the explicitly-specified template arguments, if any.
1621 if (E->hasExplicitTemplateArgs()) {
1622 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1623 *ArgEnd = Arg + E->getNumTemplateArgs();
1624 Arg != ArgEnd;
1625 ++Arg) {
1626 if (VisitTemplateArgumentLoc(*Arg))
1627 return true;
1628 }
1629 }
1630
1631 return false;
1632}
1633
Douglas Gregor336fd812010-01-23 00:40:08 +00001634bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1635 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1636 if (Visit(TSInfo->getTypeLoc()))
1637 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001638
Douglas Gregor336fd812010-01-23 00:40:08 +00001639 return VisitCastExpr(E);
1640}
1641
1642bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1643 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1644 if (Visit(TSInfo->getTypeLoc()))
1645 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001646
Douglas Gregor336fd812010-01-23 00:40:08 +00001647 return VisitExpr(E);
1648}
1649
Douglas Gregor36897b02010-09-10 00:22:18 +00001650bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1651 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1652}
1653
Douglas Gregor648220e2010-08-10 15:02:34 +00001654bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1655 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1656 Visit(E->getArgTInfo2()->getTypeLoc());
1657}
1658
1659bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1660 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1661 return true;
1662
1663 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1664}
1665
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001666bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1667 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001668 if (InitListExpr *Syntactic = E->getSyntacticForm())
1669 return VisitExpr(Syntactic);
1670
1671 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001672}
1673
1674bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1675 // Visit the designators.
1676 typedef DesignatedInitExpr::Designator Designator;
1677 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1678 DEnd = E->designators_end();
1679 D != DEnd; ++D) {
1680 if (D->isFieldDesignator()) {
1681 if (FieldDecl *Field = D->getField())
1682 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1683 return true;
1684
1685 continue;
1686 }
1687
1688 if (D->isArrayDesignator()) {
1689 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1690 return true;
1691
1692 continue;
1693 }
1694
1695 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1696 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1697 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1698 return true;
1699 }
1700
1701 // Visit the initializer value itself.
1702 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1703}
1704
Douglas Gregor94802292010-09-02 21:20:16 +00001705bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1706 if (E->isTypeOperand()) {
1707 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1708 return Visit(TSInfo->getTypeLoc());
1709
1710 return false;
1711 }
1712
1713 return VisitExpr(E);
1714}
1715
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001716bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1717 if (E->isTypeOperand()) {
1718 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1719 return Visit(TSInfo->getTypeLoc());
1720
1721 return false;
1722 }
1723
1724 return VisitExpr(E);
1725}
1726
Douglas Gregorab6677e2010-09-08 00:15:04 +00001727bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1728 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1729 return Visit(TSInfo->getTypeLoc());
1730
1731 return VisitExpr(E);
1732}
1733
1734bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1735 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1736 return Visit(TSInfo->getTypeLoc());
1737
1738 return false;
1739}
1740
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001741bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1742 // Visit placement arguments.
1743 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1744 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1745 return true;
1746
1747 // Visit the allocated type.
1748 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1749 if (Visit(TSInfo->getTypeLoc()))
1750 return true;
1751
1752 // Visit the array size, if any.
1753 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1754 return true;
1755
1756 // Visit the initializer or constructor arguments.
1757 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1758 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1759 return true;
1760
1761 return false;
1762}
1763
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001764bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1765 // Visit base expression.
1766 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1767 return true;
1768
1769 // Visit the nested-name-specifier.
1770 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1771 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1772 return true;
1773
1774 // Visit the scope type that looks disturbingly like the nested-name-specifier
1775 // but isn't.
1776 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1777 if (Visit(TSInfo->getTypeLoc()))
1778 return true;
1779
1780 // Visit the name of the type being destroyed.
1781 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1782 if (Visit(TSInfo->getTypeLoc()))
1783 return true;
1784
1785 return false;
1786}
1787
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001788bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1789 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1790}
1791
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001792bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001793 // Visit the nested-name-specifier.
1794 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1795 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1796 return true;
1797
1798 // Visit the declaration name.
1799 if (VisitDeclarationNameInfo(E->getNameInfo()))
1800 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001801
1802 // Visit the overloaded declaration reference.
1803 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1804 return true;
1805
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001806 // Visit the explicitly-specified template arguments.
1807 if (const ExplicitTemplateArgumentList *ArgList
1808 = E->getOptionalExplicitTemplateArgs()) {
1809 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1810 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1811 Arg != ArgEnd; ++Arg) {
1812 if (VisitTemplateArgumentLoc(*Arg))
1813 return true;
1814 }
1815 }
1816
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001817 return false;
1818}
1819
Douglas Gregorbfebed22010-09-03 17:24:10 +00001820bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1821 DependentScopeDeclRefExpr *E) {
1822 // Visit the nested-name-specifier.
1823 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1824 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1825 return true;
1826
1827 // Visit the declaration name.
1828 if (VisitDeclarationNameInfo(E->getNameInfo()))
1829 return true;
1830
1831 // Visit the explicitly-specified template arguments.
1832 if (const ExplicitTemplateArgumentList *ArgList
1833 = E->getOptionalExplicitTemplateArgs()) {
1834 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1835 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1836 Arg != ArgEnd; ++Arg) {
1837 if (VisitTemplateArgumentLoc(*Arg))
1838 return true;
1839 }
1840 }
1841
1842 return false;
1843}
1844
Douglas Gregorab6677e2010-09-08 00:15:04 +00001845bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1846 CXXUnresolvedConstructExpr *E) {
1847 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1848 if (Visit(TSInfo->getTypeLoc()))
1849 return true;
1850
1851 return VisitExpr(E);
1852}
1853
Douglas Gregor25d63622010-09-03 17:35:34 +00001854bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1855 CXXDependentScopeMemberExpr *E) {
1856 // Visit the base expression, if there is one.
1857 if (!E->isImplicitAccess() &&
1858 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1859 return true;
1860
1861 // Visit the nested-name-specifier.
1862 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1863 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1864 return true;
1865
1866 // Visit the declaration name.
1867 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1868 return true;
1869
1870 // Visit the explicitly-specified template arguments.
1871 if (const ExplicitTemplateArgumentList *ArgList
1872 = E->getOptionalExplicitTemplateArgs()) {
1873 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1874 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1875 Arg != ArgEnd; ++Arg) {
1876 if (VisitTemplateArgumentLoc(*Arg))
1877 return true;
1878 }
1879 }
1880
1881 return false;
1882}
1883
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001884bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1885 // Visit the base expression, if there is one.
1886 if (!E->isImplicitAccess() &&
1887 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1888 return true;
1889
1890 return VisitOverloadExpr(E);
1891}
Douglas Gregor25d63622010-09-03 17:35:34 +00001892
Douglas Gregorc2350e52010-03-08 16:40:19 +00001893bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001894 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1895 if (Visit(TSInfo->getTypeLoc()))
1896 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001897
1898 return VisitExpr(E);
1899}
1900
Douglas Gregor81d34662010-04-20 15:39:42 +00001901bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1902 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1903}
1904
1905
Ted Kremenek09dfa372010-02-18 05:46:33 +00001906bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001907 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1908 i != e; ++i)
1909 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001910 return true;
1911
1912 return false;
1913}
1914
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001915static llvm::sys::Mutex EnableMultithreadingMutex;
1916static bool EnabledMultithreading;
1917
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001918extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001919CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1920 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001921 // We use crash recovery to make some of our APIs more reliable, implicitly
1922 // enable it.
1923 llvm::CrashRecoveryContext::Enable();
1924
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001925 // Enable support for multithreading in LLVM.
1926 {
1927 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
1928 if (!EnabledMultithreading) {
1929 llvm::llvm_start_multithreaded();
1930 EnabledMultithreading = true;
1931 }
1932 }
1933
Douglas Gregora030b7c2010-01-22 20:35:53 +00001934 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001935 if (excludeDeclarationsFromPCH)
1936 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001937 if (displayDiagnostics)
1938 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001939 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001940}
1941
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001942void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001943 if (CIdx)
1944 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001945}
1946
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001947void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001948 if (CIdx) {
1949 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1950 CXXIdx->setUseExternalASTGeneration(value);
1951 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001952}
1953
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001954CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001955 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001956 if (!CIdx)
1957 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001958
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001959 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001960
Douglas Gregor28019772010-04-05 23:52:57 +00001961 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001962 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001963 CXXIdx->getOnlyLocalDecls(),
1964 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001965}
1966
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001967unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00001968 return CXTranslationUnit_PrecompiledPreamble |
1969 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001970}
1971
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001972CXTranslationUnit
1973clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1974 const char *source_filename,
1975 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001976 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001977 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001978 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001979 return clang_parseTranslationUnit(CIdx, source_filename,
1980 command_line_args, num_command_line_args,
1981 unsaved_files, num_unsaved_files,
1982 CXTranslationUnit_DetailedPreprocessingRecord);
1983}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001984
1985struct ParseTranslationUnitInfo {
1986 CXIndex CIdx;
1987 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001988 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001989 int num_command_line_args;
1990 struct CXUnsavedFile *unsaved_files;
1991 unsigned num_unsaved_files;
1992 unsigned options;
1993 CXTranslationUnit result;
1994};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001995static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001996 ParseTranslationUnitInfo *PTUI =
1997 static_cast<ParseTranslationUnitInfo*>(UserData);
1998 CXIndex CIdx = PTUI->CIdx;
1999 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002000 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002001 int num_command_line_args = PTUI->num_command_line_args;
2002 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2003 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2004 unsigned options = PTUI->options;
2005 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002006
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002007 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002008 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002009
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002010 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2011
Douglas Gregor44c181a2010-07-23 00:33:23 +00002012 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002013 bool CompleteTranslationUnit
2014 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002015 bool CacheCodeCompetionResults
2016 = options & CXTranslationUnit_CacheCompletionResults;
2017
Douglas Gregor5352ac02010-01-28 00:27:43 +00002018 // Configure the diagnostics.
2019 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002020 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2021 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002022
Douglas Gregor4db64a42010-01-23 00:14:00 +00002023 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2024 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002025 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002026 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002027 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002028 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2029 Buffer));
2030 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002031
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002032 if (!CXXIdx->getUseExternalASTGeneration()) {
2033 llvm::SmallVector<const char *, 16> Args;
2034
2035 // The 'source_filename' argument is optional. If the caller does not
2036 // specify it then it is assumed that the source file is specified
2037 // in the actual argument list.
2038 if (source_filename)
2039 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002040
2041 // Since the Clang C library is primarily used by batch tools dealing with
2042 // (often very broken) source code, where spell-checking can have a
2043 // significant negative impact on performance (particularly when
2044 // precompiled headers are involved), we disable it by default.
Douglas Gregorfe08e402010-10-02 20:06:51 +00002045 // Only do this if we haven't found a spell-checking-related argument.
2046 bool FoundSpellCheckingArgument = false;
2047 for (int I = 0; I != num_command_line_args; ++I) {
2048 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2049 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2050 FoundSpellCheckingArgument = true;
2051 break;
2052 }
2053 }
2054 if (!FoundSpellCheckingArgument)
2055 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002056
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002057 Args.insert(Args.end(), command_line_args,
2058 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00002059
Douglas Gregor44c181a2010-07-23 00:33:23 +00002060 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00002061 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2062 Args.push_back("-Xclang");
2063 Args.push_back("-detailed-preprocessing-record");
2064 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00002065
Douglas Gregor5352ac02010-01-28 00:27:43 +00002066 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002067
Ted Kremenek29b72842010-01-07 22:49:05 +00002068#ifdef USE_CRASHTRACER
2069 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00002070#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002071
Daniel Dunbar94220972009-12-05 02:17:18 +00002072 llvm::OwningPtr<ASTUnit> Unit(
2073 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00002074 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00002075 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00002076 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002077 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002078 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00002079 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00002080 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002081 CompleteTranslationUnit,
2082 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002083
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002084 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00002085 // Make sure to check that 'Unit' is non-NULL.
2086 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00002087 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2088 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002089 D != DEnd; ++D) {
2090 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00002091 CXString Msg = clang_formatDiagnostic(&Diag,
2092 clang_defaultDiagnosticDisplayOptions());
2093 fprintf(stderr, "%s\n", clang_getCString(Msg));
2094 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002095 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002096#ifdef LLVM_ON_WIN32
2097 // On Windows, force a flush, since there may be multiple copies of
2098 // stderr and stdout in the file system, all with different buffers
2099 // but writing to the same device.
2100 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00002101#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002102 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002103 }
Daniel Dunbar94220972009-12-05 02:17:18 +00002104
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002105 PTUI->result = Unit.take();
2106 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002107 }
2108
Ted Kremenek139ba862009-10-22 00:03:57 +00002109 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002110 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002111
Ted Kremenek139ba862009-10-22 00:03:57 +00002112 // First add the complete path to the 'clang' executable.
2113 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002114 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002115
Ted Kremenek139ba862009-10-22 00:03:57 +00002116 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002117 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002118
Ted Kremenek139ba862009-10-22 00:03:57 +00002119 // The 'source_filename' argument is optional. If the caller does not
2120 // specify it then it is assumed that the source file is specified
2121 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002122 if (source_filename)
2123 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00002124
Steve Naroff37b5ac22009-10-15 20:50:09 +00002125 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00002126 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002127 char astTmpFile[L_tmpnam];
2128 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002129
2130 // Since the Clang C library is primarily used by batch tools dealing with
2131 // (often very broken) source code, where spell-checking can have a
2132 // significant negative impact on performance (particularly when
2133 // precompiled headers are involved), we disable it by default.
2134 // Note that we place this argument early in the list, so that it can be
2135 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00002136 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00002137
Douglas Gregor4db64a42010-01-23 00:14:00 +00002138 // Remap any unsaved files to temporary files.
2139 std::vector<llvm::sys::Path> TemporaryFiles;
2140 std::vector<std::string> RemapArgs;
2141 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002142 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143
Douglas Gregor4db64a42010-01-23 00:14:00 +00002144 // The pointers into the elements of RemapArgs are stable because we
2145 // won't be adding anything to RemapArgs after this point.
2146 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
2147 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
Ted Kremenek139ba862009-10-22 00:03:57 +00002149 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
2150 for (int i = 0; i < num_command_line_args; ++i)
2151 if (const char *arg = command_line_args[i]) {
2152 if (strcmp(arg, "-o") == 0) {
2153 ++i; // Also skip the matching argument.
2154 continue;
2155 }
2156 if (strcmp(arg, "-emit-ast") == 0 ||
2157 strcmp(arg, "-c") == 0 ||
2158 strcmp(arg, "-fsyntax-only") == 0) {
2159 continue;
2160 }
2161
2162 // Keep the argument.
2163 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002164 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002165
Douglas Gregord93256e2010-01-28 06:00:51 +00002166 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002167 char tmpFileResults[L_tmpnam];
2168 char *tmpResultsFileName = tmpnam(tmpFileResults);
2169 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00002170 TemporaryFiles.push_back(DiagnosticsFile);
2171 argv.push_back("-fdiagnostics-binary");
2172
Douglas Gregor44c181a2010-07-23 00:33:23 +00002173 // Do we need the detailed preprocessing record?
2174 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2175 argv.push_back("-Xclang");
2176 argv.push_back("-detailed-preprocessing-record");
2177 }
2178
Ted Kremenek139ba862009-10-22 00:03:57 +00002179 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002180 argv.push_back(NULL);
2181
Ted Kremenekfeb15e32009-10-26 22:14:08 +00002182 // Invoke 'clang'.
2183 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
2184 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00002185 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00002186 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
2187 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00002188 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002189 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00002190 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002191
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002192 if (!ErrMsg.empty()) {
2193 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00002194 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002195 I != E; ++I) {
2196 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00002197 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002198 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00002199 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002200
Daniel Dunbar32141c82010-02-23 20:23:45 +00002201 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00002202 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00002203
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002204 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002205 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002206 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002207 RemappedFiles.size(),
2208 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00002209 if (ATU) {
2210 LoadSerializedDiagnostics(DiagnosticsFile,
2211 num_unsaved_files, unsaved_files,
2212 ATU->getFileManager(),
2213 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00002214 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002215 } else if (CXXIdx->getDisplayDiagnostics()) {
2216 // We failed to load the ASTUnit, but we can still deserialize the
2217 // diagnostics and emit them.
2218 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00002219 Diagnostic Diag;
2220 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002221 // FIXME: Faked LangOpts!
2222 LangOptions LangOpts;
2223 llvm::SmallVector<StoredDiagnostic, 4> Diags;
2224 LoadSerializedDiagnostics(DiagnosticsFile,
2225 num_unsaved_files, unsaved_files,
2226 FileMgr, SourceMgr, Diags);
2227 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
2228 DEnd = Diags.end();
2229 D != DEnd; ++D) {
2230 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00002231 CXString Msg = clang_formatDiagnostic(&Diag,
2232 clang_defaultDiagnosticDisplayOptions());
2233 fprintf(stderr, "%s\n", clang_getCString(Msg));
2234 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002235 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002236
2237#ifdef LLVM_ON_WIN32
2238 // On Windows, force a flush, since there may be multiple copies of
2239 // stderr and stdout in the file system, all with different buffers
2240 // but writing to the same device.
2241 fflush(stderr);
2242#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00002243 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002244
Douglas Gregor313e26c2010-02-18 23:35:40 +00002245 if (ATU) {
2246 // Make the translation unit responsible for destroying all temporary files.
2247 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2248 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002249 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00002250 } else {
2251 // Destroy all of the temporary files now; they can't be referenced any
2252 // longer.
2253 llvm::sys::Path(astTmpFile).eraseFromDisk();
2254 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2255 TemporaryFiles[i].eraseFromDisk();
2256 }
2257
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002258 PTUI->result = ATU;
2259}
2260CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2261 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002262 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002263 int num_command_line_args,
2264 struct CXUnsavedFile *unsaved_files,
2265 unsigned num_unsaved_files,
2266 unsigned options) {
2267 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2268 num_command_line_args, unsaved_files, num_unsaved_files,
2269 options, 0 };
2270 llvm::CrashRecoveryContext CRC;
2271
2272 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002273 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2274 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2275 fprintf(stderr, " 'command_line_args' : [");
2276 for (int i = 0; i != num_command_line_args; ++i) {
2277 if (i)
2278 fprintf(stderr, ", ");
2279 fprintf(stderr, "'%s'", command_line_args[i]);
2280 }
2281 fprintf(stderr, "],\n");
2282 fprintf(stderr, " 'unsaved_files' : [");
2283 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2284 if (i)
2285 fprintf(stderr, ", ");
2286 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2287 unsaved_files[i].Length);
2288 }
2289 fprintf(stderr, "],\n");
2290 fprintf(stderr, " 'options' : %d,\n", options);
2291 fprintf(stderr, "}\n");
2292
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002293 return 0;
2294 }
2295
2296 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002297}
2298
Douglas Gregor19998442010-08-13 15:35:05 +00002299unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2300 return CXSaveTranslationUnit_None;
2301}
2302
2303int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2304 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002305 if (!TU)
2306 return 1;
2307
2308 return static_cast<ASTUnit *>(TU)->Save(FileName);
2309}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002310
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002311void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002312 if (CTUnit) {
2313 // If the translation unit has been marked as unsafe to free, just discard
2314 // it.
2315 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2316 return;
2317
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002318 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002319 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002320}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002321
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002322unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2323 return CXReparse_None;
2324}
2325
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002326struct ReparseTranslationUnitInfo {
2327 CXTranslationUnit TU;
2328 unsigned num_unsaved_files;
2329 struct CXUnsavedFile *unsaved_files;
2330 unsigned options;
2331 int result;
2332};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002333
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002334static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002335 ReparseTranslationUnitInfo *RTUI =
2336 static_cast<ReparseTranslationUnitInfo*>(UserData);
2337 CXTranslationUnit TU = RTUI->TU;
2338 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2339 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2340 unsigned options = RTUI->options;
2341 (void) options;
2342 RTUI->result = 1;
2343
Douglas Gregorabc563f2010-07-19 21:46:24 +00002344 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002345 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002346
2347 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2348 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002349
2350 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2351 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2352 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2353 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002354 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002355 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2356 Buffer));
2357 }
2358
Douglas Gregor593b0c12010-09-23 18:47:53 +00002359 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2360 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002361}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002362
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002363int clang_reparseTranslationUnit(CXTranslationUnit TU,
2364 unsigned num_unsaved_files,
2365 struct CXUnsavedFile *unsaved_files,
2366 unsigned options) {
2367 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2368 options, 0 };
2369 llvm::CrashRecoveryContext CRC;
2370
2371 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002372 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002373 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2374 return 1;
2375 }
2376
2377 return RTUI.result;
2378}
2379
Douglas Gregordf95a132010-08-09 20:45:32 +00002380
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002381CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002382 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002383 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002384
Steve Naroff77accc12009-09-03 18:19:54 +00002385 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002386 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002387}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002388
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002389CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002390 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002391 return Result;
2392}
2393
Ted Kremenekfb480492010-01-13 21:46:36 +00002394} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002395
Ted Kremenekfb480492010-01-13 21:46:36 +00002396//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002397// CXSourceLocation and CXSourceRange Operations.
2398//===----------------------------------------------------------------------===//
2399
Douglas Gregorb9790342010-01-22 21:44:22 +00002400extern "C" {
2401CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002402 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002403 return Result;
2404}
2405
2406unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002407 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2408 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2409 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002410}
2411
2412CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2413 CXFile file,
2414 unsigned line,
2415 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002416 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002417 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002418
Douglas Gregorb9790342010-01-22 21:44:22 +00002419 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2420 SourceLocation SLoc
2421 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002422 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002423 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002424
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002425 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002426}
2427
Douglas Gregor5352ac02010-01-28 00:27:43 +00002428CXSourceRange clang_getNullRange() {
2429 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2430 return Result;
2431}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002432
Douglas Gregor5352ac02010-01-28 00:27:43 +00002433CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2434 if (begin.ptr_data[0] != end.ptr_data[0] ||
2435 begin.ptr_data[1] != end.ptr_data[1])
2436 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002437
2438 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002439 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002440 return Result;
2441}
2442
Douglas Gregor46766dc2010-01-26 19:19:08 +00002443void clang_getInstantiationLocation(CXSourceLocation location,
2444 CXFile *file,
2445 unsigned *line,
2446 unsigned *column,
2447 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002448 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2449
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002450 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002451 if (file)
2452 *file = 0;
2453 if (line)
2454 *line = 0;
2455 if (column)
2456 *column = 0;
2457 if (offset)
2458 *offset = 0;
2459 return;
2460 }
2461
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002462 const SourceManager &SM =
2463 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002464 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002465
2466 if (file)
2467 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2468 if (line)
2469 *line = SM.getInstantiationLineNumber(InstLoc);
2470 if (column)
2471 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002472 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002473 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002474}
2475
Douglas Gregor1db19de2010-01-19 21:36:55 +00002476CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002477 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002478 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002479 return Result;
2480}
2481
2482CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002483 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002484 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002485 return Result;
2486}
2487
Douglas Gregorb9790342010-01-22 21:44:22 +00002488} // end: extern "C"
2489
Douglas Gregor1db19de2010-01-19 21:36:55 +00002490//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002491// CXFile Operations.
2492//===----------------------------------------------------------------------===//
2493
2494extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002495CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002496 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002497 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002498
Steve Naroff88145032009-10-27 14:35:18 +00002499 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002500 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002501}
2502
2503time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002504 if (!SFile)
2505 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002506
Steve Naroff88145032009-10-27 14:35:18 +00002507 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2508 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002509}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002510
Douglas Gregorb9790342010-01-22 21:44:22 +00002511CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2512 if (!tu)
2513 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002514
Douglas Gregorb9790342010-01-22 21:44:22 +00002515 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002516
Douglas Gregorb9790342010-01-22 21:44:22 +00002517 FileManager &FMgr = CXXUnit->getFileManager();
2518 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2519 return const_cast<FileEntry *>(File);
2520}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002521
Ted Kremenekfb480492010-01-13 21:46:36 +00002522} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002523
Ted Kremenekfb480492010-01-13 21:46:36 +00002524//===----------------------------------------------------------------------===//
2525// CXCursor Operations.
2526//===----------------------------------------------------------------------===//
2527
Ted Kremenekfb480492010-01-13 21:46:36 +00002528static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002529 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2530 return getDeclFromExpr(CE->getSubExpr());
2531
Ted Kremenekfb480492010-01-13 21:46:36 +00002532 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2533 return RefExpr->getDecl();
2534 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2535 return ME->getMemberDecl();
2536 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2537 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002538 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2539 return PRE->getProperty();
2540
Ted Kremenekfb480492010-01-13 21:46:36 +00002541 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2542 return getDeclFromExpr(CE->getCallee());
Ted Kremenekfb480492010-01-13 21:46:36 +00002543 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2544 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002545
Douglas Gregordb1314e2010-10-01 21:11:22 +00002546 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2547 return PE->getProtocol();
2548
Ted Kremenekfb480492010-01-13 21:46:36 +00002549 return 0;
2550}
2551
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002552static SourceLocation getLocationFromExpr(Expr *E) {
2553 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2554 return /*FIXME:*/Msg->getLeftLoc();
2555 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2556 return DRE->getLocation();
2557 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2558 return Member->getMemberLoc();
2559 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2560 return Ivar->getLocation();
2561 return E->getLocStart();
2562}
2563
Ted Kremenekfb480492010-01-13 21:46:36 +00002564extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002565
2566unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002567 CXCursorVisitor visitor,
2568 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002569 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002570
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002571 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2572 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002573 return CursorVis.VisitChildren(parent);
2574}
2575
Douglas Gregor78205d42010-01-20 21:45:58 +00002576static CXString getDeclSpelling(Decl *D) {
2577 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2578 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002579 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002580
Douglas Gregor78205d42010-01-20 21:45:58 +00002581 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002582 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002583
Douglas Gregor78205d42010-01-20 21:45:58 +00002584 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2585 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2586 // and returns different names. NamedDecl returns the class name and
2587 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002588 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002589
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002590 if (isa<UsingDirectiveDecl>(D))
2591 return createCXString("");
2592
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002593 llvm::SmallString<1024> S;
2594 llvm::raw_svector_ostream os(S);
2595 ND->printName(os);
2596
2597 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002598}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002599
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002600CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002601 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002602 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002603
Steve Narofff334b4e2009-09-02 18:26:48 +00002604 if (clang_isReference(C.kind)) {
2605 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002606 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002607 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002608 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002609 }
2610 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002611 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002612 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002613 }
2614 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002615 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002616 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002617 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002618 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002619 case CXCursor_CXXBaseSpecifier: {
2620 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2621 return createCXString(B->getType().getAsString());
2622 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002623 case CXCursor_TypeRef: {
2624 TypeDecl *Type = getCursorTypeRef(C).first;
2625 assert(Type && "Missing type decl");
2626
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002627 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2628 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002629 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002630 case CXCursor_TemplateRef: {
2631 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002632 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002633
2634 return createCXString(Template->getNameAsString());
2635 }
Douglas Gregor69319002010-08-31 23:48:11 +00002636
2637 case CXCursor_NamespaceRef: {
2638 NamedDecl *NS = getCursorNamespaceRef(C).first;
2639 assert(NS && "Missing namespace decl");
2640
2641 return createCXString(NS->getNameAsString());
2642 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002643
Douglas Gregora67e03f2010-09-09 21:42:20 +00002644 case CXCursor_MemberRef: {
2645 FieldDecl *Field = getCursorMemberRef(C).first;
2646 assert(Field && "Missing member decl");
2647
2648 return createCXString(Field->getNameAsString());
2649 }
2650
Douglas Gregor36897b02010-09-10 00:22:18 +00002651 case CXCursor_LabelRef: {
2652 LabelStmt *Label = getCursorLabelRef(C).first;
2653 assert(Label && "Missing label");
2654
2655 return createCXString(Label->getID()->getName());
2656 }
2657
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002658 case CXCursor_OverloadedDeclRef: {
2659 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2660 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2661 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2662 return createCXString(ND->getNameAsString());
2663 return createCXString("");
2664 }
2665 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2666 return createCXString(E->getName().getAsString());
2667 OverloadedTemplateStorage *Ovl
2668 = Storage.get<OverloadedTemplateStorage*>();
2669 if (Ovl->size() == 0)
2670 return createCXString("");
2671 return createCXString((*Ovl->begin())->getNameAsString());
2672 }
2673
Daniel Dunbaracca7252009-11-30 20:42:49 +00002674 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002675 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002676 }
2677 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002678
2679 if (clang_isExpression(C.kind)) {
2680 Decl *D = getDeclFromExpr(getCursorExpr(C));
2681 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002682 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002683 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002684 }
2685
Douglas Gregor36897b02010-09-10 00:22:18 +00002686 if (clang_isStatement(C.kind)) {
2687 Stmt *S = getCursorStmt(C);
2688 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2689 return createCXString(Label->getID()->getName());
2690
2691 return createCXString("");
2692 }
2693
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002694 if (C.kind == CXCursor_MacroInstantiation)
2695 return createCXString(getCursorMacroInstantiation(C)->getName()
2696 ->getNameStart());
2697
Douglas Gregor572feb22010-03-18 18:04:21 +00002698 if (C.kind == CXCursor_MacroDefinition)
2699 return createCXString(getCursorMacroDefinition(C)->getName()
2700 ->getNameStart());
2701
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002702 if (clang_isDeclaration(C.kind))
2703 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002704
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002705 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002706}
2707
Ted Kremeneke68fff62010-02-17 00:41:32 +00002708CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002709 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002710 case CXCursor_FunctionDecl:
2711 return createCXString("FunctionDecl");
2712 case CXCursor_TypedefDecl:
2713 return createCXString("TypedefDecl");
2714 case CXCursor_EnumDecl:
2715 return createCXString("EnumDecl");
2716 case CXCursor_EnumConstantDecl:
2717 return createCXString("EnumConstantDecl");
2718 case CXCursor_StructDecl:
2719 return createCXString("StructDecl");
2720 case CXCursor_UnionDecl:
2721 return createCXString("UnionDecl");
2722 case CXCursor_ClassDecl:
2723 return createCXString("ClassDecl");
2724 case CXCursor_FieldDecl:
2725 return createCXString("FieldDecl");
2726 case CXCursor_VarDecl:
2727 return createCXString("VarDecl");
2728 case CXCursor_ParmDecl:
2729 return createCXString("ParmDecl");
2730 case CXCursor_ObjCInterfaceDecl:
2731 return createCXString("ObjCInterfaceDecl");
2732 case CXCursor_ObjCCategoryDecl:
2733 return createCXString("ObjCCategoryDecl");
2734 case CXCursor_ObjCProtocolDecl:
2735 return createCXString("ObjCProtocolDecl");
2736 case CXCursor_ObjCPropertyDecl:
2737 return createCXString("ObjCPropertyDecl");
2738 case CXCursor_ObjCIvarDecl:
2739 return createCXString("ObjCIvarDecl");
2740 case CXCursor_ObjCInstanceMethodDecl:
2741 return createCXString("ObjCInstanceMethodDecl");
2742 case CXCursor_ObjCClassMethodDecl:
2743 return createCXString("ObjCClassMethodDecl");
2744 case CXCursor_ObjCImplementationDecl:
2745 return createCXString("ObjCImplementationDecl");
2746 case CXCursor_ObjCCategoryImplDecl:
2747 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002748 case CXCursor_CXXMethod:
2749 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002750 case CXCursor_UnexposedDecl:
2751 return createCXString("UnexposedDecl");
2752 case CXCursor_ObjCSuperClassRef:
2753 return createCXString("ObjCSuperClassRef");
2754 case CXCursor_ObjCProtocolRef:
2755 return createCXString("ObjCProtocolRef");
2756 case CXCursor_ObjCClassRef:
2757 return createCXString("ObjCClassRef");
2758 case CXCursor_TypeRef:
2759 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002760 case CXCursor_TemplateRef:
2761 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002762 case CXCursor_NamespaceRef:
2763 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002764 case CXCursor_MemberRef:
2765 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002766 case CXCursor_LabelRef:
2767 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002768 case CXCursor_OverloadedDeclRef:
2769 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002770 case CXCursor_UnexposedExpr:
2771 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002772 case CXCursor_BlockExpr:
2773 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002774 case CXCursor_DeclRefExpr:
2775 return createCXString("DeclRefExpr");
2776 case CXCursor_MemberRefExpr:
2777 return createCXString("MemberRefExpr");
2778 case CXCursor_CallExpr:
2779 return createCXString("CallExpr");
2780 case CXCursor_ObjCMessageExpr:
2781 return createCXString("ObjCMessageExpr");
2782 case CXCursor_UnexposedStmt:
2783 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002784 case CXCursor_LabelStmt:
2785 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002786 case CXCursor_InvalidFile:
2787 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002788 case CXCursor_InvalidCode:
2789 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002790 case CXCursor_NoDeclFound:
2791 return createCXString("NoDeclFound");
2792 case CXCursor_NotImplemented:
2793 return createCXString("NotImplemented");
2794 case CXCursor_TranslationUnit:
2795 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002796 case CXCursor_UnexposedAttr:
2797 return createCXString("UnexposedAttr");
2798 case CXCursor_IBActionAttr:
2799 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002800 case CXCursor_IBOutletAttr:
2801 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002802 case CXCursor_IBOutletCollectionAttr:
2803 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002804 case CXCursor_PreprocessingDirective:
2805 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002806 case CXCursor_MacroDefinition:
2807 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002808 case CXCursor_MacroInstantiation:
2809 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002810 case CXCursor_Namespace:
2811 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002812 case CXCursor_LinkageSpec:
2813 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002814 case CXCursor_CXXBaseSpecifier:
2815 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002816 case CXCursor_Constructor:
2817 return createCXString("CXXConstructor");
2818 case CXCursor_Destructor:
2819 return createCXString("CXXDestructor");
2820 case CXCursor_ConversionFunction:
2821 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002822 case CXCursor_TemplateTypeParameter:
2823 return createCXString("TemplateTypeParameter");
2824 case CXCursor_NonTypeTemplateParameter:
2825 return createCXString("NonTypeTemplateParameter");
2826 case CXCursor_TemplateTemplateParameter:
2827 return createCXString("TemplateTemplateParameter");
2828 case CXCursor_FunctionTemplate:
2829 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002830 case CXCursor_ClassTemplate:
2831 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002832 case CXCursor_ClassTemplatePartialSpecialization:
2833 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002834 case CXCursor_NamespaceAlias:
2835 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002836 case CXCursor_UsingDirective:
2837 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002838 case CXCursor_UsingDeclaration:
2839 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002840 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002841
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002842 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002843 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002844}
Steve Naroff89922f82009-08-31 00:59:03 +00002845
Ted Kremeneke68fff62010-02-17 00:41:32 +00002846enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2847 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002848 CXClientData client_data) {
2849 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2850 *BestCursor = cursor;
2851 return CXChildVisit_Recurse;
2852}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002853
Douglas Gregorb9790342010-01-22 21:44:22 +00002854CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2855 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002856 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002857
Douglas Gregorb9790342010-01-22 21:44:22 +00002858 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002859 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2860
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002861 // Translate the given source location to make it point at the beginning of
2862 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002863 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002864
2865 // Guard against an invalid SourceLocation, or we may assert in one
2866 // of the following calls.
2867 if (SLoc.isInvalid())
2868 return clang_getNullCursor();
2869
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002870 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2871 CXXUnit->getASTContext().getLangOptions());
2872
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002873 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2874 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002875 // FIXME: Would be great to have a "hint" cursor, then walk from that
2876 // hint cursor upward until we find a cursor whose source range encloses
2877 // the region of interest, rather than starting from the translation unit.
2878 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002879 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002880 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002881 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002882 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002883 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002884}
2885
Ted Kremenek73885552009-11-17 19:28:59 +00002886CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002887 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002888}
2889
2890unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002891 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002892}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002893
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002894unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002895 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2896}
2897
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002898unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002899 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2900}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002901
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002902unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002903 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2904}
2905
Douglas Gregor97b98722010-01-19 23:20:36 +00002906unsigned clang_isExpression(enum CXCursorKind K) {
2907 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2908}
2909
2910unsigned clang_isStatement(enum CXCursorKind K) {
2911 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2912}
2913
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002914unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2915 return K == CXCursor_TranslationUnit;
2916}
2917
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002918unsigned clang_isPreprocessing(enum CXCursorKind K) {
2919 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2920}
2921
Ted Kremenekad6eff62010-03-08 21:17:29 +00002922unsigned clang_isUnexposed(enum CXCursorKind K) {
2923 switch (K) {
2924 case CXCursor_UnexposedDecl:
2925 case CXCursor_UnexposedExpr:
2926 case CXCursor_UnexposedStmt:
2927 case CXCursor_UnexposedAttr:
2928 return true;
2929 default:
2930 return false;
2931 }
2932}
2933
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002934CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002935 return C.kind;
2936}
2937
Douglas Gregor98258af2010-01-18 22:46:11 +00002938CXSourceLocation clang_getCursorLocation(CXCursor C) {
2939 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002940 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002941 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002942 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2943 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002944 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002945 }
2946
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002947 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002948 std::pair<ObjCProtocolDecl *, SourceLocation> P
2949 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002950 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002951 }
2952
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002953 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002954 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2955 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002956 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002957 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002958
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002959 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002960 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002961 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002962 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002963
2964 case CXCursor_TemplateRef: {
2965 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2966 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2967 }
2968
Douglas Gregor69319002010-08-31 23:48:11 +00002969 case CXCursor_NamespaceRef: {
2970 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2971 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2972 }
2973
Douglas Gregora67e03f2010-09-09 21:42:20 +00002974 case CXCursor_MemberRef: {
2975 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2976 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2977 }
2978
Ted Kremenek3064ef92010-08-27 21:34:58 +00002979 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00002980 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
2981 if (!BaseSpec)
2982 return clang_getNullLocation();
2983
2984 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
2985 return cxloc::translateSourceLocation(getCursorContext(C),
2986 TSInfo->getTypeLoc().getBeginLoc());
2987
2988 return cxloc::translateSourceLocation(getCursorContext(C),
2989 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00002990 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002991
Douglas Gregor36897b02010-09-10 00:22:18 +00002992 case CXCursor_LabelRef: {
2993 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
2994 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
2995 }
2996
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002997 case CXCursor_OverloadedDeclRef:
2998 return cxloc::translateSourceLocation(getCursorContext(C),
2999 getCursorOverloadedDeclRef(C).second);
3000
Douglas Gregorf46034a2010-01-18 23:41:10 +00003001 default:
3002 // FIXME: Need a way to enumerate all non-reference cases.
3003 llvm_unreachable("Missed a reference kind");
3004 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003005 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003006
3007 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003008 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003009 getLocationFromExpr(getCursorExpr(C)));
3010
Douglas Gregor36897b02010-09-10 00:22:18 +00003011 if (clang_isStatement(C.kind))
3012 return cxloc::translateSourceLocation(getCursorContext(C),
3013 getCursorStmt(C)->getLocStart());
3014
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003015 if (C.kind == CXCursor_PreprocessingDirective) {
3016 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3017 return cxloc::translateSourceLocation(getCursorContext(C), L);
3018 }
Douglas Gregor48072312010-03-18 15:23:44 +00003019
3020 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003021 SourceLocation L
3022 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003023 return cxloc::translateSourceLocation(getCursorContext(C), L);
3024 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003025
3026 if (C.kind == CXCursor_MacroDefinition) {
3027 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3028 return cxloc::translateSourceLocation(getCursorContext(C), L);
3029 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003030
Ted Kremenek9a700d22010-05-12 06:16:13 +00003031 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003032 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003033
Douglas Gregorf46034a2010-01-18 23:41:10 +00003034 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003035 SourceLocation Loc = D->getLocation();
3036 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3037 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003038 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003039}
Douglas Gregora7bde202010-01-19 00:34:46 +00003040
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003041} // end extern "C"
3042
3043static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003044 if (clang_isReference(C.kind)) {
3045 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003046 case CXCursor_ObjCSuperClassRef:
3047 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003048
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003049 case CXCursor_ObjCProtocolRef:
3050 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003051
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003052 case CXCursor_ObjCClassRef:
3053 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003054
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003055 case CXCursor_TypeRef:
3056 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003057
3058 case CXCursor_TemplateRef:
3059 return getCursorTemplateRef(C).second;
3060
Douglas Gregor69319002010-08-31 23:48:11 +00003061 case CXCursor_NamespaceRef:
3062 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003063
3064 case CXCursor_MemberRef:
3065 return getCursorMemberRef(C).second;
3066
Ted Kremenek3064ef92010-08-27 21:34:58 +00003067 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003068 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003069
Douglas Gregor36897b02010-09-10 00:22:18 +00003070 case CXCursor_LabelRef:
3071 return getCursorLabelRef(C).second;
3072
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003073 case CXCursor_OverloadedDeclRef:
3074 return getCursorOverloadedDeclRef(C).second;
3075
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003076 default:
3077 // FIXME: Need a way to enumerate all non-reference cases.
3078 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003079 }
3080 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003081
3082 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003083 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003084
3085 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003086 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003087
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003088 if (C.kind == CXCursor_PreprocessingDirective)
3089 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003090
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003091 if (C.kind == CXCursor_MacroInstantiation)
3092 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003093
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003094 if (C.kind == CXCursor_MacroDefinition)
3095 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003096
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003097 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
3098 return getCursorDecl(C)->getSourceRange();
3099
3100 return SourceRange();
3101}
3102
3103extern "C" {
3104
3105CXSourceRange clang_getCursorExtent(CXCursor C) {
3106 SourceRange R = getRawCursorExtent(C);
3107 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003108 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003109
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003110 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003111}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003112
3113CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003114 if (clang_isInvalid(C.kind))
3115 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003116
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003117 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003118 if (clang_isDeclaration(C.kind)) {
3119 Decl *D = getCursorDecl(C);
3120 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3121 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3122 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3123 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3124 if (ObjCForwardProtocolDecl *Protocols
3125 = dyn_cast<ObjCForwardProtocolDecl>(D))
3126 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3127
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003128 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003129 }
3130
Douglas Gregor97b98722010-01-19 23:20:36 +00003131 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003132 Expr *E = getCursorExpr(C);
3133 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003134 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003135 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003136
3137 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3138 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3139
Douglas Gregor97b98722010-01-19 23:20:36 +00003140 return clang_getNullCursor();
3141 }
3142
Douglas Gregor36897b02010-09-10 00:22:18 +00003143 if (clang_isStatement(C.kind)) {
3144 Stmt *S = getCursorStmt(C);
3145 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3146 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3147 getCursorASTUnit(C));
3148
3149 return clang_getNullCursor();
3150 }
3151
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003152 if (C.kind == CXCursor_MacroInstantiation) {
3153 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3154 return MakeMacroDefinitionCursor(Def, CXXUnit);
3155 }
3156
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003157 if (!clang_isReference(C.kind))
3158 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003159
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003160 switch (C.kind) {
3161 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003162 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003163
3164 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003165 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003166
3167 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003168 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003169
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003170 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003171 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003172
3173 case CXCursor_TemplateRef:
3174 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3175
Douglas Gregor69319002010-08-31 23:48:11 +00003176 case CXCursor_NamespaceRef:
3177 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3178
Douglas Gregora67e03f2010-09-09 21:42:20 +00003179 case CXCursor_MemberRef:
3180 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3181
Ted Kremenek3064ef92010-08-27 21:34:58 +00003182 case CXCursor_CXXBaseSpecifier: {
3183 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3184 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3185 CXXUnit));
3186 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003187
Douglas Gregor36897b02010-09-10 00:22:18 +00003188 case CXCursor_LabelRef:
3189 // FIXME: We end up faking the "parent" declaration here because we
3190 // don't want to make CXCursor larger.
3191 return MakeCXCursor(getCursorLabelRef(C).first,
3192 CXXUnit->getASTContext().getTranslationUnitDecl(),
3193 CXXUnit);
3194
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003195 case CXCursor_OverloadedDeclRef:
3196 return C;
3197
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003198 default:
3199 // We would prefer to enumerate all non-reference cursor kinds here.
3200 llvm_unreachable("Unhandled reference cursor kind");
3201 break;
3202 }
3203 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003204
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003205 return clang_getNullCursor();
3206}
3207
Douglas Gregorb6998662010-01-19 19:34:47 +00003208CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003209 if (clang_isInvalid(C.kind))
3210 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003211
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003212 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003213
Douglas Gregorb6998662010-01-19 19:34:47 +00003214 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003215 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003216 C = clang_getCursorReferenced(C);
3217 WasReference = true;
3218 }
3219
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003220 if (C.kind == CXCursor_MacroInstantiation)
3221 return clang_getCursorReferenced(C);
3222
Douglas Gregorb6998662010-01-19 19:34:47 +00003223 if (!clang_isDeclaration(C.kind))
3224 return clang_getNullCursor();
3225
3226 Decl *D = getCursorDecl(C);
3227 if (!D)
3228 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003229
Douglas Gregorb6998662010-01-19 19:34:47 +00003230 switch (D->getKind()) {
3231 // Declaration kinds that don't really separate the notions of
3232 // declaration and definition.
3233 case Decl::Namespace:
3234 case Decl::Typedef:
3235 case Decl::TemplateTypeParm:
3236 case Decl::EnumConstant:
3237 case Decl::Field:
3238 case Decl::ObjCIvar:
3239 case Decl::ObjCAtDefsField:
3240 case Decl::ImplicitParam:
3241 case Decl::ParmVar:
3242 case Decl::NonTypeTemplateParm:
3243 case Decl::TemplateTemplateParm:
3244 case Decl::ObjCCategoryImpl:
3245 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003246 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003247 case Decl::LinkageSpec:
3248 case Decl::ObjCPropertyImpl:
3249 case Decl::FileScopeAsm:
3250 case Decl::StaticAssert:
3251 case Decl::Block:
3252 return C;
3253
3254 // Declaration kinds that don't make any sense here, but are
3255 // nonetheless harmless.
3256 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003257 break;
3258
3259 // Declaration kinds for which the definition is not resolvable.
3260 case Decl::UnresolvedUsingTypename:
3261 case Decl::UnresolvedUsingValue:
3262 break;
3263
3264 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003265 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3266 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003267
3268 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003269 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003270
3271 case Decl::Enum:
3272 case Decl::Record:
3273 case Decl::CXXRecord:
3274 case Decl::ClassTemplateSpecialization:
3275 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003276 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003277 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003278 return clang_getNullCursor();
3279
3280 case Decl::Function:
3281 case Decl::CXXMethod:
3282 case Decl::CXXConstructor:
3283 case Decl::CXXDestructor:
3284 case Decl::CXXConversion: {
3285 const FunctionDecl *Def = 0;
3286 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003287 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003288 return clang_getNullCursor();
3289 }
3290
3291 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003292 // Ask the variable if it has a definition.
3293 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3294 return MakeCXCursor(Def, CXXUnit);
3295 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003296 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003297
Douglas Gregorb6998662010-01-19 19:34:47 +00003298 case Decl::FunctionTemplate: {
3299 const FunctionDecl *Def = 0;
3300 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003301 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003302 return clang_getNullCursor();
3303 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003304
Douglas Gregorb6998662010-01-19 19:34:47 +00003305 case Decl::ClassTemplate: {
3306 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003307 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003308 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003309 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003310 return clang_getNullCursor();
3311 }
3312
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003313 case Decl::Using:
3314 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3315 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003316
3317 case Decl::UsingShadow:
3318 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003319 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003320 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003321
3322 case Decl::ObjCMethod: {
3323 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3324 if (Method->isThisDeclarationADefinition())
3325 return C;
3326
3327 // Dig out the method definition in the associated
3328 // @implementation, if we have it.
3329 // FIXME: The ASTs should make finding the definition easier.
3330 if (ObjCInterfaceDecl *Class
3331 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3332 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3333 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3334 Method->isInstanceMethod()))
3335 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003336 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003337
3338 return clang_getNullCursor();
3339 }
3340
3341 case Decl::ObjCCategory:
3342 if (ObjCCategoryImplDecl *Impl
3343 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003344 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003345 return clang_getNullCursor();
3346
3347 case Decl::ObjCProtocol:
3348 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3349 return C;
3350 return clang_getNullCursor();
3351
3352 case Decl::ObjCInterface:
3353 // There are two notions of a "definition" for an Objective-C
3354 // class: the interface and its implementation. When we resolved a
3355 // reference to an Objective-C class, produce the @interface as
3356 // the definition; when we were provided with the interface,
3357 // produce the @implementation as the definition.
3358 if (WasReference) {
3359 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3360 return C;
3361 } else if (ObjCImplementationDecl *Impl
3362 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003363 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003364 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003365
Douglas Gregorb6998662010-01-19 19:34:47 +00003366 case Decl::ObjCProperty:
3367 // FIXME: We don't really know where to find the
3368 // ObjCPropertyImplDecls that implement this property.
3369 return clang_getNullCursor();
3370
3371 case Decl::ObjCCompatibleAlias:
3372 if (ObjCInterfaceDecl *Class
3373 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3374 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003375 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003376
Douglas Gregorb6998662010-01-19 19:34:47 +00003377 return clang_getNullCursor();
3378
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003379 case Decl::ObjCForwardProtocol:
3380 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3381 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003382
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003383 case Decl::ObjCClass:
3384 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3385 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003386
3387 case Decl::Friend:
3388 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003389 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003390 return clang_getNullCursor();
3391
3392 case Decl::FriendTemplate:
3393 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003394 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003395 return clang_getNullCursor();
3396 }
3397
3398 return clang_getNullCursor();
3399}
3400
3401unsigned clang_isCursorDefinition(CXCursor C) {
3402 if (!clang_isDeclaration(C.kind))
3403 return 0;
3404
3405 return clang_getCursorDefinition(C) == C;
3406}
3407
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003408unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003409 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003410 return 0;
3411
3412 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3413 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3414 return E->getNumDecls();
3415
3416 if (OverloadedTemplateStorage *S
3417 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3418 return S->size();
3419
3420 Decl *D = Storage.get<Decl*>();
3421 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3422 return Using->getNumShadowDecls();
3423 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3424 return Classes->size();
3425 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3426 return Protocols->protocol_size();
3427
3428 return 0;
3429}
3430
3431CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003432 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003433 return clang_getNullCursor();
3434
3435 if (index >= clang_getNumOverloadedDecls(cursor))
3436 return clang_getNullCursor();
3437
3438 ASTUnit *Unit = getCursorASTUnit(cursor);
3439 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3440 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3441 return MakeCXCursor(E->decls_begin()[index], Unit);
3442
3443 if (OverloadedTemplateStorage *S
3444 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3445 return MakeCXCursor(S->begin()[index], Unit);
3446
3447 Decl *D = Storage.get<Decl*>();
3448 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3449 // FIXME: This is, unfortunately, linear time.
3450 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3451 std::advance(Pos, index);
3452 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3453 }
3454
3455 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3456 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3457
3458 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3459 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3460
3461 return clang_getNullCursor();
3462}
3463
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003464void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003465 const char **startBuf,
3466 const char **endBuf,
3467 unsigned *startLine,
3468 unsigned *startColumn,
3469 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003470 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003471 assert(getCursorDecl(C) && "CXCursor has null decl");
3472 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003473 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3474 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003475
Steve Naroff4ade6d62009-09-23 17:52:52 +00003476 SourceManager &SM = FD->getASTContext().getSourceManager();
3477 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3478 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3479 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3480 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3481 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3482 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3483}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003484
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003485void clang_enableStackTraces(void) {
3486 llvm::sys::PrintStackTraceOnErrorSignal();
3487}
3488
Ted Kremenekfb480492010-01-13 21:46:36 +00003489} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003490
Ted Kremenekfb480492010-01-13 21:46:36 +00003491//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003492// Token-based Operations.
3493//===----------------------------------------------------------------------===//
3494
3495/* CXToken layout:
3496 * int_data[0]: a CXTokenKind
3497 * int_data[1]: starting token location
3498 * int_data[2]: token length
3499 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003500 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003501 * otherwise unused.
3502 */
3503extern "C" {
3504
3505CXTokenKind clang_getTokenKind(CXToken CXTok) {
3506 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3507}
3508
3509CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3510 switch (clang_getTokenKind(CXTok)) {
3511 case CXToken_Identifier:
3512 case CXToken_Keyword:
3513 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003514 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3515 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003516
3517 case CXToken_Literal: {
3518 // We have stashed the starting pointer in the ptr_data field. Use it.
3519 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003520 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003521 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003522
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003523 case CXToken_Punctuation:
3524 case CXToken_Comment:
3525 break;
3526 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003527
3528 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003529 // deconstructing the source location.
3530 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3531 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003532 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003533
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003534 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3535 std::pair<FileID, unsigned> LocInfo
3536 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003537 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003538 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003539 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3540 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003541 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003542
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003543 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003544}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003545
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003546CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3547 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3548 if (!CXXUnit)
3549 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003550
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003551 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3552 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3553}
3554
3555CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3556 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003557 if (!CXXUnit)
3558 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003559
3560 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003561 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3562}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003563
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003564void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3565 CXToken **Tokens, unsigned *NumTokens) {
3566 if (Tokens)
3567 *Tokens = 0;
3568 if (NumTokens)
3569 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003570
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003571 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3572 if (!CXXUnit || !Tokens || !NumTokens)
3573 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003574
Douglas Gregorbdf60622010-03-05 21:16:25 +00003575 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3576
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003577 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003578 if (R.isInvalid())
3579 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003580
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003581 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3582 std::pair<FileID, unsigned> BeginLocInfo
3583 = SourceMgr.getDecomposedLoc(R.getBegin());
3584 std::pair<FileID, unsigned> EndLocInfo
3585 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003586
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003587 // Cannot tokenize across files.
3588 if (BeginLocInfo.first != EndLocInfo.first)
3589 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003590
3591 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003592 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003593 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003594 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003595 if (Invalid)
3596 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003597
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003598 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3599 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003600 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003601 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003602
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003603 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003604 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003605 llvm::SmallVector<CXToken, 32> CXTokens;
3606 Token Tok;
3607 do {
3608 // Lex the next token
3609 Lex.LexFromRawLexer(Tok);
3610 if (Tok.is(tok::eof))
3611 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003612
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003613 // Initialize the CXToken.
3614 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003615
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003616 // - Common fields
3617 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3618 CXTok.int_data[2] = Tok.getLength();
3619 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003620
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003621 // - Kind-specific fields
3622 if (Tok.isLiteral()) {
3623 CXTok.int_data[0] = CXToken_Literal;
3624 CXTok.ptr_data = (void *)Tok.getLiteralData();
3625 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003626 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003627 std::pair<FileID, unsigned> LocInfo
3628 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003629 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003630 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003631 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3632 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003633 return;
3634
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003635 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003636 IdentifierInfo *II
3637 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003638
3639 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3640 CXTok.int_data[0] = CXToken_Keyword;
3641 }
3642 else {
3643 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3644 CXToken_Identifier
3645 : CXToken_Keyword;
3646 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003647 CXTok.ptr_data = II;
3648 } else if (Tok.is(tok::comment)) {
3649 CXTok.int_data[0] = CXToken_Comment;
3650 CXTok.ptr_data = 0;
3651 } else {
3652 CXTok.int_data[0] = CXToken_Punctuation;
3653 CXTok.ptr_data = 0;
3654 }
3655 CXTokens.push_back(CXTok);
3656 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003657
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003658 if (CXTokens.empty())
3659 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003660
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003661 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3662 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3663 *NumTokens = CXTokens.size();
3664}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003665
Ted Kremenek6db61092010-05-05 00:55:15 +00003666void clang_disposeTokens(CXTranslationUnit TU,
3667 CXToken *Tokens, unsigned NumTokens) {
3668 free(Tokens);
3669}
3670
3671} // end: extern "C"
3672
3673//===----------------------------------------------------------------------===//
3674// Token annotation APIs.
3675//===----------------------------------------------------------------------===//
3676
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003677typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003678static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3679 CXCursor parent,
3680 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003681namespace {
3682class AnnotateTokensWorker {
3683 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003684 CXToken *Tokens;
3685 CXCursor *Cursors;
3686 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003687 unsigned TokIdx;
3688 CursorVisitor AnnotateVis;
3689 SourceManager &SrcMgr;
3690
3691 bool MoreTokens() const { return TokIdx < NumTokens; }
3692 unsigned NextToken() const { return TokIdx; }
3693 void AdvanceToken() { ++TokIdx; }
3694 SourceLocation GetTokenLoc(unsigned tokI) {
3695 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3696 }
3697
Ted Kremenek6db61092010-05-05 00:55:15 +00003698public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003699 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003700 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3701 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003702 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003703 NumTokens(numTokens), TokIdx(0),
3704 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3705 Decl::MaxPCHLevel, RegionOfInterest),
3706 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003707
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003708 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003709 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003710 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003711};
3712}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003713
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003714void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3715 // Walk the AST within the region of interest, annotating tokens
3716 // along the way.
3717 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003718
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003719 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3720 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3721 if (Pos != Annotated.end())
3722 Cursors[I] = Pos->second;
3723 }
3724
3725 // Finish up annotating any tokens left.
3726 if (!MoreTokens())
3727 return;
3728
3729 const CXCursor &C = clang_getNullCursor();
3730 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3731 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3732 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003733 }
3734}
3735
Ted Kremenek6db61092010-05-05 00:55:15 +00003736enum CXChildVisitResult
3737AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003738 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3739 // We can always annotate a preprocessing directive/macro instantiation.
3740 if (clang_isPreprocessing(cursor.kind)) {
3741 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003742 return CXChildVisit_Recurse;
3743 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003744
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003745 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003746
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003747 if (cursorRange.isInvalid())
3748 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003749
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003750 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3751
Ted Kremeneka333c662010-05-12 05:29:33 +00003752 // Adjust the annotated range based specific declarations.
3753 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3754 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003755 Decl *D = cxcursor::getCursorDecl(cursor);
3756 // Don't visit synthesized ObjC methods, since they have no syntatic
3757 // representation in the source.
3758 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3759 if (MD->isSynthesized())
3760 return CXChildVisit_Continue;
3761 }
3762 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003763 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3764 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003765 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003766 if (TLoc.isValid() &&
3767 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003768 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003769 }
3770 }
3771 }
3772
Ted Kremenek3f404602010-08-14 01:14:06 +00003773 // If the location of the cursor occurs within a macro instantiation, record
3774 // the spelling location of the cursor in our annotation map. We can then
3775 // paper over the token labelings during a post-processing step to try and
3776 // get cursor mappings for tokens that are the *arguments* of a macro
3777 // instantiation.
3778 if (L.isMacroID()) {
3779 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3780 // Only invalidate the old annotation if it isn't part of a preprocessing
3781 // directive. Here we assume that the default construction of CXCursor
3782 // results in CXCursor.kind being an initialized value (i.e., 0). If
3783 // this isn't the case, we can fix by doing lookup + insertion.
3784
3785 CXCursor &oldC = Annotated[rawEncoding];
3786 if (!clang_isPreprocessing(oldC.kind))
3787 oldC = cursor;
3788 }
3789
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003790 const enum CXCursorKind K = clang_getCursorKind(parent);
3791 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003792 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3793 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003794
3795 while (MoreTokens()) {
3796 const unsigned I = NextToken();
3797 SourceLocation TokLoc = GetTokenLoc(I);
3798 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3799 case RangeBefore:
3800 Cursors[I] = updateC;
3801 AdvanceToken();
3802 continue;
3803 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003804 case RangeOverlap:
3805 break;
3806 }
3807 break;
3808 }
3809
3810 // Visit children to get their cursor information.
3811 const unsigned BeforeChildren = NextToken();
3812 VisitChildren(cursor);
3813 const unsigned AfterChildren = NextToken();
3814
3815 // Adjust 'Last' to the last token within the extent of the cursor.
3816 while (MoreTokens()) {
3817 const unsigned I = NextToken();
3818 SourceLocation TokLoc = GetTokenLoc(I);
3819 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3820 case RangeBefore:
3821 assert(0 && "Infeasible");
3822 case RangeAfter:
3823 break;
3824 case RangeOverlap:
3825 Cursors[I] = updateC;
3826 AdvanceToken();
3827 continue;
3828 }
3829 break;
3830 }
3831 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003832
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003833 // Scan the tokens that are at the beginning of the cursor, but are not
3834 // capture by the child cursors.
3835
3836 // For AST elements within macros, rely on a post-annotate pass to
3837 // to correctly annotate the tokens with cursors. Otherwise we can
3838 // get confusing results of having tokens that map to cursors that really
3839 // are expanded by an instantiation.
3840 if (L.isMacroID())
3841 cursor = clang_getNullCursor();
3842
3843 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3844 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3845 break;
3846 Cursors[I] = cursor;
3847 }
3848 // Scan the tokens that are at the end of the cursor, but are not captured
3849 // but the child cursors.
3850 for (unsigned I = AfterChildren; I != Last; ++I)
3851 Cursors[I] = cursor;
3852
3853 TokIdx = Last;
3854 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003855}
3856
Ted Kremenek6db61092010-05-05 00:55:15 +00003857static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3858 CXCursor parent,
3859 CXClientData client_data) {
3860 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3861}
3862
3863extern "C" {
3864
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003865void clang_annotateTokens(CXTranslationUnit TU,
3866 CXToken *Tokens, unsigned NumTokens,
3867 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003868
3869 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003870 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003871
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003872 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003873 if (!CXXUnit) {
3874 // Any token we don't specifically annotate will have a NULL cursor.
3875 const CXCursor &C = clang_getNullCursor();
3876 for (unsigned I = 0; I != NumTokens; ++I)
3877 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003878 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003879 }
3880
Douglas Gregorbdf60622010-03-05 21:16:25 +00003881 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003882
Douglas Gregor0396f462010-03-19 05:22:59 +00003883 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003884 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003885 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3886 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003887 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3888 clang_getTokenLocation(TU,
3889 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003890
Douglas Gregor0396f462010-03-19 05:22:59 +00003891 // A mapping from the source locations found when re-lexing or traversing the
3892 // region of interest to the corresponding cursors.
3893 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003894
3895 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003896 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003897 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3898 std::pair<FileID, unsigned> BeginLocInfo
3899 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3900 std::pair<FileID, unsigned> EndLocInfo
3901 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003902
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003903 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003904 bool Invalid = false;
3905 if (BeginLocInfo.first == EndLocInfo.first &&
3906 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3907 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003908 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3909 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003910 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003911 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003912 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003913
3914 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003915 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003916 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003917 Token Tok;
3918 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003919
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003920 reprocess:
3921 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3922 // We have found a preprocessing directive. Gobble it up so that we
3923 // don't see it while preprocessing these tokens later, but keep track of
3924 // all of the token locations inside this preprocessing directive so that
3925 // we can annotate them appropriately.
3926 //
3927 // FIXME: Some simple tests here could identify macro definitions and
3928 // #undefs, to provide specific cursor kinds for those.
3929 std::vector<SourceLocation> Locations;
3930 do {
3931 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003932 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003933 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003934
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003935 using namespace cxcursor;
3936 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003937 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3938 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003939 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003940 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3941 Annotated[Locations[I].getRawEncoding()] = Cursor;
3942 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003943
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003944 if (Tok.isAtStartOfLine())
3945 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003946
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003947 continue;
3948 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003949
Douglas Gregor48072312010-03-18 15:23:44 +00003950 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003951 break;
3952 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003953 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003954
Douglas Gregor0396f462010-03-19 05:22:59 +00003955 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003956 // a specific cursor.
3957 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3958 CXXUnit, RegionOfInterest);
3959 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003960}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003961} // end: extern "C"
3962
3963//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003964// Operations for querying linkage of a cursor.
3965//===----------------------------------------------------------------------===//
3966
3967extern "C" {
3968CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003969 if (!clang_isDeclaration(cursor.kind))
3970 return CXLinkage_Invalid;
3971
Ted Kremenek16b42592010-03-03 06:36:57 +00003972 Decl *D = cxcursor::getCursorDecl(cursor);
3973 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3974 switch (ND->getLinkage()) {
3975 case NoLinkage: return CXLinkage_NoLinkage;
3976 case InternalLinkage: return CXLinkage_Internal;
3977 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3978 case ExternalLinkage: return CXLinkage_External;
3979 };
3980
3981 return CXLinkage_Invalid;
3982}
3983} // end: extern "C"
3984
3985//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003986// Operations for querying language of a cursor.
3987//===----------------------------------------------------------------------===//
3988
3989static CXLanguageKind getDeclLanguage(const Decl *D) {
3990 switch (D->getKind()) {
3991 default:
3992 break;
3993 case Decl::ImplicitParam:
3994 case Decl::ObjCAtDefsField:
3995 case Decl::ObjCCategory:
3996 case Decl::ObjCCategoryImpl:
3997 case Decl::ObjCClass:
3998 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003999 case Decl::ObjCForwardProtocol:
4000 case Decl::ObjCImplementation:
4001 case Decl::ObjCInterface:
4002 case Decl::ObjCIvar:
4003 case Decl::ObjCMethod:
4004 case Decl::ObjCProperty:
4005 case Decl::ObjCPropertyImpl:
4006 case Decl::ObjCProtocol:
4007 return CXLanguage_ObjC;
4008 case Decl::CXXConstructor:
4009 case Decl::CXXConversion:
4010 case Decl::CXXDestructor:
4011 case Decl::CXXMethod:
4012 case Decl::CXXRecord:
4013 case Decl::ClassTemplate:
4014 case Decl::ClassTemplatePartialSpecialization:
4015 case Decl::ClassTemplateSpecialization:
4016 case Decl::Friend:
4017 case Decl::FriendTemplate:
4018 case Decl::FunctionTemplate:
4019 case Decl::LinkageSpec:
4020 case Decl::Namespace:
4021 case Decl::NamespaceAlias:
4022 case Decl::NonTypeTemplateParm:
4023 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004024 case Decl::TemplateTemplateParm:
4025 case Decl::TemplateTypeParm:
4026 case Decl::UnresolvedUsingTypename:
4027 case Decl::UnresolvedUsingValue:
4028 case Decl::Using:
4029 case Decl::UsingDirective:
4030 case Decl::UsingShadow:
4031 return CXLanguage_CPlusPlus;
4032 }
4033
4034 return CXLanguage_C;
4035}
4036
4037extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004038
4039enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4040 if (clang_isDeclaration(cursor.kind))
4041 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4042 if (D->hasAttr<UnavailableAttr>() ||
4043 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4044 return CXAvailability_Available;
4045
4046 if (D->hasAttr<DeprecatedAttr>())
4047 return CXAvailability_Deprecated;
4048 }
4049
4050 return CXAvailability_Available;
4051}
4052
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004053CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4054 if (clang_isDeclaration(cursor.kind))
4055 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4056
4057 return CXLanguage_Invalid;
4058}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004059
4060CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4061 if (clang_isDeclaration(cursor.kind)) {
4062 if (Decl *D = getCursorDecl(cursor)) {
4063 DeclContext *DC = D->getDeclContext();
4064 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4065 }
4066 }
4067
4068 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4069 if (Decl *D = getCursorDecl(cursor))
4070 return MakeCXCursor(D, getCursorASTUnit(cursor));
4071 }
4072
4073 return clang_getNullCursor();
4074}
4075
4076CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4077 if (clang_isDeclaration(cursor.kind)) {
4078 if (Decl *D = getCursorDecl(cursor)) {
4079 DeclContext *DC = D->getLexicalDeclContext();
4080 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4081 }
4082 }
4083
4084 // FIXME: Note that we can't easily compute the lexical context of a
4085 // statement or expression, so we return nothing.
4086 return clang_getNullCursor();
4087}
4088
Douglas Gregor9f592342010-10-01 20:25:15 +00004089static void CollectOverriddenMethods(DeclContext *Ctx,
4090 ObjCMethodDecl *Method,
4091 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4092 if (!Ctx)
4093 return;
4094
4095 // If we have a class or category implementation, jump straight to the
4096 // interface.
4097 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4098 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4099
4100 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4101 if (!Container)
4102 return;
4103
4104 // Check whether we have a matching method at this level.
4105 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4106 Method->isInstanceMethod()))
4107 if (Method != Overridden) {
4108 // We found an override at this level; there is no need to look
4109 // into other protocols or categories.
4110 Methods.push_back(Overridden);
4111 return;
4112 }
4113
4114 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4115 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4116 PEnd = Protocol->protocol_end();
4117 P != PEnd; ++P)
4118 CollectOverriddenMethods(*P, Method, Methods);
4119 }
4120
4121 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4122 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4123 PEnd = Category->protocol_end();
4124 P != PEnd; ++P)
4125 CollectOverriddenMethods(*P, Method, Methods);
4126 }
4127
4128 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4129 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4130 PEnd = Interface->protocol_end();
4131 P != PEnd; ++P)
4132 CollectOverriddenMethods(*P, Method, Methods);
4133
4134 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4135 Category; Category = Category->getNextClassCategory())
4136 CollectOverriddenMethods(Category, Method, Methods);
4137
4138 // We only look into the superclass if we haven't found anything yet.
4139 if (Methods.empty())
4140 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4141 return CollectOverriddenMethods(Super, Method, Methods);
4142 }
4143}
4144
4145void clang_getOverriddenCursors(CXCursor cursor,
4146 CXCursor **overridden,
4147 unsigned *num_overridden) {
4148 if (overridden)
4149 *overridden = 0;
4150 if (num_overridden)
4151 *num_overridden = 0;
4152 if (!overridden || !num_overridden)
4153 return;
4154
4155 if (!clang_isDeclaration(cursor.kind))
4156 return;
4157
4158 Decl *D = getCursorDecl(cursor);
4159 if (!D)
4160 return;
4161
4162 // Handle C++ member functions.
4163 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4164 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4165 *num_overridden = CXXMethod->size_overridden_methods();
4166 if (!*num_overridden)
4167 return;
4168
4169 *overridden = new CXCursor [*num_overridden];
4170 unsigned I = 0;
4171 for (CXXMethodDecl::method_iterator
4172 M = CXXMethod->begin_overridden_methods(),
4173 MEnd = CXXMethod->end_overridden_methods();
4174 M != MEnd; (void)++M, ++I)
4175 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4176 return;
4177 }
4178
4179 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4180 if (!Method)
4181 return;
4182
4183 // Handle Objective-C methods.
4184 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4185 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4186
4187 if (Methods.empty())
4188 return;
4189
4190 *num_overridden = Methods.size();
4191 *overridden = new CXCursor [Methods.size()];
4192 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4193 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4194}
4195
4196void clang_disposeOverriddenCursors(CXCursor *overridden) {
4197 delete [] overridden;
4198}
4199
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004200} // end: extern "C"
4201
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004202
4203//===----------------------------------------------------------------------===//
4204// C++ AST instrospection.
4205//===----------------------------------------------------------------------===//
4206
4207extern "C" {
4208unsigned clang_CXXMethod_isStatic(CXCursor C) {
4209 if (!clang_isDeclaration(C.kind))
4210 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004211
4212 CXXMethodDecl *Method = 0;
4213 Decl *D = cxcursor::getCursorDecl(C);
4214 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4215 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4216 else
4217 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4218 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004219}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004220
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004221} // end: extern "C"
4222
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004223//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004224// Attribute introspection.
4225//===----------------------------------------------------------------------===//
4226
4227extern "C" {
4228CXType clang_getIBOutletCollectionType(CXCursor C) {
4229 if (C.kind != CXCursor_IBOutletCollectionAttr)
4230 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4231
4232 IBOutletCollectionAttr *A =
4233 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4234
4235 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4236}
4237} // end: extern "C"
4238
4239//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004240// CXString Operations.
4241//===----------------------------------------------------------------------===//
4242
4243extern "C" {
4244const char *clang_getCString(CXString string) {
4245 return string.Spelling;
4246}
4247
4248void clang_disposeString(CXString string) {
4249 if (string.MustFreeString && string.Spelling)
4250 free((void*)string.Spelling);
4251}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004252
Ted Kremenekfb480492010-01-13 21:46:36 +00004253} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004254
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004255namespace clang { namespace cxstring {
4256CXString createCXString(const char *String, bool DupString){
4257 CXString Str;
4258 if (DupString) {
4259 Str.Spelling = strdup(String);
4260 Str.MustFreeString = 1;
4261 } else {
4262 Str.Spelling = String;
4263 Str.MustFreeString = 0;
4264 }
4265 return Str;
4266}
4267
4268CXString createCXString(llvm::StringRef String, bool DupString) {
4269 CXString Result;
4270 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4271 char *Spelling = (char *)malloc(String.size() + 1);
4272 memmove(Spelling, String.data(), String.size());
4273 Spelling[String.size()] = 0;
4274 Result.Spelling = Spelling;
4275 Result.MustFreeString = 1;
4276 } else {
4277 Result.Spelling = String.data();
4278 Result.MustFreeString = 0;
4279 }
4280 return Result;
4281}
4282}}
4283
Ted Kremenek04bb7162010-01-22 22:44:15 +00004284//===----------------------------------------------------------------------===//
4285// Misc. utility functions.
4286//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004287
Ted Kremenek04bb7162010-01-22 22:44:15 +00004288extern "C" {
4289
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004290CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004291 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004292}
4293
4294} // end: extern "C"