blob: d2d00571c1d8f824ffbb9fbf5cc747a45249704a [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"
Benjamin Kramer0829a832009-10-18 11:19:36 +000037#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000038#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000039
Benjamin Kramerc2a98162010-03-13 21:22:49 +000040// Needed to define L_TMPNAM on some systems.
41#include <cstdio>
42
Steve Naroff50398192009-08-28 15:28:48 +000043using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000044using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000045using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000046
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000047//===----------------------------------------------------------------------===//
48// Crash Reporting.
49//===----------------------------------------------------------------------===//
50
Ted Kremenekd7ffd082010-05-22 00:06:46 +000051#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000052#include "clang/Analysis/Support/SaveAndRestore.h"
53// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000054static const char *__crashreporter_info__ = 0;
55asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000056#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000057static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000058static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000059static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
60static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
61
62static unsigned SetCrashTracerInfo(const char *str,
63 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000064
Ted Kremenek254ba7c2010-01-07 23:13:53 +000065 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000066 while (crashtracer_strings[slot]) {
67 if (++slot == NUM_CRASH_STRINGS)
68 slot = 0;
69 }
70 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000071 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000072
73 // We need to create an aggregate string because multiple threads
74 // may be in this method at one time. The crash reporter string
75 // will attempt to overapproximate the set of in-flight invocations
76 // of this function. Race conditions can still cause this goal
77 // to not be achieved.
78 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000079 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000080 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
81 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
82 }
83 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
84 return slot;
85}
86
87static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000088 unsigned max_slot = 0;
89 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000090
Ted Kremenek254ba7c2010-01-07 23:13:53 +000091 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
92
93 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
94 if (agg_crashtracer_strings[i] &&
95 crashtracer_counter_id[i] > max_value) {
96 max_slot = i;
97 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000098 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000099
100 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +0000101}
102
103namespace {
104class ArgsCrashTracerInfo {
105 llvm::SmallString<1024> CrashString;
106 llvm::SmallString<1024> AggregateString;
107 unsigned crashtracerSlot;
108public:
109 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
110 : crashtracerSlot(0)
111 {
112 {
113 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000114 Out << "ClangCIndex [" << getClangFullVersion() << "]"
115 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000116 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
117 E=Args.end(); I!=E; ++I)
118 Out << ' ' << *I;
119 }
120 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
121 AggregateString);
122 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000123
Ted Kremenek29b72842010-01-07 22:49:05 +0000124 ~ArgsCrashTracerInfo() {
125 ResetCrashTracerInfo(crashtracerSlot);
126 }
127};
128}
129#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131/// \brief The result of comparing two source ranges.
132enum RangeComparisonResult {
133 /// \brief Either the ranges overlap or one of the ranges is invalid.
134 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000135
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136 /// \brief The first range ends before the second range starts.
137 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000138
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000139 /// \brief The first range starts after the second range ends.
140 RangeAfter
141};
142
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000143/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000144/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000145static RangeComparisonResult RangeCompare(SourceManager &SM,
146 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000147 SourceRange R2) {
148 assert(R1.isValid() && "First range is invalid?");
149 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000150 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000151 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000153 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000154 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000155 return RangeAfter;
156 return RangeOverlap;
157}
158
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000159/// \brief Determine if a source location falls within, before, or after a
160/// a given source range.
161static RangeComparisonResult LocationCompare(SourceManager &SM,
162 SourceLocation L, SourceRange R) {
163 assert(R.isValid() && "First range is invalid?");
164 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000165 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000166 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000167 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
168 return RangeBefore;
169 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
170 return RangeAfter;
171 return RangeOverlap;
172}
173
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000174/// \brief Translate a Clang source range into a CIndex source range.
175///
176/// Clang internally represents ranges where the end location points to the
177/// start of the token at the end. However, for external clients it is more
178/// useful to have a CXSourceRange be a proper half-open interval. This routine
179/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000181 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000182 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000183 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000184 // location accordingly.
185 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000186 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000187 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000188 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000189 EndLoc = EndLoc.getFileLocWithOffset(Length);
190 }
191
192 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
193 R.getBegin().getRawEncoding(),
194 EndLoc.getRawEncoding() };
195 return Result;
196}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000197
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000198//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000199// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000200//===----------------------------------------------------------------------===//
201
Steve Naroff89922f82009-08-31 00:59:03 +0000202namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000203
Douglas Gregorb1373d02010-01-20 20:59:29 +0000204// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000205class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000206 public TypeLocVisitor<CursorVisitor, bool>,
207 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000208{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000209 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000210 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000212 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000213 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215 /// \brief The declaration that serves at the parent of any statement or
216 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000217 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000218
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000219 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000221
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000222 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000223 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000224
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000225 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
226 // to the visitor. Declarations with a PCH level greater than this value will
227 // be suppressed.
228 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000229
230 /// \brief When valid, a source range to which the cursor should restrict
231 /// its search.
232 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000233
Douglas Gregorb1373d02010-01-20 20:59:29 +0000234 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000235 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000236 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000237
238 /// \brief Determine whether this particular source range comes before, comes
239 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000240 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000241 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
243
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000244 class SetParentRAII {
245 CXCursor &Parent;
246 Decl *&StmtParent;
247 CXCursor OldParent;
248
249 public:
250 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
251 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
252 {
253 Parent = NewParent;
254 if (clang_isDeclaration(Parent.kind))
255 StmtParent = getCursorDecl(Parent);
256 }
257
258 ~SetParentRAII() {
259 Parent = OldParent;
260 if (clang_isDeclaration(Parent.kind))
261 StmtParent = getCursorDecl(Parent);
262 }
263 };
264
Steve Naroff89922f82009-08-31 00:59:03 +0000265public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000266 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
267 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000268 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000269 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000270 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000271 {
272 Parent.kind = CXCursor_NoDeclFound;
273 Parent.data[0] = 0;
274 Parent.data[1] = 0;
275 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000276 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000277 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000278
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000279 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000280
281 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
282 getPreprocessedEntities();
283
Douglas Gregorb1373d02010-01-20 20:59:29 +0000284 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000285
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000286 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000287 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000288 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000289 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000290 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000291 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
292 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000293 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000294 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000295 bool VisitClassTemplatePartialSpecializationDecl(
296 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000297 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 bool VisitEnumConstantDecl(EnumConstantDecl *D);
299 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
300 bool VisitFunctionDecl(FunctionDecl *ND);
301 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000302 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000303 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000304 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000305 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000306 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000307 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
308 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
309 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
310 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000311 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000312 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
313 bool VisitObjCImplDecl(ObjCImplDecl *D);
314 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
315 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000316 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
317 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
318 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000319 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000320 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000321 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000322 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000323 bool VisitUsingDecl(UsingDecl *D);
324 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
325 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000326
Douglas Gregor01829d32010-08-31 14:41:23 +0000327 // Name visitor
328 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000329 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000330
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000331 // Template visitors
332 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000333 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000334 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
335
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000336 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000337 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000339 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000340 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
341 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000342 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000343 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000344 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000345 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
346 bool VisitPointerTypeLoc(PointerTypeLoc TL);
347 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
348 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
349 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
350 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000351 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000352 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000353 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000354 // FIXME: Implement visitors here when the unimplemented TypeLocs get
355 // implemented
356 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
357 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000358
Douglas Gregora59e3902010-01-21 23:27:09 +0000359 // Statement visitors
360 bool VisitStmt(Stmt *S);
361 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000362 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000363 bool VisitIfStmt(IfStmt *S);
364 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000365 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000366 bool VisitWhileStmt(WhileStmt *S);
367 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000368
Douglas Gregor336fd812010-01-23 00:40:08 +0000369 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000370 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000371 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000372 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000373 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000374 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000375 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000376 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000377 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000378 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000379 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000380 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000381 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
382 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000383 bool VisitInitListExpr(InitListExpr *E);
384 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000385 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000386 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000387 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000388 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
389 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000390 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000391 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000392 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000393 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000394 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000395 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000396 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000397 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000398};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000399
Ted Kremenekab188932010-01-05 19:32:54 +0000400} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000401
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000402static SourceRange getRawCursorExtent(CXCursor C);
403
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000404RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000405 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
406}
407
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408/// \brief Visit the given cursor and, if requested by the visitor,
409/// its children.
410///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000411/// \param Cursor the cursor to visit.
412///
413/// \param CheckRegionOfInterest if true, then the caller already checked that
414/// this cursor is within the region of interest.
415///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416/// \returns true if the visitation should be aborted, false if it
417/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000418bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000419 if (clang_isInvalid(Cursor.kind))
420 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000421
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422 if (clang_isDeclaration(Cursor.kind)) {
423 Decl *D = getCursorDecl(Cursor);
424 assert(D && "Invalid declaration cursor");
425 if (D->getPCHLevel() > MaxPCHLevel)
426 return false;
427
428 if (D->isImplicit())
429 return false;
430 }
431
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000432 // If we have a range of interest, and this cursor doesn't intersect with it,
433 // we're done.
434 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000435 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000436 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000437 return false;
438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440 switch (Visitor(Cursor, Parent, ClientData)) {
441 case CXChildVisit_Break:
442 return true;
443
444 case CXChildVisit_Continue:
445 return false;
446
447 case CXChildVisit_Recurse:
448 return VisitChildren(Cursor);
449 }
450
Douglas Gregorfd643772010-01-25 16:45:46 +0000451 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452}
453
Douglas Gregor788f5a12010-03-20 00:41:21 +0000454std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
455CursorVisitor::getPreprocessedEntities() {
456 PreprocessingRecord &PPRec
457 = *TU->getPreprocessor().getPreprocessingRecord();
458
459 bool OnlyLocalDecls
460 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
461
462 // There is no region of interest; we have to walk everything.
463 if (RegionOfInterest.isInvalid())
464 return std::make_pair(PPRec.begin(OnlyLocalDecls),
465 PPRec.end(OnlyLocalDecls));
466
467 // Find the file in which the region of interest lands.
468 SourceManager &SM = TU->getSourceManager();
469 std::pair<FileID, unsigned> Begin
470 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
471 std::pair<FileID, unsigned> End
472 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
473
474 // The region of interest spans files; we have to walk everything.
475 if (Begin.first != End.first)
476 return std::make_pair(PPRec.begin(OnlyLocalDecls),
477 PPRec.end(OnlyLocalDecls));
478
479 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
480 = TU->getPreprocessedEntitiesByFile();
481 if (ByFileMap.empty()) {
482 // Build the mapping from files to sets of preprocessed entities.
483 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
484 EEnd = PPRec.end(OnlyLocalDecls);
485 E != EEnd; ++E) {
486 std::pair<FileID, unsigned> P
487 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
488 ByFileMap[P.first].push_back(*E);
489 }
490 }
491
492 return std::make_pair(ByFileMap[Begin.first].begin(),
493 ByFileMap[Begin.first].end());
494}
495
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496/// \brief Visit the children of the given cursor.
497///
498/// \returns true if the visitation should be aborted, false if it
499/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000501 if (clang_isReference(Cursor.kind)) {
502 // By definition, references have no children.
503 return false;
504 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000505
506 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000507 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000508 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000509
Douglas Gregorb1373d02010-01-20 20:59:29 +0000510 if (clang_isDeclaration(Cursor.kind)) {
511 Decl *D = getCursorDecl(Cursor);
512 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000513 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000515
Douglas Gregora59e3902010-01-21 23:27:09 +0000516 if (clang_isStatement(Cursor.kind))
517 return Visit(getCursorStmt(Cursor));
518 if (clang_isExpression(Cursor.kind))
519 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000520
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000522 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000523 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
524 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000525 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
526 TLEnd = CXXUnit->top_level_end();
527 TL != TLEnd; ++TL) {
528 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000529 return true;
530 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000531 } else if (VisitDeclContext(
532 CXXUnit->getASTContext().getTranslationUnitDecl()))
533 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000534
Douglas Gregor0396f462010-03-19 05:22:59 +0000535 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000536 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000537 // FIXME: Once we have the ability to deserialize a preprocessing record,
538 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000539 PreprocessingRecord::iterator E, EEnd;
540 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000541 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
542 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
543 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000544
Douglas Gregor0396f462010-03-19 05:22:59 +0000545 continue;
546 }
547
548 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
549 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
550 return true;
551
552 continue;
553 }
554 }
555 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000556 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000558
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000560 return false;
561}
562
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000563bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000564 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
565 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000566
Ted Kremenek664cffd2010-07-22 11:30:19 +0000567 if (Stmt *Body = B->getBody())
568 return Visit(MakeCXCursor(Body, StmtParent, TU));
569
570 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000571}
572
Douglas Gregorb1373d02010-01-20 20:59:29 +0000573bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000574 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000575 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000576
Ted Kremenek23173d72010-05-18 21:09:07 +0000577 Decl *D = *I;
578 if (D->getLexicalDeclContext() != DC)
579 continue;
580
581 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000582
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000583 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000584 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000585 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000586 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000587
588 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000589 case RangeBefore:
590 // This declaration comes before the region of interest; skip it.
591 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000592
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000593 case RangeAfter:
594 // This declaration comes after the region of interest; we're done.
595 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000596
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000597 case RangeOverlap:
598 // This declaration overlaps the region of interest; visit it.
599 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000600 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000601 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000602
Daniel Dunbard52864b2010-02-14 10:02:57 +0000603 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000604 return true;
605 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000606
Douglas Gregorb1373d02010-01-20 20:59:29 +0000607 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000608}
609
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000610bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
611 llvm_unreachable("Translation units are visited directly by Visit()");
612 return false;
613}
614
615bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
616 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
617 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619 return false;
620}
621
622bool CursorVisitor::VisitTagDecl(TagDecl *D) {
623 return VisitDeclContext(D);
624}
625
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000626bool CursorVisitor::VisitClassTemplateSpecializationDecl(
627 ClassTemplateSpecializationDecl *D) {
628 bool ShouldVisitBody = false;
629 switch (D->getSpecializationKind()) {
630 case TSK_Undeclared:
631 case TSK_ImplicitInstantiation:
632 // Nothing to visit
633 return false;
634
635 case TSK_ExplicitInstantiationDeclaration:
636 case TSK_ExplicitInstantiationDefinition:
637 break;
638
639 case TSK_ExplicitSpecialization:
640 ShouldVisitBody = true;
641 break;
642 }
643
644 // Visit the template arguments used in the specialization.
645 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
646 TypeLoc TL = SpecType->getTypeLoc();
647 if (TemplateSpecializationTypeLoc *TSTLoc
648 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
649 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
650 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
651 return true;
652 }
653 }
654
655 if (ShouldVisitBody && VisitCXXRecordDecl(D))
656 return true;
657
658 return false;
659}
660
Douglas Gregor74dbe642010-08-31 19:31:58 +0000661bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
662 ClassTemplatePartialSpecializationDecl *D) {
663 // FIXME: Visit the "outer" template parameter lists on the TagDecl
664 // before visiting these template parameters.
665 if (VisitTemplateParameters(D->getTemplateParameters()))
666 return true;
667
668 // Visit the partial specialization arguments.
669 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
670 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
671 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
672 return true;
673
674 return VisitCXXRecordDecl(D);
675}
676
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000677bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000678 // Visit the default argument.
679 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
680 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
681 if (Visit(DefArg->getTypeLoc()))
682 return true;
683
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000684 return false;
685}
686
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000687bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
688 if (Expr *Init = D->getInitExpr())
689 return Visit(MakeCXCursor(Init, StmtParent, TU));
690 return false;
691}
692
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000693bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
694 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
695 if (Visit(TSInfo->getTypeLoc()))
696 return true;
697
698 return false;
699}
700
Douglas Gregora67e03f2010-09-09 21:42:20 +0000701/// \brief Compare two base or member initializers based on their source order.
702static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
703 CXXBaseOrMemberInitializer const * const *X
704 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
705 CXXBaseOrMemberInitializer const * const *Y
706 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
707
708 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
709 return -1;
710 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
711 return 1;
712 else
713 return 0;
714}
715
Douglas Gregorb1373d02010-01-20 20:59:29 +0000716bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000717 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
718 // Visit the function declaration's syntactic components in the order
719 // written. This requires a bit of work.
720 TypeLoc TL = TSInfo->getTypeLoc();
721 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
722
723 // If we have a function declared directly (without the use of a typedef),
724 // visit just the return type. Otherwise, just visit the function's type
725 // now.
726 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
727 (!FTL && Visit(TL)))
728 return true;
729
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000730 // Visit the nested-name-specifier, if present.
731 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
732 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
733 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000734
735 // Visit the declaration name.
736 if (VisitDeclarationNameInfo(ND->getNameInfo()))
737 return true;
738
739 // FIXME: Visit explicitly-specified template arguments!
740
741 // Visit the function parameters, if we have a function type.
742 if (FTL && VisitFunctionTypeLoc(*FTL, true))
743 return true;
744
745 // FIXME: Attributes?
746 }
747
Douglas Gregora67e03f2010-09-09 21:42:20 +0000748 if (ND->isThisDeclarationADefinition()) {
749 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
750 // Find the initializers that were written in the source.
751 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
752 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
753 IEnd = Constructor->init_end();
754 I != IEnd; ++I) {
755 if (!(*I)->isWritten())
756 continue;
757
758 WrittenInits.push_back(*I);
759 }
760
761 // Sort the initializers in source order
762 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
763 &CompareCXXBaseOrMemberInitializers);
764
765 // Visit the initializers in source order
766 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
767 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
768 if (Init->isMemberInitializer()) {
769 if (Visit(MakeCursorMemberRef(Init->getMember(),
770 Init->getMemberLocation(), TU)))
771 return true;
772 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
773 if (Visit(BaseInfo->getTypeLoc()))
774 return true;
775 }
776
777 // Visit the initializer value.
778 if (Expr *Initializer = Init->getInit())
779 if (Visit(MakeCXCursor(Initializer, ND, TU)))
780 return true;
781 }
782 }
783
784 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
785 return true;
786 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregorb1373d02010-01-20 20:59:29 +0000788 return false;
789}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000790
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000791bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
792 if (VisitDeclaratorDecl(D))
793 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 if (Expr *BitWidth = D->getBitWidth())
796 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798 return false;
799}
800
801bool CursorVisitor::VisitVarDecl(VarDecl *D) {
802 if (VisitDeclaratorDecl(D))
803 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 if (Expr *Init = D->getInit())
806 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000807
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000808 return false;
809}
810
Douglas Gregor84b51d72010-09-01 20:16:53 +0000811bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
812 if (VisitDeclaratorDecl(D))
813 return true;
814
815 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
816 if (Expr *DefArg = D->getDefaultArgument())
817 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
818
819 return false;
820}
821
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000822bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
823 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
824 // before visiting these template parameters.
825 if (VisitTemplateParameters(D->getTemplateParameters()))
826 return true;
827
828 return VisitFunctionDecl(D->getTemplatedDecl());
829}
830
Douglas Gregor39d6f072010-08-31 19:02:00 +0000831bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
832 // FIXME: Visit the "outer" template parameter lists on the TagDecl
833 // before visiting these template parameters.
834 if (VisitTemplateParameters(D->getTemplateParameters()))
835 return true;
836
837 return VisitCXXRecordDecl(D->getTemplatedDecl());
838}
839
Douglas Gregor84b51d72010-09-01 20:16:53 +0000840bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
841 if (VisitTemplateParameters(D->getTemplateParameters()))
842 return true;
843
844 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
845 VisitTemplateArgumentLoc(D->getDefaultArgument()))
846 return true;
847
848 return false;
849}
850
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000851bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000852 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
853 if (Visit(TSInfo->getTypeLoc()))
854 return true;
855
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 PEnd = ND->param_end();
858 P != PEnd; ++P) {
859 if (Visit(MakeCXCursor(*P, TU)))
860 return true;
861 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000862
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000863 if (ND->isThisDeclarationADefinition() &&
864 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
865 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000867 return false;
868}
869
Douglas Gregora59e3902010-01-21 23:27:09 +0000870bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
871 return VisitDeclContext(D);
872}
873
Douglas Gregorb1373d02010-01-20 20:59:29 +0000874bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000875 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
876 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000877 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000878
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000879 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
880 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
881 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000882 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000883 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000884
Douglas Gregora59e3902010-01-21 23:27:09 +0000885 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000886}
887
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000888bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
889 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
890 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
891 E = PID->protocol_end(); I != E; ++I, ++PL)
892 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
893 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000894
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000895 return VisitObjCContainerDecl(PID);
896}
897
Ted Kremenek23173d72010-05-18 21:09:07 +0000898bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000899 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000900 return true;
901
Ted Kremenek23173d72010-05-18 21:09:07 +0000902 // FIXME: This implements a workaround with @property declarations also being
903 // installed in the DeclContext for the @interface. Eventually this code
904 // should be removed.
905 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
906 if (!CDecl || !CDecl->IsClassExtension())
907 return false;
908
909 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
910 if (!ID)
911 return false;
912
913 IdentifierInfo *PropertyId = PD->getIdentifier();
914 ObjCPropertyDecl *prevDecl =
915 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
916
917 if (!prevDecl)
918 return false;
919
920 // Visit synthesized methods since they will be skipped when visiting
921 // the @interface.
922 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000923 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000924 if (Visit(MakeCXCursor(MD, TU)))
925 return true;
926
927 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000928 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000929 if (Visit(MakeCXCursor(MD, TU)))
930 return true;
931
932 return false;
933}
934
Douglas Gregorb1373d02010-01-20 20:59:29 +0000935bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000936 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000937 if (D->getSuperClass() &&
938 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000939 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000940 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000943 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
944 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
945 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000946 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregora59e3902010-01-21 23:27:09 +0000949 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000950}
951
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000952bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
953 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000954}
955
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000956bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000957 // 'ID' could be null when dealing with invalid code.
958 if (ObjCInterfaceDecl *ID = D->getClassInterface())
959 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
960 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000961
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000962 return VisitObjCImplDecl(D);
963}
964
965bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
966#if 0
967 // Issue callbacks for super class.
968 // FIXME: No source location information!
969 if (D->getSuperClass() &&
970 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000971 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000972 TU)))
973 return true;
974#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000975
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000976 return VisitObjCImplDecl(D);
977}
978
979bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
980 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
981 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
982 E = D->protocol_end();
983 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000984 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000985 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000986
987 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000988}
989
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000990bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
991 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
992 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
993 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000995 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000996}
997
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000998bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
999 return VisitDeclContext(D);
1000}
1001
Douglas Gregor69319002010-08-31 23:48:11 +00001002bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001003 // Visit nested-name-specifier.
1004 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1005 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1006 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001007
1008 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1009 D->getTargetNameLoc(), TU));
1010}
1011
Douglas Gregor7e242562010-09-01 19:52:22 +00001012bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001013 // Visit nested-name-specifier.
1014 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1015 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1016 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001017
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001018 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1019 return true;
1020
Douglas Gregor7e242562010-09-01 19:52:22 +00001021 return VisitDeclarationNameInfo(D->getNameInfo());
1022}
1023
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001024bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001025 // Visit nested-name-specifier.
1026 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1027 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1028 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001029
1030 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1031 D->getIdentLocation(), TU));
1032}
1033
Douglas Gregor7e242562010-09-01 19:52:22 +00001034bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001035 // Visit nested-name-specifier.
1036 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1037 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1038 return true;
1039
Douglas Gregor7e242562010-09-01 19:52:22 +00001040 return VisitDeclarationNameInfo(D->getNameInfo());
1041}
1042
1043bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1044 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001045 // Visit nested-name-specifier.
1046 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1047 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1048 return true;
1049
Douglas Gregor7e242562010-09-01 19:52:22 +00001050 return false;
1051}
1052
Douglas Gregor01829d32010-08-31 14:41:23 +00001053bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1054 switch (Name.getName().getNameKind()) {
1055 case clang::DeclarationName::Identifier:
1056 case clang::DeclarationName::CXXLiteralOperatorName:
1057 case clang::DeclarationName::CXXOperatorName:
1058 case clang::DeclarationName::CXXUsingDirective:
1059 return false;
1060
1061 case clang::DeclarationName::CXXConstructorName:
1062 case clang::DeclarationName::CXXDestructorName:
1063 case clang::DeclarationName::CXXConversionFunctionName:
1064 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1065 return Visit(TSInfo->getTypeLoc());
1066 return false;
1067
1068 case clang::DeclarationName::ObjCZeroArgSelector:
1069 case clang::DeclarationName::ObjCOneArgSelector:
1070 case clang::DeclarationName::ObjCMultiArgSelector:
1071 // FIXME: Per-identifier location info?
1072 return false;
1073 }
1074
1075 return false;
1076}
1077
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001078bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1079 SourceRange Range) {
1080 // FIXME: This whole routine is a hack to work around the lack of proper
1081 // source information in nested-name-specifiers (PR5791). Since we do have
1082 // a beginning source location, we can visit the first component of the
1083 // nested-name-specifier, if it's a single-token component.
1084 if (!NNS)
1085 return false;
1086
1087 // Get the first component in the nested-name-specifier.
1088 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1089 NNS = Prefix;
1090
1091 switch (NNS->getKind()) {
1092 case NestedNameSpecifier::Namespace:
1093 // FIXME: The token at this source location might actually have been a
1094 // namespace alias, but we don't model that. Lame!
1095 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1096 TU));
1097
1098 case NestedNameSpecifier::TypeSpec: {
1099 // If the type has a form where we know that the beginning of the source
1100 // range matches up with a reference cursor. Visit the appropriate reference
1101 // cursor.
1102 Type *T = NNS->getAsType();
1103 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1104 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1105 if (const TagType *Tag = dyn_cast<TagType>(T))
1106 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1107 if (const TemplateSpecializationType *TST
1108 = dyn_cast<TemplateSpecializationType>(T))
1109 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1110 break;
1111 }
1112
1113 case NestedNameSpecifier::TypeSpecWithTemplate:
1114 case NestedNameSpecifier::Global:
1115 case NestedNameSpecifier::Identifier:
1116 break;
1117 }
1118
1119 return false;
1120}
1121
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001122bool CursorVisitor::VisitTemplateParameters(
1123 const TemplateParameterList *Params) {
1124 if (!Params)
1125 return false;
1126
1127 for (TemplateParameterList::const_iterator P = Params->begin(),
1128 PEnd = Params->end();
1129 P != PEnd; ++P) {
1130 if (Visit(MakeCXCursor(*P, TU)))
1131 return true;
1132 }
1133
1134 return false;
1135}
1136
Douglas Gregor0b36e612010-08-31 20:37:03 +00001137bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1138 switch (Name.getKind()) {
1139 case TemplateName::Template:
1140 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1141
1142 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001143 // Visit the overloaded template set.
1144 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1145 return true;
1146
Douglas Gregor0b36e612010-08-31 20:37:03 +00001147 return false;
1148
1149 case TemplateName::DependentTemplate:
1150 // FIXME: Visit nested-name-specifier.
1151 return false;
1152
1153 case TemplateName::QualifiedTemplate:
1154 // FIXME: Visit nested-name-specifier.
1155 return Visit(MakeCursorTemplateRef(
1156 Name.getAsQualifiedTemplateName()->getDecl(),
1157 Loc, TU));
1158 }
1159
1160 return false;
1161}
1162
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001163bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1164 switch (TAL.getArgument().getKind()) {
1165 case TemplateArgument::Null:
1166 case TemplateArgument::Integral:
1167 return false;
1168
1169 case TemplateArgument::Pack:
1170 // FIXME: Implement when variadic templates come along.
1171 return false;
1172
1173 case TemplateArgument::Type:
1174 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1175 return Visit(TSInfo->getTypeLoc());
1176 return false;
1177
1178 case TemplateArgument::Declaration:
1179 if (Expr *E = TAL.getSourceDeclExpression())
1180 return Visit(MakeCXCursor(E, StmtParent, TU));
1181 return false;
1182
1183 case TemplateArgument::Expression:
1184 if (Expr *E = TAL.getSourceExpression())
1185 return Visit(MakeCXCursor(E, StmtParent, TU));
1186 return false;
1187
1188 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001189 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1190 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001191 }
1192
1193 return false;
1194}
1195
Ted Kremeneka0536d82010-05-07 01:04:29 +00001196bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1197 return VisitDeclContext(D);
1198}
1199
Douglas Gregor01829d32010-08-31 14:41:23 +00001200bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1201 return Visit(TL.getUnqualifiedLoc());
1202}
1203
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001204bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1205 ASTContext &Context = TU->getASTContext();
1206
1207 // Some builtin types (such as Objective-C's "id", "sel", and
1208 // "Class") have associated declarations. Create cursors for those.
1209 QualType VisitType;
1210 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001211 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001212 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001213 case BuiltinType::Char_U:
1214 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001215 case BuiltinType::Char16:
1216 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001217 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001218 case BuiltinType::UInt:
1219 case BuiltinType::ULong:
1220 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001221 case BuiltinType::UInt128:
1222 case BuiltinType::Char_S:
1223 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001224 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001225 case BuiltinType::Short:
1226 case BuiltinType::Int:
1227 case BuiltinType::Long:
1228 case BuiltinType::LongLong:
1229 case BuiltinType::Int128:
1230 case BuiltinType::Float:
1231 case BuiltinType::Double:
1232 case BuiltinType::LongDouble:
1233 case BuiltinType::NullPtr:
1234 case BuiltinType::Overload:
1235 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001236 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001237
1238 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001239 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001240
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001241 case BuiltinType::ObjCId:
1242 VisitType = Context.getObjCIdType();
1243 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001244
1245 case BuiltinType::ObjCClass:
1246 VisitType = Context.getObjCClassType();
1247 break;
1248
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001249 case BuiltinType::ObjCSel:
1250 VisitType = Context.getObjCSelType();
1251 break;
1252 }
1253
1254 if (!VisitType.isNull()) {
1255 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001256 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001257 TU));
1258 }
1259
1260 return false;
1261}
1262
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001263bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1264 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1265}
1266
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1268 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1269}
1270
1271bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1272 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1273}
1274
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001275bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001276 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001277 // no context information with which we can match up the depth/index in the
1278 // type to the appropriate
1279 return false;
1280}
1281
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001282bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1283 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1284 return true;
1285
John McCallc12c5bb2010-05-15 11:32:37 +00001286 return false;
1287}
1288
1289bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1290 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1291 return true;
1292
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001293 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1294 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1295 TU)))
1296 return true;
1297 }
1298
1299 return false;
1300}
1301
1302bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001303 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001304}
1305
1306bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1307 return Visit(TL.getPointeeLoc());
1308}
1309
1310bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1311 return Visit(TL.getPointeeLoc());
1312}
1313
1314bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1315 return Visit(TL.getPointeeLoc());
1316}
1317
1318bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001319 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001320}
1321
1322bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001323 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001324}
1325
Douglas Gregor01829d32010-08-31 14:41:23 +00001326bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1327 bool SkipResultType) {
1328 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001329 return true;
1330
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001332 if (Decl *D = TL.getArg(I))
1333 if (Visit(MakeCXCursor(D, TU)))
1334 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335
1336 return false;
1337}
1338
1339bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1340 if (Visit(TL.getElementLoc()))
1341 return true;
1342
1343 if (Expr *Size = TL.getSizeExpr())
1344 return Visit(MakeCXCursor(Size, StmtParent, TU));
1345
1346 return false;
1347}
1348
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001349bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1350 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001351 // Visit the template name.
1352 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1353 TL.getTemplateNameLoc()))
1354 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001355
1356 // Visit the template arguments.
1357 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1358 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1359 return true;
1360
1361 return false;
1362}
1363
Douglas Gregor2332c112010-01-21 20:48:56 +00001364bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1365 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1366}
1367
1368bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1369 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1370 return Visit(TSInfo->getTypeLoc());
1371
1372 return false;
1373}
1374
Douglas Gregora59e3902010-01-21 23:27:09 +00001375bool CursorVisitor::VisitStmt(Stmt *S) {
1376 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1377 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001378 if (Stmt *C = *Child)
1379 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1380 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001381 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001382
Douglas Gregora59e3902010-01-21 23:27:09 +00001383 return false;
1384}
1385
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001386bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1387 // Specially handle CaseStmts because they can be nested, e.g.:
1388 //
1389 // case 1:
1390 // case 2:
1391 //
1392 // In this case the second CaseStmt is the child of the first. Walking
1393 // these recursively can blow out the stack.
1394 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1395 while (true) {
1396 // Set the Parent field to Cursor, then back to its old value once we're
1397 // done.
1398 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1399
1400 if (Stmt *LHS = S->getLHS())
1401 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1402 return true;
1403 if (Stmt *RHS = S->getRHS())
1404 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1405 return true;
1406 if (Stmt *SubStmt = S->getSubStmt()) {
1407 if (!isa<CaseStmt>(SubStmt))
1408 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1409
1410 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1411 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1412 Cursor = MakeCXCursor(CS, StmtParent, TU);
1413 if (RegionOfInterest.isValid()) {
1414 SourceRange Range = CS->getSourceRange();
1415 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1416 return false;
1417 }
1418
1419 switch (Visitor(Cursor, Parent, ClientData)) {
1420 case CXChildVisit_Break: return true;
1421 case CXChildVisit_Continue: return false;
1422 case CXChildVisit_Recurse:
1423 // Perform tail-recursion manually.
1424 S = CS;
1425 continue;
1426 }
1427 }
1428 return false;
1429 }
1430}
1431
Douglas Gregora59e3902010-01-21 23:27:09 +00001432bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1433 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1434 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001435 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001436 return true;
1437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438
Douglas Gregora59e3902010-01-21 23:27:09 +00001439 return false;
1440}
1441
Douglas Gregor36897b02010-09-10 00:22:18 +00001442bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1443 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1444}
1445
Douglas Gregorf5bab412010-01-22 01:00:11 +00001446bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1447 if (VarDecl *Var = S->getConditionVariable()) {
1448 if (Visit(MakeCXCursor(Var, TU)))
1449 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001450 }
1451
Douglas Gregor263b47b2010-01-25 16:12:32 +00001452 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1453 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001454 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1455 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001456 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1457 return true;
1458
1459 return false;
1460}
1461
1462bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1463 if (VarDecl *Var = S->getConditionVariable()) {
1464 if (Visit(MakeCXCursor(Var, TU)))
1465 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001466 }
1467
Douglas Gregor263b47b2010-01-25 16:12:32 +00001468 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1469 return true;
1470 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1471 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001472
Douglas Gregor263b47b2010-01-25 16:12:32 +00001473 return false;
1474}
1475
1476bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1477 if (VarDecl *Var = S->getConditionVariable()) {
1478 if (Visit(MakeCXCursor(Var, TU)))
1479 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001480 }
1481
Douglas Gregor263b47b2010-01-25 16:12:32 +00001482 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1483 return true;
1484 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001485 return true;
1486
Douglas Gregor263b47b2010-01-25 16:12:32 +00001487 return false;
1488}
1489
1490bool CursorVisitor::VisitForStmt(ForStmt *S) {
1491 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1492 return true;
1493 if (VarDecl *Var = S->getConditionVariable()) {
1494 if (Visit(MakeCXCursor(Var, TU)))
1495 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001496 }
1497
Douglas Gregor263b47b2010-01-25 16:12:32 +00001498 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1499 return true;
1500 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1501 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001502 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1503 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001504
Douglas Gregorf5bab412010-01-22 01:00:11 +00001505 return false;
1506}
1507
Douglas Gregor8947a752010-09-02 20:35:02 +00001508bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1509 // Visit nested-name-specifier, if present.
1510 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1511 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1512 return true;
1513
1514 // Visit declaration name.
1515 if (VisitDeclarationNameInfo(E->getNameInfo()))
1516 return true;
1517
1518 // Visit explicitly-specified template arguments.
1519 if (E->hasExplicitTemplateArgs()) {
1520 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1521 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1522 *ArgEnd = Arg + Args.NumTemplateArgs;
1523 Arg != ArgEnd; ++Arg)
1524 if (VisitTemplateArgumentLoc(*Arg))
1525 return true;
1526 }
1527
1528 return false;
1529}
1530
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001531bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1532 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1533 return true;
1534
1535 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1536 return true;
1537
1538 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1539 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1540 return true;
1541
1542 return false;
1543}
1544
Ted Kremenek3064ef92010-08-27 21:34:58 +00001545bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1546 if (D->isDefinition()) {
1547 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1548 E = D->bases_end(); I != E; ++I) {
1549 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1550 return true;
1551 }
1552 }
1553
1554 return VisitTagDecl(D);
1555}
1556
1557
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001558bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1559 return Visit(B->getBlockDecl());
1560}
1561
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001562bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001563 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001564 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1565 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001566
1567 // Visit the components of the offsetof expression.
1568 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1569 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1570 const OffsetOfNode &Node = E->getComponent(I);
1571 switch (Node.getKind()) {
1572 case OffsetOfNode::Array:
1573 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1574 StmtParent, TU)))
1575 return true;
1576 break;
1577
1578 case OffsetOfNode::Field:
1579 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1580 TU)))
1581 return true;
1582 break;
1583
1584 case OffsetOfNode::Identifier:
1585 case OffsetOfNode::Base:
1586 continue;
1587 }
1588 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001589
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001590 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001591}
1592
Douglas Gregor336fd812010-01-23 00:40:08 +00001593bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1594 if (E->isArgumentType()) {
1595 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1596 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001597
Douglas Gregor336fd812010-01-23 00:40:08 +00001598 return false;
1599 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001600
Douglas Gregor336fd812010-01-23 00:40:08 +00001601 return VisitExpr(E);
1602}
1603
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001604bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1605 // Visit the base expression.
1606 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1607 return true;
1608
1609 // Visit the nested-name-specifier
1610 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1611 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1612 return true;
1613
1614 // Visit the declaration name.
1615 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1616 return true;
1617
1618 // Visit the explicitly-specified template arguments, if any.
1619 if (E->hasExplicitTemplateArgs()) {
1620 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1621 *ArgEnd = Arg + E->getNumTemplateArgs();
1622 Arg != ArgEnd;
1623 ++Arg) {
1624 if (VisitTemplateArgumentLoc(*Arg))
1625 return true;
1626 }
1627 }
1628
1629 return false;
1630}
1631
Douglas Gregor336fd812010-01-23 00:40:08 +00001632bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1633 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1634 if (Visit(TSInfo->getTypeLoc()))
1635 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001636
Douglas Gregor336fd812010-01-23 00:40:08 +00001637 return VisitCastExpr(E);
1638}
1639
1640bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1641 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1642 if (Visit(TSInfo->getTypeLoc()))
1643 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001644
Douglas Gregor336fd812010-01-23 00:40:08 +00001645 return VisitExpr(E);
1646}
1647
Douglas Gregor36897b02010-09-10 00:22:18 +00001648bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1649 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1650}
1651
Douglas Gregor648220e2010-08-10 15:02:34 +00001652bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1653 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1654 Visit(E->getArgTInfo2()->getTypeLoc());
1655}
1656
1657bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1658 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1659 return true;
1660
1661 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1662}
1663
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001664bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1665 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001666 if (InitListExpr *Syntactic = E->getSyntacticForm())
1667 return VisitExpr(Syntactic);
1668
1669 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001670}
1671
1672bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1673 // Visit the designators.
1674 typedef DesignatedInitExpr::Designator Designator;
1675 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1676 DEnd = E->designators_end();
1677 D != DEnd; ++D) {
1678 if (D->isFieldDesignator()) {
1679 if (FieldDecl *Field = D->getField())
1680 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1681 return true;
1682
1683 continue;
1684 }
1685
1686 if (D->isArrayDesignator()) {
1687 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1688 return true;
1689
1690 continue;
1691 }
1692
1693 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1694 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1695 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1696 return true;
1697 }
1698
1699 // Visit the initializer value itself.
1700 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1701}
1702
Douglas Gregor94802292010-09-02 21:20:16 +00001703bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1704 if (E->isTypeOperand()) {
1705 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1706 return Visit(TSInfo->getTypeLoc());
1707
1708 return false;
1709 }
1710
1711 return VisitExpr(E);
1712}
1713
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001714bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1715 if (E->isTypeOperand()) {
1716 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1717 return Visit(TSInfo->getTypeLoc());
1718
1719 return false;
1720 }
1721
1722 return VisitExpr(E);
1723}
1724
Douglas Gregorab6677e2010-09-08 00:15:04 +00001725bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1726 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1727 return Visit(TSInfo->getTypeLoc());
1728
1729 return VisitExpr(E);
1730}
1731
1732bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1733 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1734 return Visit(TSInfo->getTypeLoc());
1735
1736 return false;
1737}
1738
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001739bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1740 // Visit placement arguments.
1741 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1742 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1743 return true;
1744
1745 // Visit the allocated type.
1746 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1747 if (Visit(TSInfo->getTypeLoc()))
1748 return true;
1749
1750 // Visit the array size, if any.
1751 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1752 return true;
1753
1754 // Visit the initializer or constructor arguments.
1755 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1756 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1757 return true;
1758
1759 return false;
1760}
1761
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001762bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1763 // Visit base expression.
1764 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1765 return true;
1766
1767 // Visit the nested-name-specifier.
1768 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1769 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1770 return true;
1771
1772 // Visit the scope type that looks disturbingly like the nested-name-specifier
1773 // but isn't.
1774 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1775 if (Visit(TSInfo->getTypeLoc()))
1776 return true;
1777
1778 // Visit the name of the type being destroyed.
1779 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1780 if (Visit(TSInfo->getTypeLoc()))
1781 return true;
1782
1783 return false;
1784}
1785
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001786bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1787 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1788}
1789
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001790bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001791 // Visit the nested-name-specifier.
1792 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1793 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1794 return true;
1795
1796 // Visit the declaration name.
1797 if (VisitDeclarationNameInfo(E->getNameInfo()))
1798 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001799
1800 // Visit the overloaded declaration reference.
1801 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1802 return true;
1803
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001804 // Visit the explicitly-specified template arguments.
1805 if (const ExplicitTemplateArgumentList *ArgList
1806 = E->getOptionalExplicitTemplateArgs()) {
1807 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1808 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1809 Arg != ArgEnd; ++Arg) {
1810 if (VisitTemplateArgumentLoc(*Arg))
1811 return true;
1812 }
1813 }
1814
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001815 return false;
1816}
1817
Douglas Gregorbfebed22010-09-03 17:24:10 +00001818bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1819 DependentScopeDeclRefExpr *E) {
1820 // Visit the nested-name-specifier.
1821 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1822 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1823 return true;
1824
1825 // Visit the declaration name.
1826 if (VisitDeclarationNameInfo(E->getNameInfo()))
1827 return true;
1828
1829 // Visit the explicitly-specified template arguments.
1830 if (const ExplicitTemplateArgumentList *ArgList
1831 = E->getOptionalExplicitTemplateArgs()) {
1832 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1833 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1834 Arg != ArgEnd; ++Arg) {
1835 if (VisitTemplateArgumentLoc(*Arg))
1836 return true;
1837 }
1838 }
1839
1840 return false;
1841}
1842
Douglas Gregorab6677e2010-09-08 00:15:04 +00001843bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1844 CXXUnresolvedConstructExpr *E) {
1845 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1846 if (Visit(TSInfo->getTypeLoc()))
1847 return true;
1848
1849 return VisitExpr(E);
1850}
1851
Douglas Gregor25d63622010-09-03 17:35:34 +00001852bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1853 CXXDependentScopeMemberExpr *E) {
1854 // Visit the base expression, if there is one.
1855 if (!E->isImplicitAccess() &&
1856 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1857 return true;
1858
1859 // Visit the nested-name-specifier.
1860 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1861 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1862 return true;
1863
1864 // Visit the declaration name.
1865 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1866 return true;
1867
1868 // Visit the explicitly-specified template arguments.
1869 if (const ExplicitTemplateArgumentList *ArgList
1870 = E->getOptionalExplicitTemplateArgs()) {
1871 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1872 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1873 Arg != ArgEnd; ++Arg) {
1874 if (VisitTemplateArgumentLoc(*Arg))
1875 return true;
1876 }
1877 }
1878
1879 return false;
1880}
1881
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001882bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1883 // Visit the base expression, if there is one.
1884 if (!E->isImplicitAccess() &&
1885 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1886 return true;
1887
1888 return VisitOverloadExpr(E);
1889}
Douglas Gregor25d63622010-09-03 17:35:34 +00001890
Douglas Gregorc2350e52010-03-08 16:40:19 +00001891bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001892 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1893 if (Visit(TSInfo->getTypeLoc()))
1894 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001895
1896 return VisitExpr(E);
1897}
1898
Douglas Gregor81d34662010-04-20 15:39:42 +00001899bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1900 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1901}
1902
1903
Ted Kremenek09dfa372010-02-18 05:46:33 +00001904bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001905 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1906 i != e; ++i)
1907 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001908 return true;
1909
1910 return false;
1911}
1912
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001913extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001914CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1915 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001916 // We use crash recovery to make some of our APIs more reliable, implicitly
1917 // enable it.
1918 llvm::CrashRecoveryContext::Enable();
1919
Douglas Gregora030b7c2010-01-22 20:35:53 +00001920 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001921 if (excludeDeclarationsFromPCH)
1922 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001923 if (displayDiagnostics)
1924 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001925 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001926}
1927
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001928void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001929 if (CIdx)
1930 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001931 if (getenv("LIBCLANG_TIMING"))
1932 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001933}
1934
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001935void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001936 if (CIdx) {
1937 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1938 CXXIdx->setUseExternalASTGeneration(value);
1939 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001940}
1941
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001942CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001943 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001944 if (!CIdx)
1945 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001946
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001947 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001948
Douglas Gregor28019772010-04-05 23:52:57 +00001949 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001950 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001951 CXXIdx->getOnlyLocalDecls(),
1952 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001953}
1954
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001955unsigned clang_defaultEditingTranslationUnitOptions() {
1956 return CXTranslationUnit_PrecompiledPreamble;
1957}
1958
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001959CXTranslationUnit
1960clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1961 const char *source_filename,
1962 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001963 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001964 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001965 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001966 return clang_parseTranslationUnit(CIdx, source_filename,
1967 command_line_args, num_command_line_args,
1968 unsaved_files, num_unsaved_files,
1969 CXTranslationUnit_DetailedPreprocessingRecord);
1970}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001971
1972struct ParseTranslationUnitInfo {
1973 CXIndex CIdx;
1974 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001975 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001976 int num_command_line_args;
1977 struct CXUnsavedFile *unsaved_files;
1978 unsigned num_unsaved_files;
1979 unsigned options;
1980 CXTranslationUnit result;
1981};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001982static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001983 ParseTranslationUnitInfo *PTUI =
1984 static_cast<ParseTranslationUnitInfo*>(UserData);
1985 CXIndex CIdx = PTUI->CIdx;
1986 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001987 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001988 int num_command_line_args = PTUI->num_command_line_args;
1989 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1990 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1991 unsigned options = PTUI->options;
1992 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001993
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001994 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001995 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001996
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001997 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1998
Douglas Gregor44c181a2010-07-23 00:33:23 +00001999 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002000 bool CompleteTranslationUnit
2001 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002002 bool CacheCodeCompetionResults
2003 = options & CXTranslationUnit_CacheCompletionResults;
2004
Douglas Gregor5352ac02010-01-28 00:27:43 +00002005 // Configure the diagnostics.
2006 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002007 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2008 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002009
Douglas Gregor4db64a42010-01-23 00:14:00 +00002010 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2011 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002012 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002013 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002014 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002015 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2016 Buffer));
2017 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002018
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002019 if (!CXXIdx->getUseExternalASTGeneration()) {
2020 llvm::SmallVector<const char *, 16> Args;
2021
2022 // The 'source_filename' argument is optional. If the caller does not
2023 // specify it then it is assumed that the source file is specified
2024 // in the actual argument list.
2025 if (source_filename)
2026 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002027
2028 // Since the Clang C library is primarily used by batch tools dealing with
2029 // (often very broken) source code, where spell-checking can have a
2030 // significant negative impact on performance (particularly when
2031 // precompiled headers are involved), we disable it by default.
2032 // Note that we place this argument early in the list, so that it can be
2033 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00002034 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002035
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002036 Args.insert(Args.end(), command_line_args,
2037 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00002038
Douglas Gregor44c181a2010-07-23 00:33:23 +00002039 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00002040 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2041 Args.push_back("-Xclang");
2042 Args.push_back("-detailed-preprocessing-record");
2043 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00002044
Douglas Gregor5352ac02010-01-28 00:27:43 +00002045 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002046
Ted Kremenek29b72842010-01-07 22:49:05 +00002047#ifdef USE_CRASHTRACER
2048 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00002049#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002050
Daniel Dunbar94220972009-12-05 02:17:18 +00002051 llvm::OwningPtr<ASTUnit> Unit(
2052 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00002053 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00002054 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00002055 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002056 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002057 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00002058 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00002059 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002060 CompleteTranslationUnit,
2061 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002062
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002063 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00002064 // Make sure to check that 'Unit' is non-NULL.
2065 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00002066 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2067 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002068 D != DEnd; ++D) {
2069 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00002070 CXString Msg = clang_formatDiagnostic(&Diag,
2071 clang_defaultDiagnosticDisplayOptions());
2072 fprintf(stderr, "%s\n", clang_getCString(Msg));
2073 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002074 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002075#ifdef LLVM_ON_WIN32
2076 // On Windows, force a flush, since there may be multiple copies of
2077 // stderr and stdout in the file system, all with different buffers
2078 // but writing to the same device.
2079 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00002080#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002081 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002082 }
Daniel Dunbar94220972009-12-05 02:17:18 +00002083
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002084 PTUI->result = Unit.take();
2085 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002086 }
2087
Ted Kremenek139ba862009-10-22 00:03:57 +00002088 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002089 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002090
Ted Kremenek139ba862009-10-22 00:03:57 +00002091 // First add the complete path to the 'clang' executable.
2092 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002093 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002094
Ted Kremenek139ba862009-10-22 00:03:57 +00002095 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002096 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002097
Ted Kremenek139ba862009-10-22 00:03:57 +00002098 // The 'source_filename' argument is optional. If the caller does not
2099 // specify it then it is assumed that the source file is specified
2100 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002101 if (source_filename)
2102 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00002103
Steve Naroff37b5ac22009-10-15 20:50:09 +00002104 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00002105 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002106 char astTmpFile[L_tmpnam];
2107 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002108
2109 // Since the Clang C library is primarily used by batch tools dealing with
2110 // (often very broken) source code, where spell-checking can have a
2111 // significant negative impact on performance (particularly when
2112 // precompiled headers are involved), we disable it by default.
2113 // Note that we place this argument early in the list, so that it can be
2114 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00002115 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00002116
Douglas Gregor4db64a42010-01-23 00:14:00 +00002117 // Remap any unsaved files to temporary files.
2118 std::vector<llvm::sys::Path> TemporaryFiles;
2119 std::vector<std::string> RemapArgs;
2120 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002121 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002122
Douglas Gregor4db64a42010-01-23 00:14:00 +00002123 // The pointers into the elements of RemapArgs are stable because we
2124 // won't be adding anything to RemapArgs after this point.
2125 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
2126 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002127
Ted Kremenek139ba862009-10-22 00:03:57 +00002128 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
2129 for (int i = 0; i < num_command_line_args; ++i)
2130 if (const char *arg = command_line_args[i]) {
2131 if (strcmp(arg, "-o") == 0) {
2132 ++i; // Also skip the matching argument.
2133 continue;
2134 }
2135 if (strcmp(arg, "-emit-ast") == 0 ||
2136 strcmp(arg, "-c") == 0 ||
2137 strcmp(arg, "-fsyntax-only") == 0) {
2138 continue;
2139 }
2140
2141 // Keep the argument.
2142 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002143 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002144
Douglas Gregord93256e2010-01-28 06:00:51 +00002145 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002146 char tmpFileResults[L_tmpnam];
2147 char *tmpResultsFileName = tmpnam(tmpFileResults);
2148 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00002149 TemporaryFiles.push_back(DiagnosticsFile);
2150 argv.push_back("-fdiagnostics-binary");
2151
Douglas Gregor44c181a2010-07-23 00:33:23 +00002152 // Do we need the detailed preprocessing record?
2153 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2154 argv.push_back("-Xclang");
2155 argv.push_back("-detailed-preprocessing-record");
2156 }
2157
Ted Kremenek139ba862009-10-22 00:03:57 +00002158 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002159 argv.push_back(NULL);
2160
Ted Kremenekfeb15e32009-10-26 22:14:08 +00002161 // Invoke 'clang'.
2162 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
2163 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00002164 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00002165 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
2166 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00002167 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002168 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00002169 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002170
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002171 if (!ErrMsg.empty()) {
2172 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00002173 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002174 I != E; ++I) {
2175 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00002176 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002177 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00002178 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179
Daniel Dunbar32141c82010-02-23 20:23:45 +00002180 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00002181 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00002182
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002183 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002184 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002185 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002186 RemappedFiles.size(),
2187 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00002188 if (ATU) {
2189 LoadSerializedDiagnostics(DiagnosticsFile,
2190 num_unsaved_files, unsaved_files,
2191 ATU->getFileManager(),
2192 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00002193 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002194 } else if (CXXIdx->getDisplayDiagnostics()) {
2195 // We failed to load the ASTUnit, but we can still deserialize the
2196 // diagnostics and emit them.
2197 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00002198 Diagnostic Diag;
2199 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002200 // FIXME: Faked LangOpts!
2201 LangOptions LangOpts;
2202 llvm::SmallVector<StoredDiagnostic, 4> Diags;
2203 LoadSerializedDiagnostics(DiagnosticsFile,
2204 num_unsaved_files, unsaved_files,
2205 FileMgr, SourceMgr, Diags);
2206 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
2207 DEnd = Diags.end();
2208 D != DEnd; ++D) {
2209 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00002210 CXString Msg = clang_formatDiagnostic(&Diag,
2211 clang_defaultDiagnosticDisplayOptions());
2212 fprintf(stderr, "%s\n", clang_getCString(Msg));
2213 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002214 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002215
2216#ifdef LLVM_ON_WIN32
2217 // On Windows, force a flush, since there may be multiple copies of
2218 // stderr and stdout in the file system, all with different buffers
2219 // but writing to the same device.
2220 fflush(stderr);
2221#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00002222 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002223
Douglas Gregor313e26c2010-02-18 23:35:40 +00002224 if (ATU) {
2225 // Make the translation unit responsible for destroying all temporary files.
2226 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2227 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002228 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00002229 } else {
2230 // Destroy all of the temporary files now; they can't be referenced any
2231 // longer.
2232 llvm::sys::Path(astTmpFile).eraseFromDisk();
2233 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2234 TemporaryFiles[i].eraseFromDisk();
2235 }
2236
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002237 PTUI->result = ATU;
2238}
2239CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2240 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002241 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002242 int num_command_line_args,
2243 struct CXUnsavedFile *unsaved_files,
2244 unsigned num_unsaved_files,
2245 unsigned options) {
2246 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2247 num_command_line_args, unsaved_files, num_unsaved_files,
2248 options, 0 };
2249 llvm::CrashRecoveryContext CRC;
2250
2251 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002252 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2253 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2254 fprintf(stderr, " 'command_line_args' : [");
2255 for (int i = 0; i != num_command_line_args; ++i) {
2256 if (i)
2257 fprintf(stderr, ", ");
2258 fprintf(stderr, "'%s'", command_line_args[i]);
2259 }
2260 fprintf(stderr, "],\n");
2261 fprintf(stderr, " 'unsaved_files' : [");
2262 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2263 if (i)
2264 fprintf(stderr, ", ");
2265 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2266 unsaved_files[i].Length);
2267 }
2268 fprintf(stderr, "],\n");
2269 fprintf(stderr, " 'options' : %d,\n", options);
2270 fprintf(stderr, "}\n");
2271
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002272 return 0;
2273 }
2274
2275 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002276}
2277
Douglas Gregor19998442010-08-13 15:35:05 +00002278unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2279 return CXSaveTranslationUnit_None;
2280}
2281
2282int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2283 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002284 if (!TU)
2285 return 1;
2286
2287 return static_cast<ASTUnit *>(TU)->Save(FileName);
2288}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002289
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002290void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002291 if (CTUnit) {
2292 // If the translation unit has been marked as unsafe to free, just discard
2293 // it.
2294 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2295 return;
2296
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002297 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002298 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002299}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002300
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002301unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2302 return CXReparse_None;
2303}
2304
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002305struct ReparseTranslationUnitInfo {
2306 CXTranslationUnit TU;
2307 unsigned num_unsaved_files;
2308 struct CXUnsavedFile *unsaved_files;
2309 unsigned options;
2310 int result;
2311};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002312
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002313static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002314 ReparseTranslationUnitInfo *RTUI =
2315 static_cast<ReparseTranslationUnitInfo*>(UserData);
2316 CXTranslationUnit TU = RTUI->TU;
2317 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2318 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2319 unsigned options = RTUI->options;
2320 (void) options;
2321 RTUI->result = 1;
2322
Douglas Gregorabc563f2010-07-19 21:46:24 +00002323 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002324 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002325
2326 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2327 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002328
2329 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2330 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2331 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2332 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002333 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002334 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2335 Buffer));
2336 }
2337
Douglas Gregor593b0c12010-09-23 18:47:53 +00002338 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2339 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002340}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002341
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002342int clang_reparseTranslationUnit(CXTranslationUnit TU,
2343 unsigned num_unsaved_files,
2344 struct CXUnsavedFile *unsaved_files,
2345 unsigned options) {
2346 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2347 options, 0 };
2348 llvm::CrashRecoveryContext CRC;
2349
2350 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002351 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002352 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2353 return 1;
2354 }
2355
2356 return RTUI.result;
2357}
2358
Douglas Gregordf95a132010-08-09 20:45:32 +00002359
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002360CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002361 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002362 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002363
Steve Naroff77accc12009-09-03 18:19:54 +00002364 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002365 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002366}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002367
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002368CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002369 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002370 return Result;
2371}
2372
Ted Kremenekfb480492010-01-13 21:46:36 +00002373} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002374
Ted Kremenekfb480492010-01-13 21:46:36 +00002375//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002376// CXSourceLocation and CXSourceRange Operations.
2377//===----------------------------------------------------------------------===//
2378
Douglas Gregorb9790342010-01-22 21:44:22 +00002379extern "C" {
2380CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002381 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002382 return Result;
2383}
2384
2385unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002386 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2387 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2388 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002389}
2390
2391CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2392 CXFile file,
2393 unsigned line,
2394 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002395 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002396 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002397
Douglas Gregorb9790342010-01-22 21:44:22 +00002398 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2399 SourceLocation SLoc
2400 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002401 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002402 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002403
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002404 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002405}
2406
Douglas Gregor5352ac02010-01-28 00:27:43 +00002407CXSourceRange clang_getNullRange() {
2408 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2409 return Result;
2410}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002411
Douglas Gregor5352ac02010-01-28 00:27:43 +00002412CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2413 if (begin.ptr_data[0] != end.ptr_data[0] ||
2414 begin.ptr_data[1] != end.ptr_data[1])
2415 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002416
2417 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002418 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002419 return Result;
2420}
2421
Douglas Gregor46766dc2010-01-26 19:19:08 +00002422void clang_getInstantiationLocation(CXSourceLocation location,
2423 CXFile *file,
2424 unsigned *line,
2425 unsigned *column,
2426 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002427 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2428
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002429 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002430 if (file)
2431 *file = 0;
2432 if (line)
2433 *line = 0;
2434 if (column)
2435 *column = 0;
2436 if (offset)
2437 *offset = 0;
2438 return;
2439 }
2440
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002441 const SourceManager &SM =
2442 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002443 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002444
2445 if (file)
2446 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2447 if (line)
2448 *line = SM.getInstantiationLineNumber(InstLoc);
2449 if (column)
2450 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002451 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002452 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002453}
2454
Douglas Gregor1db19de2010-01-19 21:36:55 +00002455CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002456 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002457 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002458 return Result;
2459}
2460
2461CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002462 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002463 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002464 return Result;
2465}
2466
Douglas Gregorb9790342010-01-22 21:44:22 +00002467} // end: extern "C"
2468
Douglas Gregor1db19de2010-01-19 21:36:55 +00002469//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002470// CXFile Operations.
2471//===----------------------------------------------------------------------===//
2472
2473extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002474CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002475 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002476 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002477
Steve Naroff88145032009-10-27 14:35:18 +00002478 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002479 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002480}
2481
2482time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002483 if (!SFile)
2484 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002485
Steve Naroff88145032009-10-27 14:35:18 +00002486 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2487 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002488}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002489
Douglas Gregorb9790342010-01-22 21:44:22 +00002490CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2491 if (!tu)
2492 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002493
Douglas Gregorb9790342010-01-22 21:44:22 +00002494 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002495
Douglas Gregorb9790342010-01-22 21:44:22 +00002496 FileManager &FMgr = CXXUnit->getFileManager();
2497 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2498 return const_cast<FileEntry *>(File);
2499}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002500
Ted Kremenekfb480492010-01-13 21:46:36 +00002501} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002502
Ted Kremenekfb480492010-01-13 21:46:36 +00002503//===----------------------------------------------------------------------===//
2504// CXCursor Operations.
2505//===----------------------------------------------------------------------===//
2506
Ted Kremenekfb480492010-01-13 21:46:36 +00002507static Decl *getDeclFromExpr(Stmt *E) {
2508 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2509 return RefExpr->getDecl();
2510 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2511 return ME->getMemberDecl();
2512 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2513 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002514
Ted Kremenekfb480492010-01-13 21:46:36 +00002515 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2516 return getDeclFromExpr(CE->getCallee());
2517 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2518 return getDeclFromExpr(CE->getSubExpr());
2519 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2520 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002521
Ted Kremenekfb480492010-01-13 21:46:36 +00002522 return 0;
2523}
2524
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002525static SourceLocation getLocationFromExpr(Expr *E) {
2526 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2527 return /*FIXME:*/Msg->getLeftLoc();
2528 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2529 return DRE->getLocation();
2530 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2531 return Member->getMemberLoc();
2532 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2533 return Ivar->getLocation();
2534 return E->getLocStart();
2535}
2536
Ted Kremenekfb480492010-01-13 21:46:36 +00002537extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002538
2539unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002540 CXCursorVisitor visitor,
2541 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002542 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002543
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002544 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2545 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002546 return CursorVis.VisitChildren(parent);
2547}
2548
Douglas Gregor78205d42010-01-20 21:45:58 +00002549static CXString getDeclSpelling(Decl *D) {
2550 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2551 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002552 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002553
Douglas Gregor78205d42010-01-20 21:45:58 +00002554 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002555 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002556
Douglas Gregor78205d42010-01-20 21:45:58 +00002557 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2558 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2559 // and returns different names. NamedDecl returns the class name and
2560 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002561 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002562
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002563 if (isa<UsingDirectiveDecl>(D))
2564 return createCXString("");
2565
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002566 llvm::SmallString<1024> S;
2567 llvm::raw_svector_ostream os(S);
2568 ND->printName(os);
2569
2570 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002571}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002572
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002573CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002574 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002575 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002576
Steve Narofff334b4e2009-09-02 18:26:48 +00002577 if (clang_isReference(C.kind)) {
2578 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002579 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002580 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002581 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002582 }
2583 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002584 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002585 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002586 }
2587 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002588 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002589 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002590 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002591 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002592 case CXCursor_CXXBaseSpecifier: {
2593 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2594 return createCXString(B->getType().getAsString());
2595 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002596 case CXCursor_TypeRef: {
2597 TypeDecl *Type = getCursorTypeRef(C).first;
2598 assert(Type && "Missing type decl");
2599
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002600 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2601 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002602 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002603 case CXCursor_TemplateRef: {
2604 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002605 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002606
2607 return createCXString(Template->getNameAsString());
2608 }
Douglas Gregor69319002010-08-31 23:48:11 +00002609
2610 case CXCursor_NamespaceRef: {
2611 NamedDecl *NS = getCursorNamespaceRef(C).first;
2612 assert(NS && "Missing namespace decl");
2613
2614 return createCXString(NS->getNameAsString());
2615 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002616
Douglas Gregora67e03f2010-09-09 21:42:20 +00002617 case CXCursor_MemberRef: {
2618 FieldDecl *Field = getCursorMemberRef(C).first;
2619 assert(Field && "Missing member decl");
2620
2621 return createCXString(Field->getNameAsString());
2622 }
2623
Douglas Gregor36897b02010-09-10 00:22:18 +00002624 case CXCursor_LabelRef: {
2625 LabelStmt *Label = getCursorLabelRef(C).first;
2626 assert(Label && "Missing label");
2627
2628 return createCXString(Label->getID()->getName());
2629 }
2630
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002631 case CXCursor_OverloadedDeclRef: {
2632 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2633 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2634 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2635 return createCXString(ND->getNameAsString());
2636 return createCXString("");
2637 }
2638 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2639 return createCXString(E->getName().getAsString());
2640 OverloadedTemplateStorage *Ovl
2641 = Storage.get<OverloadedTemplateStorage*>();
2642 if (Ovl->size() == 0)
2643 return createCXString("");
2644 return createCXString((*Ovl->begin())->getNameAsString());
2645 }
2646
Daniel Dunbaracca7252009-11-30 20:42:49 +00002647 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002648 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002649 }
2650 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002651
2652 if (clang_isExpression(C.kind)) {
2653 Decl *D = getDeclFromExpr(getCursorExpr(C));
2654 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002655 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002656 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002657 }
2658
Douglas Gregor36897b02010-09-10 00:22:18 +00002659 if (clang_isStatement(C.kind)) {
2660 Stmt *S = getCursorStmt(C);
2661 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2662 return createCXString(Label->getID()->getName());
2663
2664 return createCXString("");
2665 }
2666
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002667 if (C.kind == CXCursor_MacroInstantiation)
2668 return createCXString(getCursorMacroInstantiation(C)->getName()
2669 ->getNameStart());
2670
Douglas Gregor572feb22010-03-18 18:04:21 +00002671 if (C.kind == CXCursor_MacroDefinition)
2672 return createCXString(getCursorMacroDefinition(C)->getName()
2673 ->getNameStart());
2674
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002675 if (clang_isDeclaration(C.kind))
2676 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002677
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002678 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002679}
2680
Ted Kremeneke68fff62010-02-17 00:41:32 +00002681CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002682 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002683 case CXCursor_FunctionDecl:
2684 return createCXString("FunctionDecl");
2685 case CXCursor_TypedefDecl:
2686 return createCXString("TypedefDecl");
2687 case CXCursor_EnumDecl:
2688 return createCXString("EnumDecl");
2689 case CXCursor_EnumConstantDecl:
2690 return createCXString("EnumConstantDecl");
2691 case CXCursor_StructDecl:
2692 return createCXString("StructDecl");
2693 case CXCursor_UnionDecl:
2694 return createCXString("UnionDecl");
2695 case CXCursor_ClassDecl:
2696 return createCXString("ClassDecl");
2697 case CXCursor_FieldDecl:
2698 return createCXString("FieldDecl");
2699 case CXCursor_VarDecl:
2700 return createCXString("VarDecl");
2701 case CXCursor_ParmDecl:
2702 return createCXString("ParmDecl");
2703 case CXCursor_ObjCInterfaceDecl:
2704 return createCXString("ObjCInterfaceDecl");
2705 case CXCursor_ObjCCategoryDecl:
2706 return createCXString("ObjCCategoryDecl");
2707 case CXCursor_ObjCProtocolDecl:
2708 return createCXString("ObjCProtocolDecl");
2709 case CXCursor_ObjCPropertyDecl:
2710 return createCXString("ObjCPropertyDecl");
2711 case CXCursor_ObjCIvarDecl:
2712 return createCXString("ObjCIvarDecl");
2713 case CXCursor_ObjCInstanceMethodDecl:
2714 return createCXString("ObjCInstanceMethodDecl");
2715 case CXCursor_ObjCClassMethodDecl:
2716 return createCXString("ObjCClassMethodDecl");
2717 case CXCursor_ObjCImplementationDecl:
2718 return createCXString("ObjCImplementationDecl");
2719 case CXCursor_ObjCCategoryImplDecl:
2720 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002721 case CXCursor_CXXMethod:
2722 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002723 case CXCursor_UnexposedDecl:
2724 return createCXString("UnexposedDecl");
2725 case CXCursor_ObjCSuperClassRef:
2726 return createCXString("ObjCSuperClassRef");
2727 case CXCursor_ObjCProtocolRef:
2728 return createCXString("ObjCProtocolRef");
2729 case CXCursor_ObjCClassRef:
2730 return createCXString("ObjCClassRef");
2731 case CXCursor_TypeRef:
2732 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002733 case CXCursor_TemplateRef:
2734 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002735 case CXCursor_NamespaceRef:
2736 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002737 case CXCursor_MemberRef:
2738 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002739 case CXCursor_LabelRef:
2740 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002741 case CXCursor_OverloadedDeclRef:
2742 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002743 case CXCursor_UnexposedExpr:
2744 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002745 case CXCursor_BlockExpr:
2746 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002747 case CXCursor_DeclRefExpr:
2748 return createCXString("DeclRefExpr");
2749 case CXCursor_MemberRefExpr:
2750 return createCXString("MemberRefExpr");
2751 case CXCursor_CallExpr:
2752 return createCXString("CallExpr");
2753 case CXCursor_ObjCMessageExpr:
2754 return createCXString("ObjCMessageExpr");
2755 case CXCursor_UnexposedStmt:
2756 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002757 case CXCursor_LabelStmt:
2758 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002759 case CXCursor_InvalidFile:
2760 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002761 case CXCursor_InvalidCode:
2762 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002763 case CXCursor_NoDeclFound:
2764 return createCXString("NoDeclFound");
2765 case CXCursor_NotImplemented:
2766 return createCXString("NotImplemented");
2767 case CXCursor_TranslationUnit:
2768 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002769 case CXCursor_UnexposedAttr:
2770 return createCXString("UnexposedAttr");
2771 case CXCursor_IBActionAttr:
2772 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002773 case CXCursor_IBOutletAttr:
2774 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002775 case CXCursor_IBOutletCollectionAttr:
2776 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002777 case CXCursor_PreprocessingDirective:
2778 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002779 case CXCursor_MacroDefinition:
2780 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002781 case CXCursor_MacroInstantiation:
2782 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002783 case CXCursor_Namespace:
2784 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002785 case CXCursor_LinkageSpec:
2786 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002787 case CXCursor_CXXBaseSpecifier:
2788 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002789 case CXCursor_Constructor:
2790 return createCXString("CXXConstructor");
2791 case CXCursor_Destructor:
2792 return createCXString("CXXDestructor");
2793 case CXCursor_ConversionFunction:
2794 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002795 case CXCursor_TemplateTypeParameter:
2796 return createCXString("TemplateTypeParameter");
2797 case CXCursor_NonTypeTemplateParameter:
2798 return createCXString("NonTypeTemplateParameter");
2799 case CXCursor_TemplateTemplateParameter:
2800 return createCXString("TemplateTemplateParameter");
2801 case CXCursor_FunctionTemplate:
2802 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002803 case CXCursor_ClassTemplate:
2804 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002805 case CXCursor_ClassTemplatePartialSpecialization:
2806 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002807 case CXCursor_NamespaceAlias:
2808 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002809 case CXCursor_UsingDirective:
2810 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002811 case CXCursor_UsingDeclaration:
2812 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002813 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002814
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002815 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002816 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002817}
Steve Naroff89922f82009-08-31 00:59:03 +00002818
Ted Kremeneke68fff62010-02-17 00:41:32 +00002819enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2820 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002821 CXClientData client_data) {
2822 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2823 *BestCursor = cursor;
2824 return CXChildVisit_Recurse;
2825}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002826
Douglas Gregorb9790342010-01-22 21:44:22 +00002827CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2828 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002829 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002830
Douglas Gregorb9790342010-01-22 21:44:22 +00002831 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002832 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2833
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002834 // Translate the given source location to make it point at the beginning of
2835 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002836 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002837
2838 // Guard against an invalid SourceLocation, or we may assert in one
2839 // of the following calls.
2840 if (SLoc.isInvalid())
2841 return clang_getNullCursor();
2842
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002843 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2844 CXXUnit->getASTContext().getLangOptions());
2845
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002846 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2847 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002848 // FIXME: Would be great to have a "hint" cursor, then walk from that
2849 // hint cursor upward until we find a cursor whose source range encloses
2850 // the region of interest, rather than starting from the translation unit.
2851 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002852 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002853 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002854 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002855 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002856 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002857}
2858
Ted Kremenek73885552009-11-17 19:28:59 +00002859CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002860 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002861}
2862
2863unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002864 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002865}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002866
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002867unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002868 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2869}
2870
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002871unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002872 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2873}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002874
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002875unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002876 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2877}
2878
Douglas Gregor97b98722010-01-19 23:20:36 +00002879unsigned clang_isExpression(enum CXCursorKind K) {
2880 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2881}
2882
2883unsigned clang_isStatement(enum CXCursorKind K) {
2884 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2885}
2886
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002887unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2888 return K == CXCursor_TranslationUnit;
2889}
2890
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002891unsigned clang_isPreprocessing(enum CXCursorKind K) {
2892 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2893}
2894
Ted Kremenekad6eff62010-03-08 21:17:29 +00002895unsigned clang_isUnexposed(enum CXCursorKind K) {
2896 switch (K) {
2897 case CXCursor_UnexposedDecl:
2898 case CXCursor_UnexposedExpr:
2899 case CXCursor_UnexposedStmt:
2900 case CXCursor_UnexposedAttr:
2901 return true;
2902 default:
2903 return false;
2904 }
2905}
2906
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002907CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002908 return C.kind;
2909}
2910
Douglas Gregor98258af2010-01-18 22:46:11 +00002911CXSourceLocation clang_getCursorLocation(CXCursor C) {
2912 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002913 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002914 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002915 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2916 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002917 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002918 }
2919
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002920 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002921 std::pair<ObjCProtocolDecl *, SourceLocation> P
2922 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002923 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002924 }
2925
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002926 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002927 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2928 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002929 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002930 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002931
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002932 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002933 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002934 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002935 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002936
2937 case CXCursor_TemplateRef: {
2938 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2939 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2940 }
2941
Douglas Gregor69319002010-08-31 23:48:11 +00002942 case CXCursor_NamespaceRef: {
2943 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2944 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2945 }
2946
Douglas Gregora67e03f2010-09-09 21:42:20 +00002947 case CXCursor_MemberRef: {
2948 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2949 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2950 }
2951
Ted Kremenek3064ef92010-08-27 21:34:58 +00002952 case CXCursor_CXXBaseSpecifier: {
2953 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2954 return clang_getNullLocation();
2955 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002956
Douglas Gregor36897b02010-09-10 00:22:18 +00002957 case CXCursor_LabelRef: {
2958 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
2959 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
2960 }
2961
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002962 case CXCursor_OverloadedDeclRef:
2963 return cxloc::translateSourceLocation(getCursorContext(C),
2964 getCursorOverloadedDeclRef(C).second);
2965
Douglas Gregorf46034a2010-01-18 23:41:10 +00002966 default:
2967 // FIXME: Need a way to enumerate all non-reference cases.
2968 llvm_unreachable("Missed a reference kind");
2969 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002970 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002971
2972 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002973 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002974 getLocationFromExpr(getCursorExpr(C)));
2975
Douglas Gregor36897b02010-09-10 00:22:18 +00002976 if (clang_isStatement(C.kind))
2977 return cxloc::translateSourceLocation(getCursorContext(C),
2978 getCursorStmt(C)->getLocStart());
2979
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002980 if (C.kind == CXCursor_PreprocessingDirective) {
2981 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2982 return cxloc::translateSourceLocation(getCursorContext(C), L);
2983 }
Douglas Gregor48072312010-03-18 15:23:44 +00002984
2985 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002986 SourceLocation L
2987 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002988 return cxloc::translateSourceLocation(getCursorContext(C), L);
2989 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002990
2991 if (C.kind == CXCursor_MacroDefinition) {
2992 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2993 return cxloc::translateSourceLocation(getCursorContext(C), L);
2994 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002995
Ted Kremenek9a700d22010-05-12 06:16:13 +00002996 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002997 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002998
Douglas Gregorf46034a2010-01-18 23:41:10 +00002999 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003000 SourceLocation Loc = D->getLocation();
3001 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3002 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003003 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003004}
Douglas Gregora7bde202010-01-19 00:34:46 +00003005
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003006} // end extern "C"
3007
3008static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003009 if (clang_isReference(C.kind)) {
3010 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003011 case CXCursor_ObjCSuperClassRef:
3012 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003013
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003014 case CXCursor_ObjCProtocolRef:
3015 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003016
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003017 case CXCursor_ObjCClassRef:
3018 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003019
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003020 case CXCursor_TypeRef:
3021 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003022
3023 case CXCursor_TemplateRef:
3024 return getCursorTemplateRef(C).second;
3025
Douglas Gregor69319002010-08-31 23:48:11 +00003026 case CXCursor_NamespaceRef:
3027 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003028
3029 case CXCursor_MemberRef:
3030 return getCursorMemberRef(C).second;
3031
Ted Kremenek3064ef92010-08-27 21:34:58 +00003032 case CXCursor_CXXBaseSpecifier:
3033 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
3034 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003035
Douglas Gregor36897b02010-09-10 00:22:18 +00003036 case CXCursor_LabelRef:
3037 return getCursorLabelRef(C).second;
3038
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003039 case CXCursor_OverloadedDeclRef:
3040 return getCursorOverloadedDeclRef(C).second;
3041
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003042 default:
3043 // FIXME: Need a way to enumerate all non-reference cases.
3044 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003045 }
3046 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003047
3048 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003049 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003050
3051 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003052 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003053
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003054 if (C.kind == CXCursor_PreprocessingDirective)
3055 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003056
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003057 if (C.kind == CXCursor_MacroInstantiation)
3058 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003059
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003060 if (C.kind == CXCursor_MacroDefinition)
3061 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003062
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003063 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
3064 return getCursorDecl(C)->getSourceRange();
3065
3066 return SourceRange();
3067}
3068
3069extern "C" {
3070
3071CXSourceRange clang_getCursorExtent(CXCursor C) {
3072 SourceRange R = getRawCursorExtent(C);
3073 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003074 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003075
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003076 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003077}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003078
3079CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003080 if (clang_isInvalid(C.kind))
3081 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003082
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003083 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003084 if (clang_isDeclaration(C.kind)) {
3085 Decl *D = getCursorDecl(C);
3086 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3087 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3088 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3089 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3090 if (ObjCForwardProtocolDecl *Protocols
3091 = dyn_cast<ObjCForwardProtocolDecl>(D))
3092 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3093
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003094 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003095 }
3096
Douglas Gregor97b98722010-01-19 23:20:36 +00003097 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003098 Expr *E = getCursorExpr(C);
3099 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003100 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003101 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003102
3103 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3104 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3105
Douglas Gregor97b98722010-01-19 23:20:36 +00003106 return clang_getNullCursor();
3107 }
3108
Douglas Gregor36897b02010-09-10 00:22:18 +00003109 if (clang_isStatement(C.kind)) {
3110 Stmt *S = getCursorStmt(C);
3111 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3112 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3113 getCursorASTUnit(C));
3114
3115 return clang_getNullCursor();
3116 }
3117
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003118 if (C.kind == CXCursor_MacroInstantiation) {
3119 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3120 return MakeMacroDefinitionCursor(Def, CXXUnit);
3121 }
3122
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003123 if (!clang_isReference(C.kind))
3124 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003125
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003126 switch (C.kind) {
3127 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003128 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003129
3130 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003131 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003132
3133 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003134 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003135
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003136 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003137 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003138
3139 case CXCursor_TemplateRef:
3140 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3141
Douglas Gregor69319002010-08-31 23:48:11 +00003142 case CXCursor_NamespaceRef:
3143 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3144
Douglas Gregora67e03f2010-09-09 21:42:20 +00003145 case CXCursor_MemberRef:
3146 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3147
Ted Kremenek3064ef92010-08-27 21:34:58 +00003148 case CXCursor_CXXBaseSpecifier: {
3149 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3150 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3151 CXXUnit));
3152 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003153
Douglas Gregor36897b02010-09-10 00:22:18 +00003154 case CXCursor_LabelRef:
3155 // FIXME: We end up faking the "parent" declaration here because we
3156 // don't want to make CXCursor larger.
3157 return MakeCXCursor(getCursorLabelRef(C).first,
3158 CXXUnit->getASTContext().getTranslationUnitDecl(),
3159 CXXUnit);
3160
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003161 case CXCursor_OverloadedDeclRef:
3162 return C;
3163
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003164 default:
3165 // We would prefer to enumerate all non-reference cursor kinds here.
3166 llvm_unreachable("Unhandled reference cursor kind");
3167 break;
3168 }
3169 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003170
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003171 return clang_getNullCursor();
3172}
3173
Douglas Gregorb6998662010-01-19 19:34:47 +00003174CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003175 if (clang_isInvalid(C.kind))
3176 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003177
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003178 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003179
Douglas Gregorb6998662010-01-19 19:34:47 +00003180 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003181 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003182 C = clang_getCursorReferenced(C);
3183 WasReference = true;
3184 }
3185
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003186 if (C.kind == CXCursor_MacroInstantiation)
3187 return clang_getCursorReferenced(C);
3188
Douglas Gregorb6998662010-01-19 19:34:47 +00003189 if (!clang_isDeclaration(C.kind))
3190 return clang_getNullCursor();
3191
3192 Decl *D = getCursorDecl(C);
3193 if (!D)
3194 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003195
Douglas Gregorb6998662010-01-19 19:34:47 +00003196 switch (D->getKind()) {
3197 // Declaration kinds that don't really separate the notions of
3198 // declaration and definition.
3199 case Decl::Namespace:
3200 case Decl::Typedef:
3201 case Decl::TemplateTypeParm:
3202 case Decl::EnumConstant:
3203 case Decl::Field:
3204 case Decl::ObjCIvar:
3205 case Decl::ObjCAtDefsField:
3206 case Decl::ImplicitParam:
3207 case Decl::ParmVar:
3208 case Decl::NonTypeTemplateParm:
3209 case Decl::TemplateTemplateParm:
3210 case Decl::ObjCCategoryImpl:
3211 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003212 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003213 case Decl::LinkageSpec:
3214 case Decl::ObjCPropertyImpl:
3215 case Decl::FileScopeAsm:
3216 case Decl::StaticAssert:
3217 case Decl::Block:
3218 return C;
3219
3220 // Declaration kinds that don't make any sense here, but are
3221 // nonetheless harmless.
3222 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003223 break;
3224
3225 // Declaration kinds for which the definition is not resolvable.
3226 case Decl::UnresolvedUsingTypename:
3227 case Decl::UnresolvedUsingValue:
3228 break;
3229
3230 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003231 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3232 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003233
3234 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003235 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003236
3237 case Decl::Enum:
3238 case Decl::Record:
3239 case Decl::CXXRecord:
3240 case Decl::ClassTemplateSpecialization:
3241 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003242 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003243 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003244 return clang_getNullCursor();
3245
3246 case Decl::Function:
3247 case Decl::CXXMethod:
3248 case Decl::CXXConstructor:
3249 case Decl::CXXDestructor:
3250 case Decl::CXXConversion: {
3251 const FunctionDecl *Def = 0;
3252 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003253 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003254 return clang_getNullCursor();
3255 }
3256
3257 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003258 // Ask the variable if it has a definition.
3259 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3260 return MakeCXCursor(Def, CXXUnit);
3261 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003262 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003263
Douglas Gregorb6998662010-01-19 19:34:47 +00003264 case Decl::FunctionTemplate: {
3265 const FunctionDecl *Def = 0;
3266 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003267 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003268 return clang_getNullCursor();
3269 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003270
Douglas Gregorb6998662010-01-19 19:34:47 +00003271 case Decl::ClassTemplate: {
3272 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003273 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003274 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003275 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003276 return clang_getNullCursor();
3277 }
3278
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003279 case Decl::Using:
3280 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3281 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003282
3283 case Decl::UsingShadow:
3284 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003285 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003286 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003287
3288 case Decl::ObjCMethod: {
3289 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3290 if (Method->isThisDeclarationADefinition())
3291 return C;
3292
3293 // Dig out the method definition in the associated
3294 // @implementation, if we have it.
3295 // FIXME: The ASTs should make finding the definition easier.
3296 if (ObjCInterfaceDecl *Class
3297 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3298 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3299 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3300 Method->isInstanceMethod()))
3301 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003302 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003303
3304 return clang_getNullCursor();
3305 }
3306
3307 case Decl::ObjCCategory:
3308 if (ObjCCategoryImplDecl *Impl
3309 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003310 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003311 return clang_getNullCursor();
3312
3313 case Decl::ObjCProtocol:
3314 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3315 return C;
3316 return clang_getNullCursor();
3317
3318 case Decl::ObjCInterface:
3319 // There are two notions of a "definition" for an Objective-C
3320 // class: the interface and its implementation. When we resolved a
3321 // reference to an Objective-C class, produce the @interface as
3322 // the definition; when we were provided with the interface,
3323 // produce the @implementation as the definition.
3324 if (WasReference) {
3325 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3326 return C;
3327 } else if (ObjCImplementationDecl *Impl
3328 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003329 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003330 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003331
Douglas Gregorb6998662010-01-19 19:34:47 +00003332 case Decl::ObjCProperty:
3333 // FIXME: We don't really know where to find the
3334 // ObjCPropertyImplDecls that implement this property.
3335 return clang_getNullCursor();
3336
3337 case Decl::ObjCCompatibleAlias:
3338 if (ObjCInterfaceDecl *Class
3339 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3340 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003341 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003342
Douglas Gregorb6998662010-01-19 19:34:47 +00003343 return clang_getNullCursor();
3344
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003345 case Decl::ObjCForwardProtocol:
3346 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3347 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003348
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003349 case Decl::ObjCClass:
3350 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3351 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003352
3353 case Decl::Friend:
3354 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003355 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003356 return clang_getNullCursor();
3357
3358 case Decl::FriendTemplate:
3359 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003360 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003361 return clang_getNullCursor();
3362 }
3363
3364 return clang_getNullCursor();
3365}
3366
3367unsigned clang_isCursorDefinition(CXCursor C) {
3368 if (!clang_isDeclaration(C.kind))
3369 return 0;
3370
3371 return clang_getCursorDefinition(C) == C;
3372}
3373
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003374unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003375 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003376 return 0;
3377
3378 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3379 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3380 return E->getNumDecls();
3381
3382 if (OverloadedTemplateStorage *S
3383 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3384 return S->size();
3385
3386 Decl *D = Storage.get<Decl*>();
3387 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3388 return Using->getNumShadowDecls();
3389 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3390 return Classes->size();
3391 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3392 return Protocols->protocol_size();
3393
3394 return 0;
3395}
3396
3397CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003398 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003399 return clang_getNullCursor();
3400
3401 if (index >= clang_getNumOverloadedDecls(cursor))
3402 return clang_getNullCursor();
3403
3404 ASTUnit *Unit = getCursorASTUnit(cursor);
3405 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3406 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3407 return MakeCXCursor(E->decls_begin()[index], Unit);
3408
3409 if (OverloadedTemplateStorage *S
3410 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3411 return MakeCXCursor(S->begin()[index], Unit);
3412
3413 Decl *D = Storage.get<Decl*>();
3414 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3415 // FIXME: This is, unfortunately, linear time.
3416 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3417 std::advance(Pos, index);
3418 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3419 }
3420
3421 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3422 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3423
3424 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3425 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3426
3427 return clang_getNullCursor();
3428}
3429
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003430void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003431 const char **startBuf,
3432 const char **endBuf,
3433 unsigned *startLine,
3434 unsigned *startColumn,
3435 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003436 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003437 assert(getCursorDecl(C) && "CXCursor has null decl");
3438 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003439 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3440 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003441
Steve Naroff4ade6d62009-09-23 17:52:52 +00003442 SourceManager &SM = FD->getASTContext().getSourceManager();
3443 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3444 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3445 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3446 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3447 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3448 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3449}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003450
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003451void clang_enableStackTraces(void) {
3452 llvm::sys::PrintStackTraceOnErrorSignal();
3453}
3454
Ted Kremenekfb480492010-01-13 21:46:36 +00003455} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003456
Ted Kremenekfb480492010-01-13 21:46:36 +00003457//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003458// Token-based Operations.
3459//===----------------------------------------------------------------------===//
3460
3461/* CXToken layout:
3462 * int_data[0]: a CXTokenKind
3463 * int_data[1]: starting token location
3464 * int_data[2]: token length
3465 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003466 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003467 * otherwise unused.
3468 */
3469extern "C" {
3470
3471CXTokenKind clang_getTokenKind(CXToken CXTok) {
3472 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3473}
3474
3475CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3476 switch (clang_getTokenKind(CXTok)) {
3477 case CXToken_Identifier:
3478 case CXToken_Keyword:
3479 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003480 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3481 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003482
3483 case CXToken_Literal: {
3484 // We have stashed the starting pointer in the ptr_data field. Use it.
3485 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003486 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003487 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003488
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003489 case CXToken_Punctuation:
3490 case CXToken_Comment:
3491 break;
3492 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003493
3494 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003495 // deconstructing the source location.
3496 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3497 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003498 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003499
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003500 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3501 std::pair<FileID, unsigned> LocInfo
3502 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003503 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003504 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003505 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3506 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003507 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003508
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003509 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003510}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003511
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003512CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3513 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3514 if (!CXXUnit)
3515 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003516
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003517 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3518 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3519}
3520
3521CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3522 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003523 if (!CXXUnit)
3524 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003525
3526 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003527 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3528}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003529
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003530void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3531 CXToken **Tokens, unsigned *NumTokens) {
3532 if (Tokens)
3533 *Tokens = 0;
3534 if (NumTokens)
3535 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003536
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003537 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3538 if (!CXXUnit || !Tokens || !NumTokens)
3539 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003540
Douglas Gregorbdf60622010-03-05 21:16:25 +00003541 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3542
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003543 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003544 if (R.isInvalid())
3545 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003546
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003547 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3548 std::pair<FileID, unsigned> BeginLocInfo
3549 = SourceMgr.getDecomposedLoc(R.getBegin());
3550 std::pair<FileID, unsigned> EndLocInfo
3551 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003552
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003553 // Cannot tokenize across files.
3554 if (BeginLocInfo.first != EndLocInfo.first)
3555 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003556
3557 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003558 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003559 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003560 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003561 if (Invalid)
3562 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003563
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003564 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3565 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003566 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003567 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003568
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003569 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003570 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003571 llvm::SmallVector<CXToken, 32> CXTokens;
3572 Token Tok;
3573 do {
3574 // Lex the next token
3575 Lex.LexFromRawLexer(Tok);
3576 if (Tok.is(tok::eof))
3577 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003578
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003579 // Initialize the CXToken.
3580 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003581
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003582 // - Common fields
3583 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3584 CXTok.int_data[2] = Tok.getLength();
3585 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003586
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003587 // - Kind-specific fields
3588 if (Tok.isLiteral()) {
3589 CXTok.int_data[0] = CXToken_Literal;
3590 CXTok.ptr_data = (void *)Tok.getLiteralData();
3591 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003592 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003593 std::pair<FileID, unsigned> LocInfo
3594 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003595 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003596 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003597 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3598 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003599 return;
3600
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003601 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003602 IdentifierInfo *II
3603 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003604
3605 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3606 CXTok.int_data[0] = CXToken_Keyword;
3607 }
3608 else {
3609 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3610 CXToken_Identifier
3611 : CXToken_Keyword;
3612 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003613 CXTok.ptr_data = II;
3614 } else if (Tok.is(tok::comment)) {
3615 CXTok.int_data[0] = CXToken_Comment;
3616 CXTok.ptr_data = 0;
3617 } else {
3618 CXTok.int_data[0] = CXToken_Punctuation;
3619 CXTok.ptr_data = 0;
3620 }
3621 CXTokens.push_back(CXTok);
3622 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003623
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003624 if (CXTokens.empty())
3625 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003626
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003627 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3628 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3629 *NumTokens = CXTokens.size();
3630}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003631
Ted Kremenek6db61092010-05-05 00:55:15 +00003632void clang_disposeTokens(CXTranslationUnit TU,
3633 CXToken *Tokens, unsigned NumTokens) {
3634 free(Tokens);
3635}
3636
3637} // end: extern "C"
3638
3639//===----------------------------------------------------------------------===//
3640// Token annotation APIs.
3641//===----------------------------------------------------------------------===//
3642
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003643typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003644static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3645 CXCursor parent,
3646 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003647namespace {
3648class AnnotateTokensWorker {
3649 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003650 CXToken *Tokens;
3651 CXCursor *Cursors;
3652 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003653 unsigned TokIdx;
3654 CursorVisitor AnnotateVis;
3655 SourceManager &SrcMgr;
3656
3657 bool MoreTokens() const { return TokIdx < NumTokens; }
3658 unsigned NextToken() const { return TokIdx; }
3659 void AdvanceToken() { ++TokIdx; }
3660 SourceLocation GetTokenLoc(unsigned tokI) {
3661 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3662 }
3663
Ted Kremenek6db61092010-05-05 00:55:15 +00003664public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003665 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003666 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3667 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003668 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003669 NumTokens(numTokens), TokIdx(0),
3670 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3671 Decl::MaxPCHLevel, RegionOfInterest),
3672 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003673
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003674 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003675 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003676 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003677};
3678}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003679
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003680void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3681 // Walk the AST within the region of interest, annotating tokens
3682 // along the way.
3683 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003684
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003685 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3686 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3687 if (Pos != Annotated.end())
3688 Cursors[I] = Pos->second;
3689 }
3690
3691 // Finish up annotating any tokens left.
3692 if (!MoreTokens())
3693 return;
3694
3695 const CXCursor &C = clang_getNullCursor();
3696 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3697 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3698 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003699 }
3700}
3701
Ted Kremenek6db61092010-05-05 00:55:15 +00003702enum CXChildVisitResult
3703AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003704 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3705 // We can always annotate a preprocessing directive/macro instantiation.
3706 if (clang_isPreprocessing(cursor.kind)) {
3707 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003708 return CXChildVisit_Recurse;
3709 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003710
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003711 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003712
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003713 if (cursorRange.isInvalid())
3714 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003715
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003716 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3717
Ted Kremeneka333c662010-05-12 05:29:33 +00003718 // Adjust the annotated range based specific declarations.
3719 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3720 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003721 Decl *D = cxcursor::getCursorDecl(cursor);
3722 // Don't visit synthesized ObjC methods, since they have no syntatic
3723 // representation in the source.
3724 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3725 if (MD->isSynthesized())
3726 return CXChildVisit_Continue;
3727 }
3728 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003729 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3730 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003731 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003732 if (TLoc.isValid() &&
3733 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003734 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003735 }
3736 }
3737 }
3738
Ted Kremenek3f404602010-08-14 01:14:06 +00003739 // If the location of the cursor occurs within a macro instantiation, record
3740 // the spelling location of the cursor in our annotation map. We can then
3741 // paper over the token labelings during a post-processing step to try and
3742 // get cursor mappings for tokens that are the *arguments* of a macro
3743 // instantiation.
3744 if (L.isMacroID()) {
3745 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3746 // Only invalidate the old annotation if it isn't part of a preprocessing
3747 // directive. Here we assume that the default construction of CXCursor
3748 // results in CXCursor.kind being an initialized value (i.e., 0). If
3749 // this isn't the case, we can fix by doing lookup + insertion.
3750
3751 CXCursor &oldC = Annotated[rawEncoding];
3752 if (!clang_isPreprocessing(oldC.kind))
3753 oldC = cursor;
3754 }
3755
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003756 const enum CXCursorKind K = clang_getCursorKind(parent);
3757 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003758 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3759 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003760
3761 while (MoreTokens()) {
3762 const unsigned I = NextToken();
3763 SourceLocation TokLoc = GetTokenLoc(I);
3764 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3765 case RangeBefore:
3766 Cursors[I] = updateC;
3767 AdvanceToken();
3768 continue;
3769 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003770 case RangeOverlap:
3771 break;
3772 }
3773 break;
3774 }
3775
3776 // Visit children to get their cursor information.
3777 const unsigned BeforeChildren = NextToken();
3778 VisitChildren(cursor);
3779 const unsigned AfterChildren = NextToken();
3780
3781 // Adjust 'Last' to the last token within the extent of the cursor.
3782 while (MoreTokens()) {
3783 const unsigned I = NextToken();
3784 SourceLocation TokLoc = GetTokenLoc(I);
3785 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3786 case RangeBefore:
3787 assert(0 && "Infeasible");
3788 case RangeAfter:
3789 break;
3790 case RangeOverlap:
3791 Cursors[I] = updateC;
3792 AdvanceToken();
3793 continue;
3794 }
3795 break;
3796 }
3797 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003798
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003799 // Scan the tokens that are at the beginning of the cursor, but are not
3800 // capture by the child cursors.
3801
3802 // For AST elements within macros, rely on a post-annotate pass to
3803 // to correctly annotate the tokens with cursors. Otherwise we can
3804 // get confusing results of having tokens that map to cursors that really
3805 // are expanded by an instantiation.
3806 if (L.isMacroID())
3807 cursor = clang_getNullCursor();
3808
3809 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3810 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3811 break;
3812 Cursors[I] = cursor;
3813 }
3814 // Scan the tokens that are at the end of the cursor, but are not captured
3815 // but the child cursors.
3816 for (unsigned I = AfterChildren; I != Last; ++I)
3817 Cursors[I] = cursor;
3818
3819 TokIdx = Last;
3820 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003821}
3822
Ted Kremenek6db61092010-05-05 00:55:15 +00003823static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3824 CXCursor parent,
3825 CXClientData client_data) {
3826 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3827}
3828
3829extern "C" {
3830
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003831void clang_annotateTokens(CXTranslationUnit TU,
3832 CXToken *Tokens, unsigned NumTokens,
3833 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003834
3835 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003836 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003837
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003838 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003839 if (!CXXUnit) {
3840 // Any token we don't specifically annotate will have a NULL cursor.
3841 const CXCursor &C = clang_getNullCursor();
3842 for (unsigned I = 0; I != NumTokens; ++I)
3843 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003844 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003845 }
3846
Douglas Gregorbdf60622010-03-05 21:16:25 +00003847 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003848
Douglas Gregor0396f462010-03-19 05:22:59 +00003849 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003850 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003851 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3852 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003853 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3854 clang_getTokenLocation(TU,
3855 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003856
Douglas Gregor0396f462010-03-19 05:22:59 +00003857 // A mapping from the source locations found when re-lexing or traversing the
3858 // region of interest to the corresponding cursors.
3859 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003860
3861 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003862 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003863 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3864 std::pair<FileID, unsigned> BeginLocInfo
3865 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3866 std::pair<FileID, unsigned> EndLocInfo
3867 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003868
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003869 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003870 bool Invalid = false;
3871 if (BeginLocInfo.first == EndLocInfo.first &&
3872 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3873 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003874 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3875 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003876 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003877 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003878 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003879
3880 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003881 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003882 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003883 Token Tok;
3884 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003885
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003886 reprocess:
3887 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3888 // We have found a preprocessing directive. Gobble it up so that we
3889 // don't see it while preprocessing these tokens later, but keep track of
3890 // all of the token locations inside this preprocessing directive so that
3891 // we can annotate them appropriately.
3892 //
3893 // FIXME: Some simple tests here could identify macro definitions and
3894 // #undefs, to provide specific cursor kinds for those.
3895 std::vector<SourceLocation> Locations;
3896 do {
3897 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003898 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003899 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003900
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003901 using namespace cxcursor;
3902 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003903 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3904 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003905 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003906 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3907 Annotated[Locations[I].getRawEncoding()] = Cursor;
3908 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003909
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003910 if (Tok.isAtStartOfLine())
3911 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003912
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003913 continue;
3914 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003915
Douglas Gregor48072312010-03-18 15:23:44 +00003916 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003917 break;
3918 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003919 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003920
Douglas Gregor0396f462010-03-19 05:22:59 +00003921 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003922 // a specific cursor.
3923 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3924 CXXUnit, RegionOfInterest);
3925 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003926}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003927} // end: extern "C"
3928
3929//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003930// Operations for querying linkage of a cursor.
3931//===----------------------------------------------------------------------===//
3932
3933extern "C" {
3934CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003935 if (!clang_isDeclaration(cursor.kind))
3936 return CXLinkage_Invalid;
3937
Ted Kremenek16b42592010-03-03 06:36:57 +00003938 Decl *D = cxcursor::getCursorDecl(cursor);
3939 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3940 switch (ND->getLinkage()) {
3941 case NoLinkage: return CXLinkage_NoLinkage;
3942 case InternalLinkage: return CXLinkage_Internal;
3943 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3944 case ExternalLinkage: return CXLinkage_External;
3945 };
3946
3947 return CXLinkage_Invalid;
3948}
3949} // end: extern "C"
3950
3951//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003952// Operations for querying language of a cursor.
3953//===----------------------------------------------------------------------===//
3954
3955static CXLanguageKind getDeclLanguage(const Decl *D) {
3956 switch (D->getKind()) {
3957 default:
3958 break;
3959 case Decl::ImplicitParam:
3960 case Decl::ObjCAtDefsField:
3961 case Decl::ObjCCategory:
3962 case Decl::ObjCCategoryImpl:
3963 case Decl::ObjCClass:
3964 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003965 case Decl::ObjCForwardProtocol:
3966 case Decl::ObjCImplementation:
3967 case Decl::ObjCInterface:
3968 case Decl::ObjCIvar:
3969 case Decl::ObjCMethod:
3970 case Decl::ObjCProperty:
3971 case Decl::ObjCPropertyImpl:
3972 case Decl::ObjCProtocol:
3973 return CXLanguage_ObjC;
3974 case Decl::CXXConstructor:
3975 case Decl::CXXConversion:
3976 case Decl::CXXDestructor:
3977 case Decl::CXXMethod:
3978 case Decl::CXXRecord:
3979 case Decl::ClassTemplate:
3980 case Decl::ClassTemplatePartialSpecialization:
3981 case Decl::ClassTemplateSpecialization:
3982 case Decl::Friend:
3983 case Decl::FriendTemplate:
3984 case Decl::FunctionTemplate:
3985 case Decl::LinkageSpec:
3986 case Decl::Namespace:
3987 case Decl::NamespaceAlias:
3988 case Decl::NonTypeTemplateParm:
3989 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003990 case Decl::TemplateTemplateParm:
3991 case Decl::TemplateTypeParm:
3992 case Decl::UnresolvedUsingTypename:
3993 case Decl::UnresolvedUsingValue:
3994 case Decl::Using:
3995 case Decl::UsingDirective:
3996 case Decl::UsingShadow:
3997 return CXLanguage_CPlusPlus;
3998 }
3999
4000 return CXLanguage_C;
4001}
4002
4003extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004004
4005enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4006 if (clang_isDeclaration(cursor.kind))
4007 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4008 if (D->hasAttr<UnavailableAttr>() ||
4009 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4010 return CXAvailability_Available;
4011
4012 if (D->hasAttr<DeprecatedAttr>())
4013 return CXAvailability_Deprecated;
4014 }
4015
4016 return CXAvailability_Available;
4017}
4018
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004019CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4020 if (clang_isDeclaration(cursor.kind))
4021 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4022
4023 return CXLanguage_Invalid;
4024}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004025
4026CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4027 if (clang_isDeclaration(cursor.kind)) {
4028 if (Decl *D = getCursorDecl(cursor)) {
4029 DeclContext *DC = D->getDeclContext();
4030 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4031 }
4032 }
4033
4034 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4035 if (Decl *D = getCursorDecl(cursor))
4036 return MakeCXCursor(D, getCursorASTUnit(cursor));
4037 }
4038
4039 return clang_getNullCursor();
4040}
4041
4042CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4043 if (clang_isDeclaration(cursor.kind)) {
4044 if (Decl *D = getCursorDecl(cursor)) {
4045 DeclContext *DC = D->getLexicalDeclContext();
4046 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4047 }
4048 }
4049
4050 // FIXME: Note that we can't easily compute the lexical context of a
4051 // statement or expression, so we return nothing.
4052 return clang_getNullCursor();
4053}
4054
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004055} // end: extern "C"
4056
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004057
4058//===----------------------------------------------------------------------===//
4059// C++ AST instrospection.
4060//===----------------------------------------------------------------------===//
4061
4062extern "C" {
4063unsigned clang_CXXMethod_isStatic(CXCursor C) {
4064 if (!clang_isDeclaration(C.kind))
4065 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004066
4067 CXXMethodDecl *Method = 0;
4068 Decl *D = cxcursor::getCursorDecl(C);
4069 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4070 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4071 else
4072 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4073 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004074}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004075
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004076} // end: extern "C"
4077
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004078//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004079// Attribute introspection.
4080//===----------------------------------------------------------------------===//
4081
4082extern "C" {
4083CXType clang_getIBOutletCollectionType(CXCursor C) {
4084 if (C.kind != CXCursor_IBOutletCollectionAttr)
4085 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4086
4087 IBOutletCollectionAttr *A =
4088 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4089
4090 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4091}
4092} // end: extern "C"
4093
4094//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004095// CXString Operations.
4096//===----------------------------------------------------------------------===//
4097
4098extern "C" {
4099const char *clang_getCString(CXString string) {
4100 return string.Spelling;
4101}
4102
4103void clang_disposeString(CXString string) {
4104 if (string.MustFreeString && string.Spelling)
4105 free((void*)string.Spelling);
4106}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004107
Ted Kremenekfb480492010-01-13 21:46:36 +00004108} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004109
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004110namespace clang { namespace cxstring {
4111CXString createCXString(const char *String, bool DupString){
4112 CXString Str;
4113 if (DupString) {
4114 Str.Spelling = strdup(String);
4115 Str.MustFreeString = 1;
4116 } else {
4117 Str.Spelling = String;
4118 Str.MustFreeString = 0;
4119 }
4120 return Str;
4121}
4122
4123CXString createCXString(llvm::StringRef String, bool DupString) {
4124 CXString Result;
4125 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4126 char *Spelling = (char *)malloc(String.size() + 1);
4127 memmove(Spelling, String.data(), String.size());
4128 Spelling[String.size()] = 0;
4129 Result.Spelling = Spelling;
4130 Result.MustFreeString = 1;
4131 } else {
4132 Result.Spelling = String.data();
4133 Result.MustFreeString = 0;
4134 }
4135 return Result;
4136}
4137}}
4138
Ted Kremenek04bb7162010-01-22 22:44:15 +00004139//===----------------------------------------------------------------------===//
4140// Misc. utility functions.
4141//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004142
Ted Kremenek04bb7162010-01-22 22:44:15 +00004143extern "C" {
4144
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004145CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004146 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004147}
4148
4149} // end: extern "C"