blob: f4661ca20669e2a8c6193a7f58ca7aed860441fe [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/Version.h"
30#include "clang/Frontend/ASTUnit.h"
31#include "clang/Frontend/CompilerInstance.h"
32#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000039#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000040#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
David Blaikieea4395e2017-01-06 19:49:01 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
72 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000073 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000074 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000075 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000076 CXTranslationUnit D = new CXTranslationUnitImpl();
77 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000078 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000079 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000080 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000081 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000082 D->CommentToXML = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000083 return D;
84}
85
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000086bool cxtu::isASTReadError(ASTUnit *AU) {
87 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
88 DEnd = AU->stored_diag_end();
89 D != DEnd; ++D) {
90 if (D->getLevel() >= DiagnosticsEngine::Error &&
91 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
92 diag::DiagCat_AST_Deserialization_Issue)
93 return true;
94 }
95 return false;
96}
97
Guy Benyei11169dd2012-12-18 14:30:41 +000098cxtu::CXTUOwner::~CXTUOwner() {
99 if (TU)
100 clang_disposeTranslationUnit(TU);
101}
102
103/// \brief Compare two source ranges to determine their relative position in
104/// the translation unit.
105static RangeComparisonResult RangeCompare(SourceManager &SM,
106 SourceRange R1,
107 SourceRange R2) {
108 assert(R1.isValid() && "First range is invalid?");
109 assert(R2.isValid() && "Second range is invalid?");
110 if (R1.getEnd() != R2.getBegin() &&
111 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
112 return RangeBefore;
113 if (R2.getEnd() != R1.getBegin() &&
114 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
115 return RangeAfter;
116 return RangeOverlap;
117}
118
119/// \brief Determine if a source location falls within, before, or after a
120/// a given source range.
121static RangeComparisonResult LocationCompare(SourceManager &SM,
122 SourceLocation L, SourceRange R) {
123 assert(R.isValid() && "First range is invalid?");
124 assert(L.isValid() && "Second range is invalid?");
125 if (L == R.getBegin() || L == R.getEnd())
126 return RangeOverlap;
127 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
128 return RangeBefore;
129 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
130 return RangeAfter;
131 return RangeOverlap;
132}
133
134/// \brief Translate a Clang source range into a CIndex source range.
135///
136/// Clang internally represents ranges where the end location points to the
137/// start of the token at the end. However, for external clients it is more
138/// useful to have a CXSourceRange be a proper half-open interval. This routine
139/// does the appropriate translation.
140CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
141 const LangOptions &LangOpts,
142 const CharSourceRange &R) {
143 // We want the last character in this location, so we will adjust the
144 // location accordingly.
145 SourceLocation EndLoc = R.getEnd();
146 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
147 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000148 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000149 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
150 SM, LangOpts);
151 EndLoc = EndLoc.getLocWithOffset(Length);
152 }
153
Bill Wendlingeade3622013-01-23 08:25:41 +0000154 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000155 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000156 R.getBegin().getRawEncoding(),
157 EndLoc.getRawEncoding()
158 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000159 return Result;
160}
161
162//===----------------------------------------------------------------------===//
163// Cursor visitor.
164//===----------------------------------------------------------------------===//
165
166static SourceRange getRawCursorExtent(CXCursor C);
167static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
168
169
170RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
171 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
172}
173
174/// \brief Visit the given cursor and, if requested by the visitor,
175/// its children.
176///
177/// \param Cursor the cursor to visit.
178///
179/// \param CheckedRegionOfInterest if true, then the caller already checked
180/// that this cursor is within the region of interest.
181///
182/// \returns true if the visitation should be aborted, false if it
183/// should continue.
184bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
185 if (clang_isInvalid(Cursor.kind))
186 return false;
187
188 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000189 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000190 if (!D) {
191 assert(0 && "Invalid declaration cursor");
192 return true; // abort.
193 }
194
195 // Ignore implicit declarations, unless it's an objc method because
196 // currently we should report implicit methods for properties when indexing.
197 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
198 return false;
199 }
200
201 // If we have a range of interest, and this cursor doesn't intersect with it,
202 // we're done.
203 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
204 SourceRange Range = getRawCursorExtent(Cursor);
205 if (Range.isInvalid() || CompareRegionOfInterest(Range))
206 return false;
207 }
208
209 switch (Visitor(Cursor, Parent, ClientData)) {
210 case CXChildVisit_Break:
211 return true;
212
213 case CXChildVisit_Continue:
214 return false;
215
216 case CXChildVisit_Recurse: {
217 bool ret = VisitChildren(Cursor);
218 if (PostChildrenVisitor)
219 if (PostChildrenVisitor(Cursor, ClientData))
220 return true;
221 return ret;
222 }
223 }
224
225 llvm_unreachable("Invalid CXChildVisitResult!");
226}
227
228static bool visitPreprocessedEntitiesInRange(SourceRange R,
229 PreprocessingRecord &PPRec,
230 CursorVisitor &Visitor) {
231 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
232 FileID FID;
233
234 if (!Visitor.shouldVisitIncludedEntities()) {
235 // If the begin/end of the range lie in the same FileID, do the optimization
236 // where we skip preprocessed entities that do not come from the same FileID.
237 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
238 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
239 FID = FileID();
240 }
241
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000242 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
243 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000244 PPRec, FID);
245}
246
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000247bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000248 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000249 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000250
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000251 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000252 SourceManager &SM = Unit->getSourceManager();
253
254 std::pair<FileID, unsigned>
255 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
256 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
257
258 if (End.first != Begin.first) {
259 // If the end does not reside in the same file, try to recover by
260 // picking the end of the file of begin location.
261 End.first = Begin.first;
262 End.second = SM.getFileIDSize(Begin.first);
263 }
264
265 assert(Begin.first == End.first);
266 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000267 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000268
269 FileID File = Begin.first;
270 unsigned Offset = Begin.second;
271 unsigned Length = End.second - Begin.second;
272
273 if (!VisitDeclsOnly && !VisitPreprocessorLast)
274 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000275 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000276
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000277 if (visitDeclsFromFileRegion(File, Offset, Length))
278 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000279
280 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000281 return visitPreprocessedEntitiesInRegion();
282
283 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000284}
285
286static bool isInLexicalContext(Decl *D, DeclContext *DC) {
287 if (!DC)
288 return false;
289
290 for (DeclContext *DeclDC = D->getLexicalDeclContext();
291 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
292 if (DeclDC == DC)
293 return true;
294 }
295 return false;
296}
297
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000298bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000299 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000300 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000301 SourceManager &SM = Unit->getSourceManager();
302 SourceRange Range = RegionOfInterest;
303
304 SmallVector<Decl *, 16> Decls;
305 Unit->findFileRegionDecls(File, Offset, Length, Decls);
306
307 // If we didn't find any file level decls for the file, try looking at the
308 // file that it was included from.
309 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
310 bool Invalid = false;
311 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
312 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000313 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000314
315 SourceLocation Outer;
316 if (SLEntry.isFile())
317 Outer = SLEntry.getFile().getIncludeLoc();
318 else
319 Outer = SLEntry.getExpansion().getExpansionLocStart();
320 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000321 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000322
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000323 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000324 Length = 0;
325 Unit->findFileRegionDecls(File, Offset, Length, Decls);
326 }
327
328 assert(!Decls.empty());
329
330 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000331 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000332 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
333 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000334 Decl *D = *DIt;
335 if (D->getSourceRange().isInvalid())
336 continue;
337
338 if (isInLexicalContext(D, CurDC))
339 continue;
340
341 CurDC = dyn_cast<DeclContext>(D);
342
343 if (TagDecl *TD = dyn_cast<TagDecl>(D))
344 if (!TD->isFreeStanding())
345 continue;
346
347 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
348 if (CompRes == RangeBefore)
349 continue;
350 if (CompRes == RangeAfter)
351 break;
352
353 assert(CompRes == RangeOverlap);
354 VisitedAtLeastOnce = true;
355
356 if (isa<ObjCContainerDecl>(D)) {
357 FileDI_current = &DIt;
358 FileDE_current = DE;
359 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000360 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000361 }
362
363 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000364 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 }
366
367 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000368 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000369
370 // No Decls overlapped with the range. Move up the lexical context until there
371 // is a context that contains the range or we reach the translation unit
372 // level.
373 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
374 : (*(DIt-1))->getLexicalDeclContext();
375
376 while (DC && !DC->isTranslationUnit()) {
377 Decl *D = cast<Decl>(DC);
378 SourceRange CurDeclRange = D->getSourceRange();
379 if (CurDeclRange.isInvalid())
380 break;
381
382 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000383 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
384 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 }
386
387 DC = D->getLexicalDeclContext();
388 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000389
390 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000391}
392
393bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
394 if (!AU->getPreprocessor().getPreprocessingRecord())
395 return false;
396
397 PreprocessingRecord &PPRec
398 = *AU->getPreprocessor().getPreprocessingRecord();
399 SourceManager &SM = AU->getSourceManager();
400
401 if (RegionOfInterest.isValid()) {
402 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
403 SourceLocation B = MappedRange.getBegin();
404 SourceLocation E = MappedRange.getEnd();
405
406 if (AU->isInPreambleFileID(B)) {
407 if (SM.isLoadedSourceLocation(E))
408 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
409 PPRec, *this);
410
411 // Beginning of range lies in the preamble but it also extends beyond
412 // it into the main file. Split the range into 2 parts, one covering
413 // the preamble and another covering the main file. This allows subsequent
414 // calls to visitPreprocessedEntitiesInRange to accept a source range that
415 // lies in the same FileID, allowing it to skip preprocessed entities that
416 // do not come from the same FileID.
417 bool breaked =
418 visitPreprocessedEntitiesInRange(
419 SourceRange(B, AU->getEndOfPreambleFileID()),
420 PPRec, *this);
421 if (breaked) return true;
422 return visitPreprocessedEntitiesInRange(
423 SourceRange(AU->getStartOfMainFileID(), E),
424 PPRec, *this);
425 }
426
427 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
428 }
429
430 bool OnlyLocalDecls
431 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
432
433 if (OnlyLocalDecls)
434 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
435 PPRec);
436
437 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
438}
439
440template<typename InputIterator>
441bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
442 InputIterator Last,
443 PreprocessingRecord &PPRec,
444 FileID FID) {
445 for (; First != Last; ++First) {
446 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
447 continue;
448
449 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000450 if (!PPE)
451 continue;
452
Guy Benyei11169dd2012-12-18 14:30:41 +0000453 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
454 if (Visit(MakeMacroExpansionCursor(ME, TU)))
455 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000456
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 continue;
458 }
Richard Smith66a81862015-05-04 02:25:31 +0000459
460 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
462 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000463
Guy Benyei11169dd2012-12-18 14:30:41 +0000464 continue;
465 }
466
467 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
468 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
469 return true;
470
471 continue;
472 }
473 }
474
475 return false;
476}
477
478/// \brief Visit the children of the given cursor.
479///
480/// \returns true if the visitation should be aborted, false if it
481/// should continue.
482bool CursorVisitor::VisitChildren(CXCursor Cursor) {
483 if (clang_isReference(Cursor.kind) &&
484 Cursor.kind != CXCursor_CXXBaseSpecifier) {
485 // By definition, references have no children.
486 return false;
487 }
488
489 // Set the Parent field to Cursor, then back to its old value once we're
490 // done.
491 SetParentRAII SetParent(Parent, StmtParent, Cursor);
492
493 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000494 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000495 if (!D)
496 return false;
497
498 return VisitAttributes(D) || Visit(D);
499 }
500
501 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000502 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000503 return Visit(S);
504
505 return false;
506 }
507
508 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000509 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000510 return Visit(E);
511
512 return false;
513 }
514
515 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000516 CXTranslationUnit TU = getCursorTU(Cursor);
517 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000518
519 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
520 for (unsigned I = 0; I != 2; ++I) {
521 if (VisitOrder[I]) {
522 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
523 RegionOfInterest.isInvalid()) {
524 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
525 TLEnd = CXXUnit->top_level_end();
526 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000527 const Optional<bool> V = handleDeclForVisitation(*TL);
528 if (!V.hasValue())
529 continue;
530 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000531 }
532 } else if (VisitDeclContext(
533 CXXUnit->getASTContext().getTranslationUnitDecl()))
534 return true;
535 continue;
536 }
537
538 // Walk the preprocessing record.
539 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
540 visitPreprocessedEntitiesInRegion();
541 }
542
543 return false;
544 }
545
546 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000547 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
549 return Visit(BaseTSInfo->getTypeLoc());
550 }
551 }
552 }
553
554 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000555 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000557 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000558 return Visit(cxcursor::MakeCursorObjCClassRef(
559 ObjT->getInterface(),
560 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 }
562
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000563 // If pointing inside a macro definition, check if the token is an identifier
564 // that was ever defined as a macro. In such a case, create a "pseudo" macro
565 // expansion cursor for that token.
566 SourceLocation BeginLoc = RegionOfInterest.getBegin();
567 if (Cursor.kind == CXCursor_MacroDefinition &&
568 BeginLoc == RegionOfInterest.getEnd()) {
569 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000570 const MacroInfo *MI =
571 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000572 if (MacroDefinitionRecord *MacroDef =
573 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000574 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
575 }
576
Guy Benyei11169dd2012-12-18 14:30:41 +0000577 // Nothing to visit at the moment.
578 return false;
579}
580
581bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
582 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
583 if (Visit(TSInfo->getTypeLoc()))
584 return true;
585
586 if (Stmt *Body = B->getBody())
587 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
588
589 return false;
590}
591
Ted Kremenek03325582013-02-21 01:29:01 +0000592Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000593 if (RegionOfInterest.isValid()) {
594 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
595 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000596 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000597
598 switch (CompareRegionOfInterest(Range)) {
599 case RangeBefore:
600 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000601 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000602
603 case RangeAfter:
604 // This declaration comes after the region of interest; we're done.
605 return false;
606
607 case RangeOverlap:
608 // This declaration overlaps the region of interest; visit it.
609 break;
610 }
611 }
612 return true;
613}
614
615bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
616 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
617
618 // FIXME: Eventually remove. This part of a hack to support proper
619 // iteration over all Decls contained lexically within an ObjC container.
620 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
621 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
622
623 for ( ; I != E; ++I) {
624 Decl *D = *I;
625 if (D->getLexicalDeclContext() != DC)
626 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000627 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000628 if (!V.hasValue())
629 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000630 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000631 }
632 return false;
633}
634
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000635Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
636 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
637
638 // Ignore synthesized ivars here, otherwise if we have something like:
639 // @synthesize prop = _prop;
640 // and '_prop' is not declared, we will encounter a '_prop' ivar before
641 // encountering the 'prop' synthesize declaration and we will think that
642 // we passed the region-of-interest.
643 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
644 if (ivarD->getSynthesize())
645 return None;
646 }
647
648 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
649 // declarations is a mismatch with the compiler semantics.
650 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
651 auto *ID = cast<ObjCInterfaceDecl>(D);
652 if (!ID->isThisDeclarationADefinition())
653 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
654
655 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
656 auto *PD = cast<ObjCProtocolDecl>(D);
657 if (!PD->isThisDeclarationADefinition())
658 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
659 }
660
661 const Optional<bool> V = shouldVisitCursor(Cursor);
662 if (!V.hasValue())
663 return None;
664 if (!V.getValue())
665 return false;
666 if (Visit(Cursor, true))
667 return true;
668 return None;
669}
670
Guy Benyei11169dd2012-12-18 14:30:41 +0000671bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
672 llvm_unreachable("Translation units are visited directly by Visit()");
673}
674
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000675bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
676 if (VisitTemplateParameters(D->getTemplateParameters()))
677 return true;
678
679 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
680}
681
Guy Benyei11169dd2012-12-18 14:30:41 +0000682bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
683 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
684 return Visit(TSInfo->getTypeLoc());
685
686 return false;
687}
688
689bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
690 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
691 return Visit(TSInfo->getTypeLoc());
692
693 return false;
694}
695
696bool CursorVisitor::VisitTagDecl(TagDecl *D) {
697 return VisitDeclContext(D);
698}
699
700bool CursorVisitor::VisitClassTemplateSpecializationDecl(
701 ClassTemplateSpecializationDecl *D) {
702 bool ShouldVisitBody = false;
703 switch (D->getSpecializationKind()) {
704 case TSK_Undeclared:
705 case TSK_ImplicitInstantiation:
706 // Nothing to visit
707 return false;
708
709 case TSK_ExplicitInstantiationDeclaration:
710 case TSK_ExplicitInstantiationDefinition:
711 break;
712
713 case TSK_ExplicitSpecialization:
714 ShouldVisitBody = true;
715 break;
716 }
717
718 // Visit the template arguments used in the specialization.
719 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
720 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000721 if (TemplateSpecializationTypeLoc TSTLoc =
722 TL.getAs<TemplateSpecializationTypeLoc>()) {
723 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
724 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000725 return true;
726 }
727 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000728
729 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000730}
731
732bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
733 ClassTemplatePartialSpecializationDecl *D) {
734 // FIXME: Visit the "outer" template parameter lists on the TagDecl
735 // before visiting these template parameters.
736 if (VisitTemplateParameters(D->getTemplateParameters()))
737 return true;
738
739 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000740 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
741 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
742 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
744 return true;
745
746 return VisitCXXRecordDecl(D);
747}
748
749bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
750 // Visit the default argument.
751 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
752 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
753 if (Visit(DefArg->getTypeLoc()))
754 return true;
755
756 return false;
757}
758
759bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
760 if (Expr *Init = D->getInitExpr())
761 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
762 return false;
763}
764
765bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000766 unsigned NumParamList = DD->getNumTemplateParameterLists();
767 for (unsigned i = 0; i < NumParamList; i++) {
768 TemplateParameterList* Params = DD->getTemplateParameterList(i);
769 if (VisitTemplateParameters(Params))
770 return true;
771 }
772
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
774 if (Visit(TSInfo->getTypeLoc()))
775 return true;
776
777 // Visit the nested-name-specifier, if present.
778 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
779 if (VisitNestedNameSpecifierLoc(QualifierLoc))
780 return true;
781
782 return false;
783}
784
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000785/// \brief Compare two base or member initializers based on their source order.
786static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
787 CXXCtorInitializer *const *Y) {
788 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
789}
790
Guy Benyei11169dd2012-12-18 14:30:41 +0000791bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000792 unsigned NumParamList = ND->getNumTemplateParameterLists();
793 for (unsigned i = 0; i < NumParamList; i++) {
794 TemplateParameterList* Params = ND->getTemplateParameterList(i);
795 if (VisitTemplateParameters(Params))
796 return true;
797 }
798
Guy Benyei11169dd2012-12-18 14:30:41 +0000799 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
800 // Visit the function declaration's syntactic components in the order
801 // written. This requires a bit of work.
802 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000803 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000804
805 // If we have a function declared directly (without the use of a typedef),
806 // visit just the return type. Otherwise, just visit the function's type
807 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000808 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 (!FTL && Visit(TL)))
810 return true;
811
812 // Visit the nested-name-specifier, if present.
813 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
814 if (VisitNestedNameSpecifierLoc(QualifierLoc))
815 return true;
816
817 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000818 if (!isa<CXXDestructorDecl>(ND))
819 if (VisitDeclarationNameInfo(ND->getNameInfo()))
820 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000821
822 // FIXME: Visit explicitly-specified template arguments!
823
824 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000825 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 return true;
827
Bill Wendling44426052012-12-20 19:22:21 +0000828 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 }
830
831 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
832 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
833 // Find the initializers that were written in the source.
834 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000835 for (auto *I : Constructor->inits()) {
836 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 continue;
838
Aaron Ballman0ad78302014-03-13 17:34:31 +0000839 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 }
841
842 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000843 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
844 &CompareCXXCtorInitializers);
845
Guy Benyei11169dd2012-12-18 14:30:41 +0000846 // Visit the initializers in source order
847 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
848 CXXCtorInitializer *Init = WrittenInits[I];
849 if (Init->isAnyMemberInitializer()) {
850 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
851 Init->getMemberLocation(), TU)))
852 return true;
853 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
854 if (Visit(TInfo->getTypeLoc()))
855 return true;
856 }
857
858 // Visit the initializer value.
859 if (Expr *Initializer = Init->getInit())
860 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
861 return true;
862 }
863 }
864
865 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
866 return true;
867 }
868
869 return false;
870}
871
872bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
873 if (VisitDeclaratorDecl(D))
874 return true;
875
876 if (Expr *BitWidth = D->getBitWidth())
877 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
878
879 return false;
880}
881
882bool CursorVisitor::VisitVarDecl(VarDecl *D) {
883 if (VisitDeclaratorDecl(D))
884 return true;
885
886 if (Expr *Init = D->getInit())
887 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
888
889 return false;
890}
891
892bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
893 if (VisitDeclaratorDecl(D))
894 return true;
895
896 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
897 if (Expr *DefArg = D->getDefaultArgument())
898 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
899
900 return false;
901}
902
903bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
904 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
905 // before visiting these template parameters.
906 if (VisitTemplateParameters(D->getTemplateParameters()))
907 return true;
908
909 return VisitFunctionDecl(D->getTemplatedDecl());
910}
911
912bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
913 // FIXME: Visit the "outer" template parameter lists on the TagDecl
914 // before visiting these template parameters.
915 if (VisitTemplateParameters(D->getTemplateParameters()))
916 return true;
917
918 return VisitCXXRecordDecl(D->getTemplatedDecl());
919}
920
921bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
922 if (VisitTemplateParameters(D->getTemplateParameters()))
923 return true;
924
925 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
926 VisitTemplateArgumentLoc(D->getDefaultArgument()))
927 return true;
928
929 return false;
930}
931
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000932bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
933 // Visit the bound, if it's explicit.
934 if (D->hasExplicitBound()) {
935 if (auto TInfo = D->getTypeSourceInfo()) {
936 if (Visit(TInfo->getTypeLoc()))
937 return true;
938 }
939 }
940
941 return false;
942}
943
Guy Benyei11169dd2012-12-18 14:30:41 +0000944bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000945 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 if (Visit(TSInfo->getTypeLoc()))
947 return true;
948
David Majnemer59f77922016-06-24 04:05:48 +0000949 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000950 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 return true;
952 }
953
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000954 return ND->isThisDeclarationADefinition() &&
955 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000956}
957
958template <typename DeclIt>
959static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
960 SourceManager &SM, SourceLocation EndLoc,
961 SmallVectorImpl<Decl *> &Decls) {
962 DeclIt next = *DI_current;
963 while (++next != DE_current) {
964 Decl *D_next = *next;
965 if (!D_next)
966 break;
967 SourceLocation L = D_next->getLocStart();
968 if (!L.isValid())
969 break;
970 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
971 *DI_current = next;
972 Decls.push_back(D_next);
973 continue;
974 }
975 break;
976 }
977}
978
Guy Benyei11169dd2012-12-18 14:30:41 +0000979bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
980 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
981 // an @implementation can lexically contain Decls that are not properly
982 // nested in the AST. When we identify such cases, we need to retrofit
983 // this nesting here.
984 if (!DI_current && !FileDI_current)
985 return VisitDeclContext(D);
986
987 // Scan the Decls that immediately come after the container
988 // in the current DeclContext. If any fall within the
989 // container's lexical region, stash them into a vector
990 // for later processing.
991 SmallVector<Decl *, 24> DeclsInContainer;
992 SourceLocation EndLoc = D->getSourceRange().getEnd();
993 SourceManager &SM = AU->getSourceManager();
994 if (EndLoc.isValid()) {
995 if (DI_current) {
996 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
997 DeclsInContainer);
998 } else {
999 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1000 DeclsInContainer);
1001 }
1002 }
1003
1004 // The common case.
1005 if (DeclsInContainer.empty())
1006 return VisitDeclContext(D);
1007
1008 // Get all the Decls in the DeclContext, and sort them with the
1009 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001010 for (auto *SubDecl : D->decls()) {
1011 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1012 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001013 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001014 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 }
1016
1017 // Now sort the Decls so that they appear in lexical order.
1018 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001019 [&SM](Decl *A, Decl *B) {
1020 SourceLocation L_A = A->getLocStart();
1021 SourceLocation L_B = B->getLocStart();
1022 assert(L_A.isValid() && L_B.isValid());
1023 return SM.isBeforeInTranslationUnit(L_A, L_B);
1024 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001025
1026 // Now visit the decls.
1027 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1028 E = DeclsInContainer.end(); I != E; ++I) {
1029 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001030 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001031 if (!V.hasValue())
1032 continue;
1033 if (!V.getValue())
1034 return false;
1035 if (Visit(Cursor, true))
1036 return true;
1037 }
1038 return false;
1039}
1040
1041bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1042 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1043 TU)))
1044 return true;
1045
Douglas Gregore9d95f12015-07-07 03:57:35 +00001046 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1047 return true;
1048
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1050 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1051 E = ND->protocol_end(); I != E; ++I, ++PL)
1052 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1053 return true;
1054
1055 return VisitObjCContainerDecl(ND);
1056}
1057
1058bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1059 if (!PID->isThisDeclarationADefinition())
1060 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1061
1062 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1063 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1064 E = PID->protocol_end(); I != E; ++I, ++PL)
1065 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1066 return true;
1067
1068 return VisitObjCContainerDecl(PID);
1069}
1070
1071bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1072 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1073 return true;
1074
1075 // FIXME: This implements a workaround with @property declarations also being
1076 // installed in the DeclContext for the @interface. Eventually this code
1077 // should be removed.
1078 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1079 if (!CDecl || !CDecl->IsClassExtension())
1080 return false;
1081
1082 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1083 if (!ID)
1084 return false;
1085
1086 IdentifierInfo *PropertyId = PD->getIdentifier();
1087 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001088 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1089 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001090
1091 if (!prevDecl)
1092 return false;
1093
1094 // Visit synthesized methods since they will be skipped when visiting
1095 // the @interface.
1096 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1097 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1098 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1099 return true;
1100
1101 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1102 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1103 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1104 return true;
1105
1106 return false;
1107}
1108
Douglas Gregore9d95f12015-07-07 03:57:35 +00001109bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1110 if (!typeParamList)
1111 return false;
1112
1113 for (auto *typeParam : *typeParamList) {
1114 // Visit the type parameter.
1115 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1116 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001117 }
1118
1119 return false;
1120}
1121
Guy Benyei11169dd2012-12-18 14:30:41 +00001122bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1123 if (!D->isThisDeclarationADefinition()) {
1124 // Forward declaration is treated like a reference.
1125 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1126 }
1127
Douglas Gregore9d95f12015-07-07 03:57:35 +00001128 // Objective-C type parameters.
1129 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1130 return true;
1131
Guy Benyei11169dd2012-12-18 14:30:41 +00001132 // Issue callbacks for super class.
1133 if (D->getSuperClass() &&
1134 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1135 D->getSuperClassLoc(),
1136 TU)))
1137 return true;
1138
Douglas Gregore9d95f12015-07-07 03:57:35 +00001139 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1140 if (Visit(SuperClassTInfo->getTypeLoc()))
1141 return true;
1142
Guy Benyei11169dd2012-12-18 14:30:41 +00001143 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1144 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1145 E = D->protocol_end(); I != E; ++I, ++PL)
1146 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1147 return true;
1148
1149 return VisitObjCContainerDecl(D);
1150}
1151
1152bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1153 return VisitObjCContainerDecl(D);
1154}
1155
1156bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1157 // 'ID' could be null when dealing with invalid code.
1158 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1159 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1160 return true;
1161
1162 return VisitObjCImplDecl(D);
1163}
1164
1165bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1166#if 0
1167 // Issue callbacks for super class.
1168 // FIXME: No source location information!
1169 if (D->getSuperClass() &&
1170 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1171 D->getSuperClassLoc(),
1172 TU)))
1173 return true;
1174#endif
1175
1176 return VisitObjCImplDecl(D);
1177}
1178
1179bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1180 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1181 if (PD->isIvarNameSpecified())
1182 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1183
1184 return false;
1185}
1186
1187bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1188 return VisitDeclContext(D);
1189}
1190
1191bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1192 // Visit nested-name-specifier.
1193 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1194 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1195 return true;
1196
1197 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1198 D->getTargetNameLoc(), TU));
1199}
1200
1201bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1202 // Visit nested-name-specifier.
1203 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1204 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1205 return true;
1206 }
1207
1208 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1209 return true;
1210
1211 return VisitDeclarationNameInfo(D->getNameInfo());
1212}
1213
1214bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1215 // Visit nested-name-specifier.
1216 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1217 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1218 return true;
1219
1220 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1221 D->getIdentLocation(), TU));
1222}
1223
1224bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1225 // Visit nested-name-specifier.
1226 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1227 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1228 return true;
1229 }
1230
1231 return VisitDeclarationNameInfo(D->getNameInfo());
1232}
1233
1234bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1235 UnresolvedUsingTypenameDecl *D) {
1236 // Visit nested-name-specifier.
1237 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1238 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1239 return true;
1240
1241 return false;
1242}
1243
Olivier Goffart81978012016-06-09 16:15:55 +00001244bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1245 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1246 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001247 if (StringLiteral *Message = D->getMessage())
1248 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1249 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001250 return false;
1251}
1252
Olivier Goffartd211c642016-11-04 06:29:27 +00001253bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1254 if (NamedDecl *FriendD = D->getFriendDecl()) {
1255 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1256 return true;
1257 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1258 if (Visit(TI->getTypeLoc()))
1259 return true;
1260 }
1261 return false;
1262}
1263
Guy Benyei11169dd2012-12-18 14:30:41 +00001264bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1265 switch (Name.getName().getNameKind()) {
1266 case clang::DeclarationName::Identifier:
1267 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001268 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001269 case clang::DeclarationName::CXXOperatorName:
1270 case clang::DeclarationName::CXXUsingDirective:
1271 return false;
Richard Smith35845152017-02-07 01:37:30 +00001272
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 case clang::DeclarationName::CXXConstructorName:
1274 case clang::DeclarationName::CXXDestructorName:
1275 case clang::DeclarationName::CXXConversionFunctionName:
1276 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1277 return Visit(TSInfo->getTypeLoc());
1278 return false;
1279
1280 case clang::DeclarationName::ObjCZeroArgSelector:
1281 case clang::DeclarationName::ObjCOneArgSelector:
1282 case clang::DeclarationName::ObjCMultiArgSelector:
1283 // FIXME: Per-identifier location info?
1284 return false;
1285 }
1286
1287 llvm_unreachable("Invalid DeclarationName::Kind!");
1288}
1289
1290bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1291 SourceRange Range) {
1292 // FIXME: This whole routine is a hack to work around the lack of proper
1293 // source information in nested-name-specifiers (PR5791). Since we do have
1294 // a beginning source location, we can visit the first component of the
1295 // nested-name-specifier, if it's a single-token component.
1296 if (!NNS)
1297 return false;
1298
1299 // Get the first component in the nested-name-specifier.
1300 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1301 NNS = Prefix;
1302
1303 switch (NNS->getKind()) {
1304 case NestedNameSpecifier::Namespace:
1305 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1306 TU));
1307
1308 case NestedNameSpecifier::NamespaceAlias:
1309 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1310 Range.getBegin(), TU));
1311
1312 case NestedNameSpecifier::TypeSpec: {
1313 // If the type has a form where we know that the beginning of the source
1314 // range matches up with a reference cursor. Visit the appropriate reference
1315 // cursor.
1316 const Type *T = NNS->getAsType();
1317 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1318 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1319 if (const TagType *Tag = dyn_cast<TagType>(T))
1320 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1321 if (const TemplateSpecializationType *TST
1322 = dyn_cast<TemplateSpecializationType>(T))
1323 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1324 break;
1325 }
1326
1327 case NestedNameSpecifier::TypeSpecWithTemplate:
1328 case NestedNameSpecifier::Global:
1329 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001330 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001331 break;
1332 }
1333
1334 return false;
1335}
1336
1337bool
1338CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1339 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1340 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1341 Qualifiers.push_back(Qualifier);
1342
1343 while (!Qualifiers.empty()) {
1344 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1345 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1346 switch (NNS->getKind()) {
1347 case NestedNameSpecifier::Namespace:
1348 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1349 Q.getLocalBeginLoc(),
1350 TU)))
1351 return true;
1352
1353 break;
1354
1355 case NestedNameSpecifier::NamespaceAlias:
1356 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1357 Q.getLocalBeginLoc(),
1358 TU)))
1359 return true;
1360
1361 break;
1362
1363 case NestedNameSpecifier::TypeSpec:
1364 case NestedNameSpecifier::TypeSpecWithTemplate:
1365 if (Visit(Q.getTypeLoc()))
1366 return true;
1367
1368 break;
1369
1370 case NestedNameSpecifier::Global:
1371 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001372 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001373 break;
1374 }
1375 }
1376
1377 return false;
1378}
1379
1380bool CursorVisitor::VisitTemplateParameters(
1381 const TemplateParameterList *Params) {
1382 if (!Params)
1383 return false;
1384
1385 for (TemplateParameterList::const_iterator P = Params->begin(),
1386 PEnd = Params->end();
1387 P != PEnd; ++P) {
1388 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1389 return true;
1390 }
1391
1392 return false;
1393}
1394
1395bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1396 switch (Name.getKind()) {
1397 case TemplateName::Template:
1398 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1399
1400 case TemplateName::OverloadedTemplate:
1401 // Visit the overloaded template set.
1402 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1403 return true;
1404
1405 return false;
1406
1407 case TemplateName::DependentTemplate:
1408 // FIXME: Visit nested-name-specifier.
1409 return false;
1410
1411 case TemplateName::QualifiedTemplate:
1412 // FIXME: Visit nested-name-specifier.
1413 return Visit(MakeCursorTemplateRef(
1414 Name.getAsQualifiedTemplateName()->getDecl(),
1415 Loc, TU));
1416
1417 case TemplateName::SubstTemplateTemplateParm:
1418 return Visit(MakeCursorTemplateRef(
1419 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1420 Loc, TU));
1421
1422 case TemplateName::SubstTemplateTemplateParmPack:
1423 return Visit(MakeCursorTemplateRef(
1424 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1425 Loc, TU));
1426 }
1427
1428 llvm_unreachable("Invalid TemplateName::Kind!");
1429}
1430
1431bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1432 switch (TAL.getArgument().getKind()) {
1433 case TemplateArgument::Null:
1434 case TemplateArgument::Integral:
1435 case TemplateArgument::Pack:
1436 return false;
1437
1438 case TemplateArgument::Type:
1439 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1440 return Visit(TSInfo->getTypeLoc());
1441 return false;
1442
1443 case TemplateArgument::Declaration:
1444 if (Expr *E = TAL.getSourceDeclExpression())
1445 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1446 return false;
1447
1448 case TemplateArgument::NullPtr:
1449 if (Expr *E = TAL.getSourceNullPtrExpression())
1450 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1451 return false;
1452
1453 case TemplateArgument::Expression:
1454 if (Expr *E = TAL.getSourceExpression())
1455 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1456 return false;
1457
1458 case TemplateArgument::Template:
1459 case TemplateArgument::TemplateExpansion:
1460 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1461 return true;
1462
1463 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1464 TAL.getTemplateNameLoc());
1465 }
1466
1467 llvm_unreachable("Invalid TemplateArgument::Kind!");
1468}
1469
1470bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1471 return VisitDeclContext(D);
1472}
1473
1474bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1475 return Visit(TL.getUnqualifiedLoc());
1476}
1477
1478bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1479 ASTContext &Context = AU->getASTContext();
1480
1481 // Some builtin types (such as Objective-C's "id", "sel", and
1482 // "Class") have associated declarations. Create cursors for those.
1483 QualType VisitType;
1484 switch (TL.getTypePtr()->getKind()) {
1485
1486 case BuiltinType::Void:
1487 case BuiltinType::NullPtr:
1488 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001489#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1490 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001491#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001492 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001493 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001494 case BuiltinType::OCLClkEvent:
1495 case BuiltinType::OCLQueue:
1496 case BuiltinType::OCLNDRange:
1497 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001498#define BUILTIN_TYPE(Id, SingletonId)
1499#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1500#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1501#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1502#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1503#include "clang/AST/BuiltinTypes.def"
1504 break;
1505
1506 case BuiltinType::ObjCId:
1507 VisitType = Context.getObjCIdType();
1508 break;
1509
1510 case BuiltinType::ObjCClass:
1511 VisitType = Context.getObjCClassType();
1512 break;
1513
1514 case BuiltinType::ObjCSel:
1515 VisitType = Context.getObjCSelType();
1516 break;
1517 }
1518
1519 if (!VisitType.isNull()) {
1520 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1521 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1522 TU));
1523 }
1524
1525 return false;
1526}
1527
1528bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1529 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1530}
1531
1532bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1533 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1534}
1535
1536bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1537 if (TL.isDefinition())
1538 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1539
1540 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1541}
1542
1543bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1544 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1545}
1546
1547bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001548 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001549}
1550
Manman Rene6be26c2016-09-13 17:25:08 +00001551bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1552 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1553 return true;
1554 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1555 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1556 TU)))
1557 return true;
1558 }
1559
1560 return false;
1561}
1562
Guy Benyei11169dd2012-12-18 14:30:41 +00001563bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1564 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1565 return true;
1566
Douglas Gregore9d95f12015-07-07 03:57:35 +00001567 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1568 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1569 return true;
1570 }
1571
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1573 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1574 TU)))
1575 return true;
1576 }
1577
1578 return false;
1579}
1580
1581bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1582 return Visit(TL.getPointeeLoc());
1583}
1584
1585bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1586 return Visit(TL.getInnerLoc());
1587}
1588
1589bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1590 return Visit(TL.getPointeeLoc());
1591}
1592
1593bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1594 return Visit(TL.getPointeeLoc());
1595}
1596
1597bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1598 return Visit(TL.getPointeeLoc());
1599}
1600
1601bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1602 return Visit(TL.getPointeeLoc());
1603}
1604
1605bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1606 return Visit(TL.getPointeeLoc());
1607}
1608
1609bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1610 return Visit(TL.getModifiedLoc());
1611}
1612
1613bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1614 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001615 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001616 return true;
1617
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001618 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1619 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1621 return true;
1622
1623 return false;
1624}
1625
1626bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1627 if (Visit(TL.getElementLoc()))
1628 return true;
1629
1630 if (Expr *Size = TL.getSizeExpr())
1631 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1632
1633 return false;
1634}
1635
Reid Kleckner8a365022013-06-24 17:51:48 +00001636bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1637 return Visit(TL.getOriginalLoc());
1638}
1639
Reid Kleckner0503a872013-12-05 01:23:43 +00001640bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1641 return Visit(TL.getOriginalLoc());
1642}
1643
Richard Smith600b5262017-01-26 20:40:47 +00001644bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1645 DeducedTemplateSpecializationTypeLoc TL) {
1646 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1647 TL.getTemplateNameLoc()))
1648 return true;
1649
1650 return false;
1651}
1652
Guy Benyei11169dd2012-12-18 14:30:41 +00001653bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1654 TemplateSpecializationTypeLoc TL) {
1655 // Visit the template name.
1656 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1657 TL.getTemplateNameLoc()))
1658 return true;
1659
1660 // Visit the template arguments.
1661 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1662 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1663 return true;
1664
1665 return false;
1666}
1667
1668bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1669 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1670}
1671
1672bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1673 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1674 return Visit(TSInfo->getTypeLoc());
1675
1676 return false;
1677}
1678
1679bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1680 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1681 return Visit(TSInfo->getTypeLoc());
1682
1683 return false;
1684}
1685
1686bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001687 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001688}
1689
1690bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1691 DependentTemplateSpecializationTypeLoc TL) {
1692 // Visit the nested-name-specifier, if there is one.
1693 if (TL.getQualifierLoc() &&
1694 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1695 return true;
1696
1697 // Visit the template arguments.
1698 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1699 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1700 return true;
1701
1702 return false;
1703}
1704
1705bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1706 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1707 return true;
1708
1709 return Visit(TL.getNamedTypeLoc());
1710}
1711
1712bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1713 return Visit(TL.getPatternLoc());
1714}
1715
1716bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1717 if (Expr *E = TL.getUnderlyingExpr())
1718 return Visit(MakeCXCursor(E, StmtParent, TU));
1719
1720 return false;
1721}
1722
1723bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1724 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1725}
1726
1727bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1728 return Visit(TL.getValueLoc());
1729}
1730
Xiuli Pan9c14e282016-01-09 12:53:17 +00001731bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1732 return Visit(TL.getValueLoc());
1733}
1734
Guy Benyei11169dd2012-12-18 14:30:41 +00001735#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1736bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1737 return Visit##PARENT##Loc(TL); \
1738}
1739
1740DEFAULT_TYPELOC_IMPL(Complex, Type)
1741DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1742DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1743DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1744DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1745DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1746DEFAULT_TYPELOC_IMPL(Vector, Type)
1747DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1748DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1749DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1750DEFAULT_TYPELOC_IMPL(Record, TagType)
1751DEFAULT_TYPELOC_IMPL(Enum, TagType)
1752DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1753DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1754DEFAULT_TYPELOC_IMPL(Auto, Type)
1755
1756bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1757 // Visit the nested-name-specifier, if present.
1758 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1759 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1760 return true;
1761
1762 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001763 for (const auto &I : D->bases()) {
1764 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001765 return true;
1766 }
1767 }
1768
1769 return VisitTagDecl(D);
1770}
1771
1772bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001773 for (const auto *I : D->attrs())
1774 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001775 return true;
1776
1777 return false;
1778}
1779
1780//===----------------------------------------------------------------------===//
1781// Data-recursive visitor methods.
1782//===----------------------------------------------------------------------===//
1783
1784namespace {
1785#define DEF_JOB(NAME, DATA, KIND)\
1786class NAME : public VisitorJob {\
1787public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001788 NAME(const DATA *d, CXCursor parent) : \
1789 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001790 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001791 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001792};
1793
1794DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1795DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1796DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1797DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001798DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1799DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1800DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1801#undef DEF_JOB
1802
James Y Knight04ec5bf2015-12-24 02:59:37 +00001803class ExplicitTemplateArgsVisit : public VisitorJob {
1804public:
1805 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1806 const TemplateArgumentLoc *End, CXCursor parent)
1807 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1808 End) {}
1809 static bool classof(const VisitorJob *VJ) {
1810 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1811 }
1812 const TemplateArgumentLoc *begin() const {
1813 return static_cast<const TemplateArgumentLoc *>(data[0]);
1814 }
1815 const TemplateArgumentLoc *end() {
1816 return static_cast<const TemplateArgumentLoc *>(data[1]);
1817 }
1818};
Guy Benyei11169dd2012-12-18 14:30:41 +00001819class DeclVisit : public VisitorJob {
1820public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001821 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001822 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001823 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001824 static bool classof(const VisitorJob *VJ) {
1825 return VJ->getKind() == DeclVisitKind;
1826 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001827 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001828 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001829};
1830class TypeLocVisit : public VisitorJob {
1831public:
1832 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1833 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1834 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1835
1836 static bool classof(const VisitorJob *VJ) {
1837 return VJ->getKind() == TypeLocVisitKind;
1838 }
1839
1840 TypeLoc get() const {
1841 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001842 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001843 }
1844};
1845
1846class LabelRefVisit : public VisitorJob {
1847public:
1848 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1849 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1850 labelLoc.getPtrEncoding()) {}
1851
1852 static bool classof(const VisitorJob *VJ) {
1853 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1854 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001855 const LabelDecl *get() const {
1856 return static_cast<const LabelDecl *>(data[0]);
1857 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001858 SourceLocation getLoc() const {
1859 return SourceLocation::getFromPtrEncoding(data[1]); }
1860};
1861
1862class NestedNameSpecifierLocVisit : public VisitorJob {
1863public:
1864 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1865 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1866 Qualifier.getNestedNameSpecifier(),
1867 Qualifier.getOpaqueData()) { }
1868
1869 static bool classof(const VisitorJob *VJ) {
1870 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1871 }
1872
1873 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001874 return NestedNameSpecifierLoc(
1875 const_cast<NestedNameSpecifier *>(
1876 static_cast<const NestedNameSpecifier *>(data[0])),
1877 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001878 }
1879};
1880
1881class DeclarationNameInfoVisit : public VisitorJob {
1882public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001883 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001884 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 static bool classof(const VisitorJob *VJ) {
1886 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1887 }
1888 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001889 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001890 switch (S->getStmtClass()) {
1891 default:
1892 llvm_unreachable("Unhandled Stmt");
1893 case clang::Stmt::MSDependentExistsStmtClass:
1894 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1895 case Stmt::CXXDependentScopeMemberExprClass:
1896 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1897 case Stmt::DependentScopeDeclRefExprClass:
1898 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001899 case Stmt::OMPCriticalDirectiveClass:
1900 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001901 }
1902 }
1903};
1904class MemberRefVisit : public VisitorJob {
1905public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001906 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001907 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1908 L.getPtrEncoding()) {}
1909 static bool classof(const VisitorJob *VJ) {
1910 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1911 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001912 const FieldDecl *get() const {
1913 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001914 }
1915 SourceLocation getLoc() const {
1916 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1917 }
1918};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001919class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001920 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 VisitorWorkList &WL;
1922 CXCursor Parent;
1923public:
1924 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1925 : WL(wl), Parent(parent) {}
1926
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001927 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1928 void VisitBlockExpr(const BlockExpr *B);
1929 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1930 void VisitCompoundStmt(const CompoundStmt *S);
1931 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1932 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1933 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1934 void VisitCXXNewExpr(const CXXNewExpr *E);
1935 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1936 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1937 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1938 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1939 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1940 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1941 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1942 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001943 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001944 void VisitDeclRefExpr(const DeclRefExpr *D);
1945 void VisitDeclStmt(const DeclStmt *S);
1946 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1947 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1948 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1949 void VisitForStmt(const ForStmt *FS);
1950 void VisitGotoStmt(const GotoStmt *GS);
1951 void VisitIfStmt(const IfStmt *If);
1952 void VisitInitListExpr(const InitListExpr *IE);
1953 void VisitMemberExpr(const MemberExpr *M);
1954 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1955 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1956 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1957 void VisitOverloadExpr(const OverloadExpr *E);
1958 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1959 void VisitStmt(const Stmt *S);
1960 void VisitSwitchStmt(const SwitchStmt *S);
1961 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001962 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1963 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1964 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1965 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1966 void VisitVAArgExpr(const VAArgExpr *E);
1967 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1968 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1969 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1970 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001971 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001972 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001973 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001974 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001975 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001976 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001977 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001978 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001979 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001980 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001981 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001982 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001983 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001984 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001985 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001986 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001987 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001988 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001989 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001990 void
1991 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001992 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00001993 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001994 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00001995 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001996 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00001997 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00001998 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00001999 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002000 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002001 void
2002 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002003 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002004 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002005 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002006 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002007 void VisitOMPDistributeParallelForDirective(
2008 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002009 void VisitOMPDistributeParallelForSimdDirective(
2010 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002011 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002012 void VisitOMPTargetParallelForSimdDirective(
2013 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002014 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002015 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002016 void VisitOMPTeamsDistributeSimdDirective(
2017 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002018 void VisitOMPTeamsDistributeParallelForSimdDirective(
2019 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002020 void VisitOMPTeamsDistributeParallelForDirective(
2021 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002022 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002023 void VisitOMPTargetTeamsDistributeDirective(
2024 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002025 void VisitOMPTargetTeamsDistributeParallelForDirective(
2026 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002027 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2028 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002029 void VisitOMPTargetTeamsDistributeSimdDirective(
2030 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002031
Guy Benyei11169dd2012-12-18 14:30:41 +00002032private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002033 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002034 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002035 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2036 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002037 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2038 void AddStmt(const Stmt *S);
2039 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002040 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002041 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002042 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002043};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002044} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002045
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002046void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002047 // 'S' should always be non-null, since it comes from the
2048 // statement we are visiting.
2049 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2050}
2051
2052void
2053EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2054 if (Qualifier)
2055 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2056}
2057
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002058void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002059 if (S)
2060 WL.push_back(StmtVisit(S, Parent));
2061}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002062void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002063 if (D)
2064 WL.push_back(DeclVisit(D, Parent, isFirst));
2065}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002066void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2067 unsigned NumTemplateArgs) {
2068 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002069}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002070void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002071 if (D)
2072 WL.push_back(MemberRefVisit(D, L, Parent));
2073}
2074void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2075 if (TI)
2076 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2077 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002078void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002079 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002080 for (const Stmt *SubStmt : S->children()) {
2081 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 }
2083 if (size == WL.size())
2084 return;
2085 // Now reverse the entries we just added. This will match the DFS
2086 // ordering performed by the worklist.
2087 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2088 std::reverse(I, E);
2089}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002090namespace {
2091class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2092 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002093 /// \brief Process clauses with list of variables.
2094 template <typename T>
2095 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002096public:
2097 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2098#define OPENMP_CLAUSE(Name, Class) \
2099 void Visit##Class(const Class *C);
2100#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002101 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002102 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002103};
2104
Alexey Bataev3392d762016-02-16 11:18:12 +00002105void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2106 const OMPClauseWithPreInit *C) {
2107 Visitor->AddStmt(C->getPreInitStmt());
2108}
2109
Alexey Bataev005248a2016-02-25 05:25:57 +00002110void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2111 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002112 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002113 Visitor->AddStmt(C->getPostUpdateExpr());
2114}
2115
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002116void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002117 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002118 Visitor->AddStmt(C->getCondition());
2119}
2120
Alexey Bataev3778b602014-07-17 07:32:53 +00002121void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2122 Visitor->AddStmt(C->getCondition());
2123}
2124
Alexey Bataev568a8332014-03-06 06:15:19 +00002125void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002126 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002127 Visitor->AddStmt(C->getNumThreads());
2128}
2129
Alexey Bataev62c87d22014-03-21 04:51:18 +00002130void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2131 Visitor->AddStmt(C->getSafelen());
2132}
2133
Alexey Bataev66b15b52015-08-21 11:14:16 +00002134void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2135 Visitor->AddStmt(C->getSimdlen());
2136}
2137
Alexander Musman8bd31e62014-05-27 15:12:19 +00002138void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2139 Visitor->AddStmt(C->getNumForLoops());
2140}
2141
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002142void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002143
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002144void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2145
Alexey Bataev56dafe82014-06-20 07:16:17 +00002146void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002147 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002148 Visitor->AddStmt(C->getChunkSize());
2149}
2150
Alexey Bataev10e775f2015-07-30 11:36:16 +00002151void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2152 Visitor->AddStmt(C->getNumForLoops());
2153}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002154
Alexey Bataev236070f2014-06-20 11:19:47 +00002155void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2156
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002157void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2158
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002159void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2160
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002161void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2162
Alexey Bataevdea47612014-07-23 07:46:59 +00002163void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2164
Alexey Bataev67a4f222014-07-23 10:25:33 +00002165void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2166
Alexey Bataev459dec02014-07-24 06:46:57 +00002167void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2168
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002169void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2170
Alexey Bataev346265e2015-09-25 10:37:12 +00002171void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2172
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002173void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2174
Alexey Bataevb825de12015-12-07 10:51:44 +00002175void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2176
Michael Wonge710d542015-08-07 16:16:36 +00002177void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2178 Visitor->AddStmt(C->getDevice());
2179}
2180
Kelvin Li099bb8c2015-11-24 20:50:12 +00002181void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002182 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002183 Visitor->AddStmt(C->getNumTeams());
2184}
2185
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002186void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002187 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002188 Visitor->AddStmt(C->getThreadLimit());
2189}
2190
Alexey Bataeva0569352015-12-01 10:17:31 +00002191void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2192 Visitor->AddStmt(C->getPriority());
2193}
2194
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002195void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2196 Visitor->AddStmt(C->getGrainsize());
2197}
2198
Alexey Bataev382967a2015-12-08 12:06:20 +00002199void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2200 Visitor->AddStmt(C->getNumTasks());
2201}
2202
Alexey Bataev28c75412015-12-15 08:19:24 +00002203void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2204 Visitor->AddStmt(C->getHint());
2205}
2206
Alexey Bataev756c1962013-09-24 03:17:45 +00002207template<typename T>
2208void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002209 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002210 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002211 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002212}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002213
2214void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002215 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002216 for (const auto *E : C->private_copies()) {
2217 Visitor->AddStmt(E);
2218 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002219}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002220void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2221 const OMPFirstprivateClause *C) {
2222 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002223 VisitOMPClauseWithPreInit(C);
2224 for (const auto *E : C->private_copies()) {
2225 Visitor->AddStmt(E);
2226 }
2227 for (const auto *E : C->inits()) {
2228 Visitor->AddStmt(E);
2229 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002230}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002231void OMPClauseEnqueue::VisitOMPLastprivateClause(
2232 const OMPLastprivateClause *C) {
2233 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002234 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002235 for (auto *E : C->private_copies()) {
2236 Visitor->AddStmt(E);
2237 }
2238 for (auto *E : C->source_exprs()) {
2239 Visitor->AddStmt(E);
2240 }
2241 for (auto *E : C->destination_exprs()) {
2242 Visitor->AddStmt(E);
2243 }
2244 for (auto *E : C->assignment_ops()) {
2245 Visitor->AddStmt(E);
2246 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002247}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002248void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002249 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002250}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002251void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2252 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002253 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002254 for (auto *E : C->privates()) {
2255 Visitor->AddStmt(E);
2256 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002257 for (auto *E : C->lhs_exprs()) {
2258 Visitor->AddStmt(E);
2259 }
2260 for (auto *E : C->rhs_exprs()) {
2261 Visitor->AddStmt(E);
2262 }
2263 for (auto *E : C->reduction_ops()) {
2264 Visitor->AddStmt(E);
2265 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002266}
Alexander Musman8dba6642014-04-22 13:09:42 +00002267void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2268 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002269 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002270 for (const auto *E : C->privates()) {
2271 Visitor->AddStmt(E);
2272 }
Alexander Musman3276a272015-03-21 10:12:56 +00002273 for (const auto *E : C->inits()) {
2274 Visitor->AddStmt(E);
2275 }
2276 for (const auto *E : C->updates()) {
2277 Visitor->AddStmt(E);
2278 }
2279 for (const auto *E : C->finals()) {
2280 Visitor->AddStmt(E);
2281 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002282 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002283 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002284}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002285void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2286 VisitOMPClauseList(C);
2287 Visitor->AddStmt(C->getAlignment());
2288}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002289void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2290 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002291 for (auto *E : C->source_exprs()) {
2292 Visitor->AddStmt(E);
2293 }
2294 for (auto *E : C->destination_exprs()) {
2295 Visitor->AddStmt(E);
2296 }
2297 for (auto *E : C->assignment_ops()) {
2298 Visitor->AddStmt(E);
2299 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002300}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002301void
2302OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2303 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002304 for (auto *E : C->source_exprs()) {
2305 Visitor->AddStmt(E);
2306 }
2307 for (auto *E : C->destination_exprs()) {
2308 Visitor->AddStmt(E);
2309 }
2310 for (auto *E : C->assignment_ops()) {
2311 Visitor->AddStmt(E);
2312 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002313}
Alexey Bataev6125da92014-07-21 11:26:11 +00002314void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2315 VisitOMPClauseList(C);
2316}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002317void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2318 VisitOMPClauseList(C);
2319}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002320void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2321 VisitOMPClauseList(C);
2322}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002323void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2324 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002325 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002326 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002327}
Alexey Bataev3392d762016-02-16 11:18:12 +00002328void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2329 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002330void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2331 VisitOMPClauseList(C);
2332}
Samuel Antaoec172c62016-05-26 17:49:04 +00002333void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2334 VisitOMPClauseList(C);
2335}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002336void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2337 VisitOMPClauseList(C);
2338}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002339void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2340 VisitOMPClauseList(C);
2341}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002342}
Alexey Bataev756c1962013-09-24 03:17:45 +00002343
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002344void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2345 unsigned size = WL.size();
2346 OMPClauseEnqueue Visitor(this);
2347 Visitor.Visit(S);
2348 if (size == WL.size())
2349 return;
2350 // Now reverse the entries we just added. This will match the DFS
2351 // ordering performed by the worklist.
2352 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2353 std::reverse(I, E);
2354}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002355void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2357}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002358void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 AddDecl(B->getBlockDecl());
2360}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002361void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 EnqueueChildren(E);
2363 AddTypeLoc(E->getTypeSourceInfo());
2364}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002365void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002366 for (auto &I : llvm::reverse(S->body()))
2367 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002368}
2369void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002370VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 AddStmt(S->getSubStmt());
2372 AddDeclarationNameInfo(S);
2373 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2374 AddNestedNameSpecifierLoc(QualifierLoc);
2375}
2376
2377void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002378VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002379 if (E->hasExplicitTemplateArgs())
2380 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 AddDeclarationNameInfo(E);
2382 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2383 AddNestedNameSpecifierLoc(QualifierLoc);
2384 if (!E->isImplicitAccess())
2385 AddStmt(E->getBase());
2386}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002387void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 // Enqueue the initializer , if any.
2389 AddStmt(E->getInitializer());
2390 // Enqueue the array size, if any.
2391 AddStmt(E->getArraySize());
2392 // Enqueue the allocated type.
2393 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2394 // Enqueue the placement arguments.
2395 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2396 AddStmt(E->getPlacementArg(I-1));
2397}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002398void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2400 AddStmt(CE->getArg(I-1));
2401 AddStmt(CE->getCallee());
2402 AddStmt(CE->getArg(0));
2403}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002404void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2405 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 // Visit the name of the type being destroyed.
2407 AddTypeLoc(E->getDestroyedTypeInfo());
2408 // Visit the scope type that looks disturbingly like the nested-name-specifier
2409 // but isn't.
2410 AddTypeLoc(E->getScopeTypeInfo());
2411 // Visit the nested-name-specifier.
2412 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2413 AddNestedNameSpecifierLoc(QualifierLoc);
2414 // Visit base expression.
2415 AddStmt(E->getBase());
2416}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002417void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2418 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 AddTypeLoc(E->getTypeSourceInfo());
2420}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002421void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2422 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 EnqueueChildren(E);
2424 AddTypeLoc(E->getTypeSourceInfo());
2425}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002426void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 EnqueueChildren(E);
2428 if (E->isTypeOperand())
2429 AddTypeLoc(E->getTypeOperandSourceInfo());
2430}
2431
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002432void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2433 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 EnqueueChildren(E);
2435 AddTypeLoc(E->getTypeSourceInfo());
2436}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002437void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 EnqueueChildren(E);
2439 if (E->isTypeOperand())
2440 AddTypeLoc(E->getTypeOperandSourceInfo());
2441}
2442
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002443void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 EnqueueChildren(S);
2445 AddDecl(S->getExceptionDecl());
2446}
2447
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002448void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002449 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002450 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002451 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002452}
2453
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002454void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002455 if (DR->hasExplicitTemplateArgs())
2456 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 WL.push_back(DeclRefExprParts(DR, Parent));
2458}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002459void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2460 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002461 if (E->hasExplicitTemplateArgs())
2462 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 AddDeclarationNameInfo(E);
2464 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2465}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002466void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 unsigned size = WL.size();
2468 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002469 for (const auto *D : S->decls()) {
2470 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 isFirst = false;
2472 }
2473 if (size == WL.size())
2474 return;
2475 // Now reverse the entries we just added. This will match the DFS
2476 // ordering performed by the worklist.
2477 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2478 std::reverse(I, E);
2479}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002480void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002482 for (const DesignatedInitExpr::Designator &D :
2483 llvm::reverse(E->designators())) {
2484 if (D.isFieldDesignator()) {
2485 if (FieldDecl *Field = D.getField())
2486 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 continue;
2488 }
David Majnemerf7e36092016-06-23 00:15:04 +00002489 if (D.isArrayDesignator()) {
2490 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 continue;
2492 }
David Majnemerf7e36092016-06-23 00:15:04 +00002493 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2494 AddStmt(E->getArrayRangeEnd(D));
2495 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 }
2497}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002498void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 EnqueueChildren(E);
2500 AddTypeLoc(E->getTypeInfoAsWritten());
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 AddStmt(FS->getBody());
2504 AddStmt(FS->getInc());
2505 AddStmt(FS->getCond());
2506 AddDecl(FS->getConditionVariable());
2507 AddStmt(FS->getInit());
2508}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002509void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2511}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002512void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 AddStmt(If->getElse());
2514 AddStmt(If->getThen());
2515 AddStmt(If->getCond());
2516 AddDecl(If->getConditionVariable());
2517}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002518void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 // We care about the syntactic form of the initializer list, only.
2520 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2521 IE = Syntactic;
2522 EnqueueChildren(IE);
2523}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002524void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 WL.push_back(MemberExprParts(M, Parent));
2526
2527 // If the base of the member access expression is an implicit 'this', don't
2528 // visit it.
2529 // FIXME: If we ever want to show these implicit accesses, this will be
2530 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002531 if (M->isImplicitAccess())
2532 return;
2533
2534 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2535 // real field that that we are interested in.
2536 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2537 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2538 if (FD->isAnonymousStructOrUnion()) {
2539 AddStmt(SubME->getBase());
2540 return;
2541 }
2542 }
2543 }
2544
2545 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002546}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002547void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 AddTypeLoc(E->getEncodedTypeSourceInfo());
2549}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002550void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 EnqueueChildren(M);
2552 AddTypeLoc(M->getClassReceiverTypeInfo());
2553}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002554void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 // Visit the components of the offsetof expression.
2556 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 const OffsetOfNode &Node = E->getComponent(I-1);
2558 switch (Node.getKind()) {
2559 case OffsetOfNode::Array:
2560 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2561 break;
2562 case OffsetOfNode::Field:
2563 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2564 break;
2565 case OffsetOfNode::Identifier:
2566 case OffsetOfNode::Base:
2567 continue;
2568 }
2569 }
2570 // Visit the type into which we're computing the offset.
2571 AddTypeLoc(E->getTypeSourceInfo());
2572}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002573void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002574 if (E->hasExplicitTemplateArgs())
2575 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 WL.push_back(OverloadExprParts(E, Parent));
2577}
2578void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002579 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 EnqueueChildren(E);
2581 if (E->isArgumentType())
2582 AddTypeLoc(E->getArgumentTypeInfo());
2583}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002584void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 EnqueueChildren(S);
2586}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002587void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 AddStmt(S->getBody());
2589 AddStmt(S->getCond());
2590 AddDecl(S->getConditionVariable());
2591}
2592
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002593void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 AddStmt(W->getBody());
2595 AddStmt(W->getCond());
2596 AddDecl(W->getConditionVariable());
2597}
2598
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002599void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 for (unsigned I = E->getNumArgs(); I > 0; --I)
2601 AddTypeLoc(E->getArg(I-1));
2602}
2603
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002604void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 AddTypeLoc(E->getQueriedTypeSourceInfo());
2606}
2607
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 EnqueueChildren(E);
2610}
2611
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002612void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 VisitOverloadExpr(U);
2614 if (!U->isImplicitAccess())
2615 AddStmt(U->getBase());
2616}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002617void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 AddStmt(E->getSubExpr());
2619 AddTypeLoc(E->getWrittenTypeInfo());
2620}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002621void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 WL.push_back(SizeOfPackExprParts(E, Parent));
2623}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002624void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 // If the opaque value has a source expression, just transparently
2626 // visit that. This is useful for (e.g.) pseudo-object expressions.
2627 if (Expr *SourceExpr = E->getSourceExpr())
2628 return Visit(SourceExpr);
2629}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002630void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 AddStmt(E->getBody());
2632 WL.push_back(LambdaExprParts(E, Parent));
2633}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002634void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 // Treat the expression like its syntactic form.
2636 Visit(E->getSyntacticForm());
2637}
2638
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002639void EnqueueVisitor::VisitOMPExecutableDirective(
2640 const OMPExecutableDirective *D) {
2641 EnqueueChildren(D);
2642 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2643 E = D->clauses().end();
2644 I != E; ++I)
2645 EnqueueChildren(*I);
2646}
2647
Alexander Musman3aaab662014-08-19 11:27:13 +00002648void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2649 VisitOMPExecutableDirective(D);
2650}
2651
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002652void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2653 VisitOMPExecutableDirective(D);
2654}
2655
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002656void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002657 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002658}
2659
Alexey Bataevf29276e2014-06-18 04:14:57 +00002660void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002661 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002662}
2663
Alexander Musmanf82886e2014-09-18 05:12:34 +00002664void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2665 VisitOMPLoopDirective(D);
2666}
2667
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002668void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2669 VisitOMPExecutableDirective(D);
2670}
2671
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002672void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2673 VisitOMPExecutableDirective(D);
2674}
2675
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002676void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2677 VisitOMPExecutableDirective(D);
2678}
2679
Alexander Musman80c22892014-07-17 08:54:58 +00002680void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2681 VisitOMPExecutableDirective(D);
2682}
2683
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002684void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2685 VisitOMPExecutableDirective(D);
2686 AddDeclarationNameInfo(D);
2687}
2688
Alexey Bataev4acb8592014-07-07 13:01:15 +00002689void
2690EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002691 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002692}
2693
Alexander Musmane4e893b2014-09-23 09:33:00 +00002694void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2695 const OMPParallelForSimdDirective *D) {
2696 VisitOMPLoopDirective(D);
2697}
2698
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002699void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2700 const OMPParallelSectionsDirective *D) {
2701 VisitOMPExecutableDirective(D);
2702}
2703
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002704void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2705 VisitOMPExecutableDirective(D);
2706}
2707
Alexey Bataev68446b72014-07-18 07:47:19 +00002708void
2709EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2710 VisitOMPExecutableDirective(D);
2711}
2712
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002713void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2714 VisitOMPExecutableDirective(D);
2715}
2716
Alexey Bataev2df347a2014-07-18 10:17:07 +00002717void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2718 VisitOMPExecutableDirective(D);
2719}
2720
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002721void EnqueueVisitor::VisitOMPTaskgroupDirective(
2722 const OMPTaskgroupDirective *D) {
2723 VisitOMPExecutableDirective(D);
2724}
2725
Alexey Bataev6125da92014-07-21 11:26:11 +00002726void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2727 VisitOMPExecutableDirective(D);
2728}
2729
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002730void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2731 VisitOMPExecutableDirective(D);
2732}
2733
Alexey Bataev0162e452014-07-22 10:10:35 +00002734void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2735 VisitOMPExecutableDirective(D);
2736}
2737
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002738void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2739 VisitOMPExecutableDirective(D);
2740}
2741
Michael Wong65f367f2015-07-21 13:44:28 +00002742void EnqueueVisitor::VisitOMPTargetDataDirective(const
2743 OMPTargetDataDirective *D) {
2744 VisitOMPExecutableDirective(D);
2745}
2746
Samuel Antaodf67fc42016-01-19 19:15:56 +00002747void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2748 const OMPTargetEnterDataDirective *D) {
2749 VisitOMPExecutableDirective(D);
2750}
2751
Samuel Antao72590762016-01-19 20:04:50 +00002752void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2753 const OMPTargetExitDataDirective *D) {
2754 VisitOMPExecutableDirective(D);
2755}
2756
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002757void EnqueueVisitor::VisitOMPTargetParallelDirective(
2758 const OMPTargetParallelDirective *D) {
2759 VisitOMPExecutableDirective(D);
2760}
2761
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002762void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2763 const OMPTargetParallelForDirective *D) {
2764 VisitOMPLoopDirective(D);
2765}
2766
Alexey Bataev13314bf2014-10-09 04:18:56 +00002767void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2768 VisitOMPExecutableDirective(D);
2769}
2770
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002771void EnqueueVisitor::VisitOMPCancellationPointDirective(
2772 const OMPCancellationPointDirective *D) {
2773 VisitOMPExecutableDirective(D);
2774}
2775
Alexey Bataev80909872015-07-02 11:25:17 +00002776void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2777 VisitOMPExecutableDirective(D);
2778}
2779
Alexey Bataev49f6e782015-12-01 04:18:41 +00002780void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2781 VisitOMPLoopDirective(D);
2782}
2783
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002784void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2785 const OMPTaskLoopSimdDirective *D) {
2786 VisitOMPLoopDirective(D);
2787}
2788
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002789void EnqueueVisitor::VisitOMPDistributeDirective(
2790 const OMPDistributeDirective *D) {
2791 VisitOMPLoopDirective(D);
2792}
2793
Carlo Bertolli9925f152016-06-27 14:55:37 +00002794void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2795 const OMPDistributeParallelForDirective *D) {
2796 VisitOMPLoopDirective(D);
2797}
2798
Kelvin Li4a39add2016-07-05 05:00:15 +00002799void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2800 const OMPDistributeParallelForSimdDirective *D) {
2801 VisitOMPLoopDirective(D);
2802}
2803
Kelvin Li787f3fc2016-07-06 04:45:38 +00002804void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2805 const OMPDistributeSimdDirective *D) {
2806 VisitOMPLoopDirective(D);
2807}
2808
Kelvin Lia579b912016-07-14 02:54:56 +00002809void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2810 const OMPTargetParallelForSimdDirective *D) {
2811 VisitOMPLoopDirective(D);
2812}
2813
Kelvin Li986330c2016-07-20 22:57:10 +00002814void EnqueueVisitor::VisitOMPTargetSimdDirective(
2815 const OMPTargetSimdDirective *D) {
2816 VisitOMPLoopDirective(D);
2817}
2818
Kelvin Li02532872016-08-05 14:37:37 +00002819void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2820 const OMPTeamsDistributeDirective *D) {
2821 VisitOMPLoopDirective(D);
2822}
2823
Kelvin Li4e325f72016-10-25 12:50:55 +00002824void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2825 const OMPTeamsDistributeSimdDirective *D) {
2826 VisitOMPLoopDirective(D);
2827}
2828
Kelvin Li579e41c2016-11-30 23:51:03 +00002829void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2830 const OMPTeamsDistributeParallelForSimdDirective *D) {
2831 VisitOMPLoopDirective(D);
2832}
2833
Kelvin Li7ade93f2016-12-09 03:24:30 +00002834void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2835 const OMPTeamsDistributeParallelForDirective *D) {
2836 VisitOMPLoopDirective(D);
2837}
2838
Kelvin Libf594a52016-12-17 05:48:59 +00002839void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2840 const OMPTargetTeamsDirective *D) {
2841 VisitOMPExecutableDirective(D);
2842}
2843
Kelvin Li83c451e2016-12-25 04:52:54 +00002844void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2845 const OMPTargetTeamsDistributeDirective *D) {
2846 VisitOMPLoopDirective(D);
2847}
2848
Kelvin Li80e8f562016-12-29 22:16:30 +00002849void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2850 const OMPTargetTeamsDistributeParallelForDirective *D) {
2851 VisitOMPLoopDirective(D);
2852}
2853
Kelvin Li1851df52017-01-03 05:23:48 +00002854void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2855 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2856 VisitOMPLoopDirective(D);
2857}
2858
Kelvin Lida681182017-01-10 18:08:18 +00002859void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2860 const OMPTargetTeamsDistributeSimdDirective *D) {
2861 VisitOMPLoopDirective(D);
2862}
2863
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002864void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2866}
2867
2868bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2869 if (RegionOfInterest.isValid()) {
2870 SourceRange Range = getRawCursorExtent(C);
2871 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2872 return false;
2873 }
2874 return true;
2875}
2876
2877bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2878 while (!WL.empty()) {
2879 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002880 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002881
2882 // Set the Parent field, then back to its old value once we're done.
2883 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2884
2885 switch (LI.getKind()) {
2886 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002887 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002888 if (!D)
2889 continue;
2890
2891 // For now, perform default visitation for Decls.
2892 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2893 cast<DeclVisit>(&LI)->isFirst())))
2894 return true;
2895
2896 continue;
2897 }
2898 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002899 for (const TemplateArgumentLoc &Arg :
2900 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2901 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 return true;
2903 }
2904 continue;
2905 }
2906 case VisitorJob::TypeLocVisitKind: {
2907 // Perform default visitation for TypeLocs.
2908 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2909 return true;
2910 continue;
2911 }
2912 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002913 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 if (LabelStmt *stmt = LS->getStmt()) {
2915 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2916 TU))) {
2917 return true;
2918 }
2919 }
2920 continue;
2921 }
2922
2923 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2924 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2925 if (VisitNestedNameSpecifierLoc(V->get()))
2926 return true;
2927 continue;
2928 }
2929
2930 case VisitorJob::DeclarationNameInfoVisitKind: {
2931 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2932 ->get()))
2933 return true;
2934 continue;
2935 }
2936 case VisitorJob::MemberRefVisitKind: {
2937 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2938 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2939 return true;
2940 continue;
2941 }
2942 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002943 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 if (!S)
2945 continue;
2946
2947 // Update the current cursor.
2948 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2949 if (!IsInRegionOfInterest(Cursor))
2950 continue;
2951 switch (Visitor(Cursor, Parent, ClientData)) {
2952 case CXChildVisit_Break: return true;
2953 case CXChildVisit_Continue: break;
2954 case CXChildVisit_Recurse:
2955 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002956 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 EnqueueWorkList(WL, S);
2958 break;
2959 }
2960 continue;
2961 }
2962 case VisitorJob::MemberExprPartsKind: {
2963 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002964 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002965
2966 // Visit the nested-name-specifier
2967 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2968 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2969 return true;
2970
2971 // Visit the declaration name.
2972 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2973 return true;
2974
2975 // Visit the explicitly-specified template arguments, if any.
2976 if (M->hasExplicitTemplateArgs()) {
2977 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2978 *ArgEnd = Arg + M->getNumTemplateArgs();
2979 Arg != ArgEnd; ++Arg) {
2980 if (VisitTemplateArgumentLoc(*Arg))
2981 return true;
2982 }
2983 }
2984 continue;
2985 }
2986 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002987 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 // Visit nested-name-specifier, if present.
2989 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2990 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2991 return true;
2992 // Visit declaration name.
2993 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2994 return true;
2995 continue;
2996 }
2997 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002998 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002999 // Visit the nested-name-specifier.
3000 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3001 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3002 return true;
3003 // Visit the declaration name.
3004 if (VisitDeclarationNameInfo(O->getNameInfo()))
3005 return true;
3006 // Visit the overloaded declaration reference.
3007 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3008 return true;
3009 continue;
3010 }
3011 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003012 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 NamedDecl *Pack = E->getPack();
3014 if (isa<TemplateTypeParmDecl>(Pack)) {
3015 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3016 E->getPackLoc(), TU)))
3017 return true;
3018
3019 continue;
3020 }
3021
3022 if (isa<TemplateTemplateParmDecl>(Pack)) {
3023 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3024 E->getPackLoc(), TU)))
3025 return true;
3026
3027 continue;
3028 }
3029
3030 // Non-type template parameter packs and function parameter packs are
3031 // treated like DeclRefExpr cursors.
3032 continue;
3033 }
3034
3035 case VisitorJob::LambdaExprPartsKind: {
3036 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003037 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3039 CEnd = E->explicit_capture_end();
3040 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003041 // FIXME: Lambda init-captures.
3042 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003044
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3046 C->getLocation(),
3047 TU)))
3048 return true;
3049 }
3050
3051 // Visit parameters and return type, if present.
3052 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3053 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3054 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3055 // Visit the whole type.
3056 if (Visit(TL))
3057 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003058 } else if (FunctionProtoTypeLoc Proto =
3059 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 if (E->hasExplicitParameters()) {
3061 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003062 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3063 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 return true;
3065 } else {
3066 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003067 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 return true;
3069 }
3070 }
3071 }
3072 break;
3073 }
3074
3075 case VisitorJob::PostChildrenVisitKind:
3076 if (PostChildrenVisitor(Parent, ClientData))
3077 return true;
3078 break;
3079 }
3080 }
3081 return false;
3082}
3083
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003084bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003085 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 if (!WorkListFreeList.empty()) {
3087 WL = WorkListFreeList.back();
3088 WL->clear();
3089 WorkListFreeList.pop_back();
3090 }
3091 else {
3092 WL = new VisitorWorkList();
3093 WorkListCache.push_back(WL);
3094 }
3095 EnqueueWorkList(*WL, S);
3096 bool result = RunVisitorWorkList(*WL);
3097 WorkListFreeList.push_back(WL);
3098 return result;
3099}
3100
3101namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003102typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003103RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3104 const DeclarationNameInfo &NI, SourceRange QLoc,
3105 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3107 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3108 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3109
3110 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3111
3112 RefNamePieces Pieces;
3113
3114 if (WantQualifier && QLoc.isValid())
3115 Pieces.push_back(QLoc);
3116
3117 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3118 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003119
3120 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3121 Pieces.push_back(*TemplateArgsLoc);
3122
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 if (Kind == DeclarationName::CXXOperatorName) {
3124 Pieces.push_back(SourceLocation::getFromRawEncoding(
3125 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3126 Pieces.push_back(SourceLocation::getFromRawEncoding(
3127 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3128 }
3129
3130 if (WantSinglePiece) {
3131 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3132 Pieces.clear();
3133 Pieces.push_back(R);
3134 }
3135
3136 return Pieces;
3137}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003138}
Guy Benyei11169dd2012-12-18 14:30:41 +00003139
3140//===----------------------------------------------------------------------===//
3141// Misc. API hooks.
3142//===----------------------------------------------------------------------===//
3143
Chad Rosier05c71aa2013-03-27 18:28:23 +00003144static void fatal_error_handler(void *user_data, const std::string& reason,
3145 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 // Write the result out to stderr avoiding errs() because raw_ostreams can
3147 // call report_fatal_error.
3148 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3149 ::abort();
3150}
3151
Chandler Carruth66660742014-06-27 16:37:27 +00003152namespace {
3153struct RegisterFatalErrorHandler {
3154 RegisterFatalErrorHandler() {
3155 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3156 }
3157};
3158}
3159
3160static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3161
Guy Benyei11169dd2012-12-18 14:30:41 +00003162CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3163 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 // We use crash recovery to make some of our APIs more reliable, implicitly
3165 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003166 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3167 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003168
Chandler Carruth66660742014-06-27 16:37:27 +00003169 // Look through the managed static to trigger construction of the managed
3170 // static which registers our fatal error handler. This ensures it is only
3171 // registered once.
3172 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003173
Adrian Prantlbc068582015-07-08 01:00:30 +00003174 // Initialize targets for clang module support.
3175 llvm::InitializeAllTargets();
3176 llvm::InitializeAllTargetMCs();
3177 llvm::InitializeAllAsmPrinters();
3178 llvm::InitializeAllAsmParsers();
3179
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003180 CIndexer *CIdxr = new CIndexer();
3181
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 if (excludeDeclarationsFromPCH)
3183 CIdxr->setOnlyLocalDecls();
3184 if (displayDiagnostics)
3185 CIdxr->setDisplayDiagnostics();
3186
3187 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3188 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3189 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3190 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3191 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3192 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3193
3194 return CIdxr;
3195}
3196
3197void clang_disposeIndex(CXIndex CIdx) {
3198 if (CIdx)
3199 delete static_cast<CIndexer *>(CIdx);
3200}
3201
3202void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3203 if (CIdx)
3204 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3205}
3206
3207unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3208 if (CIdx)
3209 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3210 return 0;
3211}
3212
3213void clang_toggleCrashRecovery(unsigned isEnabled) {
3214 if (isEnabled)
3215 llvm::CrashRecoveryContext::Enable();
3216 else
3217 llvm::CrashRecoveryContext::Disable();
3218}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003219
Guy Benyei11169dd2012-12-18 14:30:41 +00003220CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3221 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003222 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003223 enum CXErrorCode Result =
3224 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003225 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003226 assert((TU && Result == CXError_Success) ||
3227 (!TU && Result != CXError_Success));
3228 return TU;
3229}
3230
3231enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3232 const char *ast_filename,
3233 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003234 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003235 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003236
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003237 if (!CIdx || !ast_filename || !out_TU)
3238 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003239
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003240 LOG_FUNC_SECTION {
3241 *Log << ast_filename;
3242 }
3243
Guy Benyei11169dd2012-12-18 14:30:41 +00003244 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3245 FileSystemOptions FileSystemOpts;
3246
Justin Bognerd512c1e2014-10-15 00:33:06 +00003247 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3248 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003249 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003250 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003251 FileSystemOpts, /*UseDebugInfo=*/false,
3252 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003253 /*CaptureDiagnostics=*/true,
3254 /*AllowPCHWithCompilerErrors=*/true,
3255 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003256 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003257 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003258}
3259
3260unsigned clang_defaultEditingTranslationUnitOptions() {
3261 return CXTranslationUnit_PrecompiledPreamble |
3262 CXTranslationUnit_CacheCompletionResults;
3263}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003264
Guy Benyei11169dd2012-12-18 14:30:41 +00003265CXTranslationUnit
3266clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3267 const char *source_filename,
3268 int num_command_line_args,
3269 const char * const *command_line_args,
3270 unsigned num_unsaved_files,
3271 struct CXUnsavedFile *unsaved_files) {
3272 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3273 return clang_parseTranslationUnit(CIdx, source_filename,
3274 command_line_args, num_command_line_args,
3275 unsaved_files, num_unsaved_files,
3276 Options);
3277}
3278
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003279static CXErrorCode
3280clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3281 const char *const *command_line_args,
3282 int num_command_line_args,
3283 ArrayRef<CXUnsavedFile> unsaved_files,
3284 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003285 // Set up the initial return values.
3286 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003287 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003288
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003289 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003290 if (!CIdx || !out_TU)
3291 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3294
3295 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3296 setThreadBackgroundPriority();
3297
3298 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003299 bool CreatePreambleOnFirstParse =
3300 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 // FIXME: Add a flag for modules.
3302 TranslationUnitKind TUKind
3303 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003304 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 = options & CXTranslationUnit_CacheCompletionResults;
3306 bool IncludeBriefCommentsInCodeCompletion
3307 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3308 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3309 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3310
3311 // Configure the diagnostics.
3312 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003313 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003314
Manuel Klimek016c0242016-03-01 10:56:19 +00003315 if (options & CXTranslationUnit_KeepGoing)
3316 Diags->setFatalsAsError(true);
3317
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 // Recover resources if we crash before exiting this function.
3319 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3320 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003321 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003322
Ahmed Charlesb8984322014-03-07 20:03:18 +00003323 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3324 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003325
3326 // Recover resources if we crash before exiting this function.
3327 llvm::CrashRecoveryContextCleanupRegistrar<
3328 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3329
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003330 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003331 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003332 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003333 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 }
3335
Ahmed Charlesb8984322014-03-07 20:03:18 +00003336 std::unique_ptr<std::vector<const char *>> Args(
3337 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003338
3339 // Recover resources if we crash before exiting this method.
3340 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3341 ArgsCleanup(Args.get());
3342
3343 // Since the Clang C library is primarily used by batch tools dealing with
3344 // (often very broken) source code, where spell-checking can have a
3345 // significant negative impact on performance (particularly when
3346 // precompiled headers are involved), we disable it by default.
3347 // Only do this if we haven't found a spell-checking-related argument.
3348 bool FoundSpellCheckingArgument = false;
3349 for (int I = 0; I != num_command_line_args; ++I) {
3350 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3351 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3352 FoundSpellCheckingArgument = true;
3353 break;
3354 }
3355 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003356 Args->insert(Args->end(), command_line_args,
3357 command_line_args + num_command_line_args);
3358
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003359 if (!FoundSpellCheckingArgument)
3360 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3361
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 // The 'source_filename' argument is optional. If the caller does not
3363 // specify it then it is assumed that the source file is specified
3364 // in the actual argument list.
3365 // Put the source file after command_line_args otherwise if '-x' flag is
3366 // present it will be unused.
3367 if (source_filename)
3368 Args->push_back(source_filename);
3369
3370 // Do we need the detailed preprocessing record?
3371 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3372 Args->push_back("-Xclang");
3373 Args->push_back("-detailed-preprocessing-record");
3374 }
3375
3376 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003377 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003378 // Unless the user specified that they want the preamble on the first parse
3379 // set it up to be created on the first reparse. This makes the first parse
3380 // faster, trading for a slower (first) reparse.
3381 unsigned PrecompilePreambleAfterNParses =
3382 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003383 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003384 Args->data(), Args->data() + Args->size(),
3385 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003386 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3387 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003388 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3389 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003390 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003391 /*UserFilesAreVolatile=*/true, ForSerialization,
3392 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3393 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003394
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003395 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003396 if (!Unit && !ErrUnit)
3397 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003398
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 if (NumErrors != Diags->getClient()->getNumErrors()) {
3400 // Make sure to check that 'Unit' is non-NULL.
3401 if (CXXIdx->getDisplayDiagnostics())
3402 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3403 }
3404
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003405 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3406 return CXError_ASTReadError;
3407
David Blaikieea4395e2017-01-06 19:49:01 +00003408 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003409 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003410}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003411
3412CXTranslationUnit
3413clang_parseTranslationUnit(CXIndex CIdx,
3414 const char *source_filename,
3415 const char *const *command_line_args,
3416 int num_command_line_args,
3417 struct CXUnsavedFile *unsaved_files,
3418 unsigned num_unsaved_files,
3419 unsigned options) {
3420 CXTranslationUnit TU;
3421 enum CXErrorCode Result = clang_parseTranslationUnit2(
3422 CIdx, source_filename, command_line_args, num_command_line_args,
3423 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003424 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003425 assert((TU && Result == CXError_Success) ||
3426 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003427 return TU;
3428}
3429
3430enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003431 CXIndex CIdx, const char *source_filename,
3432 const char *const *command_line_args, int num_command_line_args,
3433 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3434 unsigned options, CXTranslationUnit *out_TU) {
3435 SmallVector<const char *, 4> Args;
3436 Args.push_back("clang");
3437 Args.append(command_line_args, command_line_args + num_command_line_args);
3438 return clang_parseTranslationUnit2FullArgv(
3439 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3440 num_unsaved_files, options, out_TU);
3441}
3442
3443enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3444 CXIndex CIdx, const char *source_filename,
3445 const char *const *command_line_args, int num_command_line_args,
3446 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3447 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003448 LOG_FUNC_SECTION {
3449 *Log << source_filename << ": ";
3450 for (int i = 0; i != num_command_line_args; ++i)
3451 *Log << command_line_args[i] << " ";
3452 }
3453
Alp Toker9d85b182014-07-07 01:23:14 +00003454 if (num_unsaved_files && !unsaved_files)
3455 return CXError_InvalidArguments;
3456
Alp Toker5c532982014-07-07 22:42:03 +00003457 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003458 auto ParseTranslationUnitImpl = [=, &result] {
3459 result = clang_parseTranslationUnit_Impl(
3460 CIdx, source_filename, command_line_args, num_command_line_args,
3461 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3462 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003463 llvm::CrashRecoveryContext CRC;
3464
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003465 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3467 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3468 fprintf(stderr, " 'command_line_args' : [");
3469 for (int i = 0; i != num_command_line_args; ++i) {
3470 if (i)
3471 fprintf(stderr, ", ");
3472 fprintf(stderr, "'%s'", command_line_args[i]);
3473 }
3474 fprintf(stderr, "],\n");
3475 fprintf(stderr, " 'unsaved_files' : [");
3476 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3477 if (i)
3478 fprintf(stderr, ", ");
3479 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3480 unsaved_files[i].Length);
3481 }
3482 fprintf(stderr, "],\n");
3483 fprintf(stderr, " 'options' : %d,\n", options);
3484 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003485
3486 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003488 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003489 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 }
Alp Toker5c532982014-07-07 22:42:03 +00003491
3492 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003493}
3494
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003495CXString clang_Type_getObjCEncoding(CXType CT) {
3496 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3497 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3498 std::string encoding;
3499 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3500 encoding);
3501
3502 return cxstring::createDup(encoding);
3503}
3504
3505static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3506 if (C.kind == CXCursor_MacroDefinition) {
3507 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3508 return MDR->getName();
3509 } else if (C.kind == CXCursor_MacroExpansion) {
3510 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3511 return ME.getName();
3512 }
3513 return nullptr;
3514}
3515
3516unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3517 const IdentifierInfo *II = getMacroIdentifier(C);
3518 if (!II) {
3519 return false;
3520 }
3521 ASTUnit *ASTU = getCursorASTUnit(C);
3522 Preprocessor &PP = ASTU->getPreprocessor();
3523 if (const MacroInfo *MI = PP.getMacroInfo(II))
3524 return MI->isFunctionLike();
3525 return false;
3526}
3527
3528unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3529 const IdentifierInfo *II = getMacroIdentifier(C);
3530 if (!II) {
3531 return false;
3532 }
3533 ASTUnit *ASTU = getCursorASTUnit(C);
3534 Preprocessor &PP = ASTU->getPreprocessor();
3535 if (const MacroInfo *MI = PP.getMacroInfo(II))
3536 return MI->isBuiltinMacro();
3537 return false;
3538}
3539
3540unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3541 const Decl *D = getCursorDecl(C);
3542 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3543 if (!FD) {
3544 return false;
3545 }
3546 return FD->isInlined();
3547}
3548
3549static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3550 if (callExpr->getNumArgs() != 1) {
3551 return nullptr;
3552 }
3553
3554 StringLiteral *S = nullptr;
3555 auto *arg = callExpr->getArg(0);
3556 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3557 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3558 auto *subExpr = I->getSubExprAsWritten();
3559
3560 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3561 return nullptr;
3562 }
3563
3564 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3565 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3566 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3567 } else {
3568 return nullptr;
3569 }
3570 return S;
3571}
3572
David Blaikie59272572016-04-13 18:23:33 +00003573struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003574 CXEvalResultKind EvalType;
3575 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003576 unsigned long long unsignedVal;
3577 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003578 double floatVal;
3579 char *stringVal;
3580 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003581 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003582 ~ExprEvalResult() {
3583 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3584 EvalType != CXEval_Int) {
3585 delete EvalData.stringVal;
3586 }
3587 }
3588};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003589
3590void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003591 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003592}
3593
3594CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3595 if (!E) {
3596 return CXEval_UnExposed;
3597 }
3598 return ((ExprEvalResult *)E)->EvalType;
3599}
3600
3601int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003602 return clang_EvalResult_getAsLongLong(E);
3603}
3604
3605long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003606 if (!E) {
3607 return 0;
3608 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003609 ExprEvalResult *Result = (ExprEvalResult*)E;
3610 if (Result->IsUnsignedInt)
3611 return Result->EvalData.unsignedVal;
3612 return Result->EvalData.intVal;
3613}
3614
3615unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3616 return ((ExprEvalResult *)E)->IsUnsignedInt;
3617}
3618
3619unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3620 if (!E) {
3621 return 0;
3622 }
3623
3624 ExprEvalResult *Result = (ExprEvalResult*)E;
3625 if (Result->IsUnsignedInt)
3626 return Result->EvalData.unsignedVal;
3627 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003628}
3629
3630double clang_EvalResult_getAsDouble(CXEvalResult E) {
3631 if (!E) {
3632 return 0;
3633 }
3634 return ((ExprEvalResult *)E)->EvalData.floatVal;
3635}
3636
3637const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3638 if (!E) {
3639 return nullptr;
3640 }
3641 return ((ExprEvalResult *)E)->EvalData.stringVal;
3642}
3643
3644static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3645 Expr::EvalResult ER;
3646 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003647 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003648 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003649
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003650 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003651 if (!expr->EvaluateAsRValue(ER, ctx))
3652 return nullptr;
3653
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003654 QualType rettype;
3655 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003656 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003657 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003658 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003659
David Blaikiebbc00882016-04-13 18:36:19 +00003660 if (ER.Val.isInt()) {
3661 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003662
3663 auto& val = ER.Val.getInt();
3664 if (val.isUnsigned()) {
3665 result->IsUnsignedInt = true;
3666 result->EvalData.unsignedVal = val.getZExtValue();
3667 } else {
3668 result->EvalData.intVal = val.getExtValue();
3669 }
3670
David Blaikiebbc00882016-04-13 18:36:19 +00003671 return result.release();
3672 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003673
David Blaikiebbc00882016-04-13 18:36:19 +00003674 if (ER.Val.isFloat()) {
3675 llvm::SmallVector<char, 100> Buffer;
3676 ER.Val.getFloat().toString(Buffer);
3677 std::string floatStr(Buffer.data(), Buffer.size());
3678 result->EvalType = CXEval_Float;
3679 bool ignored;
3680 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003681 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003682 llvm::APFloat::rmNearestTiesToEven, &ignored);
3683 result->EvalData.floatVal = apFloat.convertToDouble();
3684 return result.release();
3685 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003686
David Blaikiebbc00882016-04-13 18:36:19 +00003687 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3688 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3689 auto *subExpr = I->getSubExprAsWritten();
3690 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3691 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003692 const StringLiteral *StrE = nullptr;
3693 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003694 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003695
3696 if (ObjCExpr) {
3697 StrE = ObjCExpr->getString();
3698 result->EvalType = CXEval_ObjCStrLiteral;
3699 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003700 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003701 result->EvalType = CXEval_StrLiteral;
3702 }
3703
3704 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003705 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003706 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3707 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003708 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003709 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003710 }
3711 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3712 expr->getStmtClass() == Stmt::StringLiteralClass) {
3713 const StringLiteral *StrE = nullptr;
3714 const ObjCStringLiteral *ObjCExpr;
3715 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003716
David Blaikiebbc00882016-04-13 18:36:19 +00003717 if (ObjCExpr) {
3718 StrE = ObjCExpr->getString();
3719 result->EvalType = CXEval_ObjCStrLiteral;
3720 } else {
3721 StrE = cast<StringLiteral>(expr);
3722 result->EvalType = CXEval_StrLiteral;
3723 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003724
David Blaikiebbc00882016-04-13 18:36:19 +00003725 std::string strRef(StrE->getString().str());
3726 result->EvalData.stringVal = new char[strRef.size() + 1];
3727 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3728 result->EvalData.stringVal[strRef.size()] = '\0';
3729 return result.release();
3730 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003731
David Blaikiebbc00882016-04-13 18:36:19 +00003732 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3733 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003734
David Blaikiebbc00882016-04-13 18:36:19 +00003735 rettype = CC->getType();
3736 if (rettype.getAsString() == "CFStringRef" &&
3737 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003738
David Blaikiebbc00882016-04-13 18:36:19 +00003739 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3740 StringLiteral *S = getCFSTR_value(callExpr);
3741 if (S) {
3742 std::string strLiteral(S->getString().str());
3743 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003744
David Blaikiebbc00882016-04-13 18:36:19 +00003745 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3746 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3747 strLiteral.size());
3748 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003749 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003750 }
3751 }
3752
David Blaikiebbc00882016-04-13 18:36:19 +00003753 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3754 callExpr = static_cast<CallExpr *>(expr);
3755 rettype = callExpr->getCallReturnType(ctx);
3756
3757 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3758 return nullptr;
3759
3760 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3761 if (callExpr->getNumArgs() == 1 &&
3762 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3763 return nullptr;
3764 } else if (rettype.getAsString() == "CFStringRef") {
3765
3766 StringLiteral *S = getCFSTR_value(callExpr);
3767 if (S) {
3768 std::string strLiteral(S->getString().str());
3769 result->EvalType = CXEval_CFStr;
3770 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3771 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3772 strLiteral.size());
3773 result->EvalData.stringVal[strLiteral.size()] = '\0';
3774 return result.release();
3775 }
3776 }
3777 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3778 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3779 ValueDecl *V = D->getDecl();
3780 if (V->getKind() == Decl::Function) {
3781 std::string strName = V->getNameAsString();
3782 result->EvalType = CXEval_Other;
3783 result->EvalData.stringVal = new char[strName.size() + 1];
3784 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3785 result->EvalData.stringVal[strName.size()] = '\0';
3786 return result.release();
3787 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003788 }
3789
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003790 return nullptr;
3791}
3792
3793CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3794 const Decl *D = getCursorDecl(C);
3795 if (D) {
3796 const Expr *expr = nullptr;
3797 if (auto *Var = dyn_cast<VarDecl>(D)) {
3798 expr = Var->getInit();
3799 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3800 expr = Field->getInClassInitializer();
3801 }
3802 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003803 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3804 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003805 return nullptr;
3806 }
3807
3808 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3809 if (compoundStmt) {
3810 Expr *expr = nullptr;
3811 for (auto *bodyIterator : compoundStmt->body()) {
3812 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3813 break;
3814 }
3815 }
3816 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003817 return const_cast<CXEvalResult>(
3818 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003819 }
3820 return nullptr;
3821}
3822
3823unsigned clang_Cursor_hasAttrs(CXCursor C) {
3824 const Decl *D = getCursorDecl(C);
3825 if (!D) {
3826 return 0;
3827 }
3828
3829 if (D->hasAttrs()) {
3830 return 1;
3831 }
3832
3833 return 0;
3834}
Guy Benyei11169dd2012-12-18 14:30:41 +00003835unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3836 return CXSaveTranslationUnit_None;
3837}
3838
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003839static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3840 const char *FileName,
3841 unsigned options) {
3842 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003843 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3844 setThreadBackgroundPriority();
3845
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003846 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3847 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003848}
3849
3850int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3851 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003852 LOG_FUNC_SECTION {
3853 *Log << TU << ' ' << FileName;
3854 }
3855
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003856 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003857 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003858 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003859 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003860
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003861 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003862 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3863 if (!CXXUnit->hasSema())
3864 return CXSaveError_InvalidTU;
3865
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003866 CXSaveError result;
3867 auto SaveTranslationUnitImpl = [=, &result]() {
3868 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3869 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003870
3871 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3872 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003873 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003874
3875 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3876 PrintLibclangResourceUsage(TU);
3877
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003878 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003879 }
3880
3881 // We have an AST that has invalid nodes due to compiler errors.
3882 // Use a crash recovery thread for protection.
3883
3884 llvm::CrashRecoveryContext CRC;
3885
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003886 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003887 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3888 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3889 fprintf(stderr, " 'options' : %d,\n", options);
3890 fprintf(stderr, "}\n");
3891
3892 return CXSaveError_Unknown;
3893
3894 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3895 PrintLibclangResourceUsage(TU);
3896 }
3897
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003898 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003899}
3900
3901void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3902 if (CTUnit) {
3903 // If the translation unit has been marked as unsafe to free, just discard
3904 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003905 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3906 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003907 return;
3908
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003909 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003910 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003911 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3912 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003913 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003914 delete CTUnit;
3915 }
3916}
3917
3918unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3919 return CXReparse_None;
3920}
3921
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003922static CXErrorCode
3923clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3924 ArrayRef<CXUnsavedFile> unsaved_files,
3925 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003926 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003927 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003928 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003929 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003930 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003931
3932 // Reset the associated diagnostics.
3933 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003934 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003935
Dmitri Gribenko183436e2013-01-26 21:49:50 +00003936 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003937 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3938 setThreadBackgroundPriority();
3939
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003940 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003942
3943 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3944 new std::vector<ASTUnit::RemappedFile>());
3945
Guy Benyei11169dd2012-12-18 14:30:41 +00003946 // Recover resources if we crash before exiting this function.
3947 llvm::CrashRecoveryContextCleanupRegistrar<
3948 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00003949
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003950 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003951 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003952 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003953 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003954 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003955
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003956 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3957 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003958 return CXError_Success;
3959 if (isASTReadError(CXXUnit))
3960 return CXError_ASTReadError;
3961 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003962}
3963
3964int clang_reparseTranslationUnit(CXTranslationUnit TU,
3965 unsigned num_unsaved_files,
3966 struct CXUnsavedFile *unsaved_files,
3967 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003968 LOG_FUNC_SECTION {
3969 *Log << TU;
3970 }
3971
Alp Toker9d85b182014-07-07 01:23:14 +00003972 if (num_unsaved_files && !unsaved_files)
3973 return CXError_InvalidArguments;
3974
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003975 CXErrorCode result;
3976 auto ReparseTranslationUnitImpl = [=, &result]() {
3977 result = clang_reparseTranslationUnit_Impl(
3978 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3979 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003980
3981 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003982 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00003983 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 }
3985
3986 llvm::CrashRecoveryContext CRC;
3987
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003988 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003989 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003990 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003991 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3993 PrintLibclangResourceUsage(TU);
3994
Alp Toker5c532982014-07-07 22:42:03 +00003995 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003996}
3997
3998
3999CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004000 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004001 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004002 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004003 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004004
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004005 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004006 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004007}
4008
4009CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004010 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004011 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004012 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004013 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004014
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004015 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4017}
4018
Guy Benyei11169dd2012-12-18 14:30:41 +00004019//===----------------------------------------------------------------------===//
4020// CXFile Operations.
4021//===----------------------------------------------------------------------===//
4022
Guy Benyei11169dd2012-12-18 14:30:41 +00004023CXString clang_getFileName(CXFile SFile) {
4024 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004025 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004026
4027 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004028 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004029}
4030
4031time_t clang_getFileTime(CXFile SFile) {
4032 if (!SFile)
4033 return 0;
4034
4035 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4036 return FEnt->getModificationTime();
4037}
4038
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004039CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004040 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004041 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004042 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004043 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004044
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004045 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004046
4047 FileManager &FMgr = CXXUnit->getFileManager();
4048 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4049}
4050
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004051unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4052 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004053 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004054 LOG_BAD_TU(TU);
4055 return 0;
4056 }
4057
4058 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 return 0;
4060
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004061 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 FileEntry *FEnt = static_cast<FileEntry *>(file);
4063 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4064 .isFileMultipleIncludeGuarded(FEnt);
4065}
4066
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004067int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4068 if (!file || !outID)
4069 return 1;
4070
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004071 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004072 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4073 outID->data[0] = ID.getDevice();
4074 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004075 outID->data[2] = FEnt->getModificationTime();
4076 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004077}
4078
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004079int clang_File_isEqual(CXFile file1, CXFile file2) {
4080 if (file1 == file2)
4081 return true;
4082
4083 if (!file1 || !file2)
4084 return false;
4085
4086 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4087 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4088 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4089}
4090
Guy Benyei11169dd2012-12-18 14:30:41 +00004091//===----------------------------------------------------------------------===//
4092// CXCursor Operations.
4093//===----------------------------------------------------------------------===//
4094
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004095static const Decl *getDeclFromExpr(const Stmt *E) {
4096 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 return getDeclFromExpr(CE->getSubExpr());
4098
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004099 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004101 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004102 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004103 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004105 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004106 if (PRE->isExplicitProperty())
4107 return PRE->getExplicitProperty();
4108 // It could be messaging both getter and setter as in:
4109 // ++myobj.myprop;
4110 // in which case prefer to associate the setter since it is less obvious
4111 // from inspecting the source that the setter is going to get called.
4112 if (PRE->isMessagingSetter())
4113 return PRE->getImplicitPropertySetter();
4114 return PRE->getImplicitPropertyGetter();
4115 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004116 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004118 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004119 if (Expr *Src = OVE->getSourceExpr())
4120 return getDeclFromExpr(Src);
4121
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004122 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004124 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 if (!CE->isElidable())
4126 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004127 if (const CXXInheritedCtorInitExpr *CE =
4128 dyn_cast<CXXInheritedCtorInitExpr>(E))
4129 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004130 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004131 return OME->getMethodDecl();
4132
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004133 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004135 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004136 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4137 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004138 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4140 isa<ParmVarDecl>(SizeOfPack->getPack()))
4141 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004142
4143 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004144}
4145
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004146static SourceLocation getLocationFromExpr(const Expr *E) {
4147 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 return getLocationFromExpr(CE->getSubExpr());
4149
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004150 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004152 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004154 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004156 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004158 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004159 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004160 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004161 return PropRef->getLocation();
4162
4163 return E->getLocStart();
4164}
4165
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004166extern "C" {
4167
Guy Benyei11169dd2012-12-18 14:30:41 +00004168unsigned clang_visitChildren(CXCursor parent,
4169 CXCursorVisitor visitor,
4170 CXClientData client_data) {
4171 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4172 /*VisitPreprocessorLast=*/false);
4173 return CursorVis.VisitChildren(parent);
4174}
4175
4176#ifndef __has_feature
4177#define __has_feature(x) 0
4178#endif
4179#if __has_feature(blocks)
4180typedef enum CXChildVisitResult
4181 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4182
4183static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4184 CXClientData client_data) {
4185 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4186 return block(cursor, parent);
4187}
4188#else
4189// If we are compiled with a compiler that doesn't have native blocks support,
4190// define and call the block manually, so the
4191typedef struct _CXChildVisitResult
4192{
4193 void *isa;
4194 int flags;
4195 int reserved;
4196 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4197 CXCursor);
4198} *CXCursorVisitorBlock;
4199
4200static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4201 CXClientData client_data) {
4202 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4203 return block->invoke(block, cursor, parent);
4204}
4205#endif
4206
4207
4208unsigned clang_visitChildrenWithBlock(CXCursor parent,
4209 CXCursorVisitorBlock block) {
4210 return clang_visitChildren(parent, visitWithBlock, block);
4211}
4212
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004213static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004215 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004216
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004217 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004218 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004219 if (const ObjCPropertyImplDecl *PropImpl =
4220 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004222 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004223
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004224 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004225 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004226 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004227
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004228 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 }
4230
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004231 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004232 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004233
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004234 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4236 // and returns different names. NamedDecl returns the class name and
4237 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004238 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004239
4240 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004241 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004242
4243 SmallString<1024> S;
4244 llvm::raw_svector_ostream os(S);
4245 ND->printName(os);
4246
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004247 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004248}
4249
4250CXString clang_getCursorSpelling(CXCursor C) {
4251 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004252 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004253
4254 if (clang_isReference(C.kind)) {
4255 switch (C.kind) {
4256 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004257 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004258 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 }
4260 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004261 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004262 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 }
4264 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004265 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004267 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 }
4269 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004270 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004271 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 }
4273 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004274 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 assert(Type && "Missing type decl");
4276
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004277 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 getAsString());
4279 }
4280 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004281 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 assert(Template && "Missing template decl");
4283
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004284 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004285 }
4286
4287 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004288 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004289 assert(NS && "Missing namespace decl");
4290
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004291 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 }
4293
4294 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004295 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 assert(Field && "Missing member decl");
4297
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004298 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 }
4300
4301 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004302 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 assert(Label && "Missing label");
4304
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004305 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004306 }
4307
4308 case CXCursor_OverloadedDeclRef: {
4309 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004310 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4311 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004312 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004313 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004315 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004316 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 OverloadedTemplateStorage *Ovl
4318 = Storage.get<OverloadedTemplateStorage*>();
4319 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004320 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004321 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 }
4323
4324 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004325 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 assert(Var && "Missing variable decl");
4327
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004328 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 }
4330
4331 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004332 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 }
4334 }
4335
4336 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004337 const Expr *E = getCursorExpr(C);
4338
4339 if (C.kind == CXCursor_ObjCStringLiteral ||
4340 C.kind == CXCursor_StringLiteral) {
4341 const StringLiteral *SLit;
4342 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4343 SLit = OSL->getString();
4344 } else {
4345 SLit = cast<StringLiteral>(E);
4346 }
4347 SmallString<256> Buf;
4348 llvm::raw_svector_ostream OS(Buf);
4349 SLit->outputString(OS);
4350 return cxstring::createDup(OS.str());
4351 }
4352
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004353 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 if (D)
4355 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004356 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 }
4358
4359 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004360 const Stmt *S = getCursorStmt(C);
4361 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004362 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004363
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004364 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 }
4366
4367 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004368 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 ->getNameStart());
4370
4371 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004372 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 ->getNameStart());
4374
4375 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004376 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004377
4378 if (clang_isDeclaration(C.kind))
4379 return getDeclSpelling(getCursorDecl(C));
4380
4381 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004382 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004383 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 }
4385
4386 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004387 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004388 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 }
4390
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004391 if (C.kind == CXCursor_PackedAttr) {
4392 return cxstring::createRef("packed");
4393 }
4394
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004395 if (C.kind == CXCursor_VisibilityAttr) {
4396 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4397 switch (AA->getVisibility()) {
4398 case VisibilityAttr::VisibilityType::Default:
4399 return cxstring::createRef("default");
4400 case VisibilityAttr::VisibilityType::Hidden:
4401 return cxstring::createRef("hidden");
4402 case VisibilityAttr::VisibilityType::Protected:
4403 return cxstring::createRef("protected");
4404 }
4405 llvm_unreachable("unknown visibility type");
4406 }
4407
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004408 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004409}
4410
4411CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4412 unsigned pieceIndex,
4413 unsigned options) {
4414 if (clang_Cursor_isNull(C))
4415 return clang_getNullRange();
4416
4417 ASTContext &Ctx = getCursorContext(C);
4418
4419 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004420 const Stmt *S = getCursorStmt(C);
4421 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 if (pieceIndex > 0)
4423 return clang_getNullRange();
4424 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4425 }
4426
4427 return clang_getNullRange();
4428 }
4429
4430 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004431 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4433 if (pieceIndex >= ME->getNumSelectorLocs())
4434 return clang_getNullRange();
4435 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4436 }
4437 }
4438
4439 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4440 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004441 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4443 if (pieceIndex >= MD->getNumSelectorLocs())
4444 return clang_getNullRange();
4445 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4446 }
4447 }
4448
4449 if (C.kind == CXCursor_ObjCCategoryDecl ||
4450 C.kind == CXCursor_ObjCCategoryImplDecl) {
4451 if (pieceIndex > 0)
4452 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004453 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4455 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004456 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4458 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4459 }
4460
4461 if (C.kind == CXCursor_ModuleImportDecl) {
4462 if (pieceIndex > 0)
4463 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004464 if (const ImportDecl *ImportD =
4465 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4467 if (!Locs.empty())
4468 return cxloc::translateSourceRange(Ctx,
4469 SourceRange(Locs.front(), Locs.back()));
4470 }
4471 return clang_getNullRange();
4472 }
4473
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004474 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004475 C.kind == CXCursor_ConversionFunction ||
4476 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004477 if (pieceIndex > 0)
4478 return clang_getNullRange();
4479 if (const FunctionDecl *FD =
4480 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4481 DeclarationNameInfo FunctionName = FD->getNameInfo();
4482 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4483 }
4484 return clang_getNullRange();
4485 }
4486
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 // FIXME: A CXCursor_InclusionDirective should give the location of the
4488 // filename, but we don't keep track of this.
4489
4490 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4491 // but we don't keep track of this.
4492
4493 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4494 // but we don't keep track of this.
4495
4496 // Default handling, give the location of the cursor.
4497
4498 if (pieceIndex > 0)
4499 return clang_getNullRange();
4500
4501 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4502 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4503 return cxloc::translateSourceRange(Ctx, Loc);
4504}
4505
Eli Bendersky44a206f2014-07-31 18:04:56 +00004506CXString clang_Cursor_getMangling(CXCursor C) {
4507 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4508 return cxstring::createEmpty();
4509
Eli Bendersky44a206f2014-07-31 18:04:56 +00004510 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004511 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004512 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4513 return cxstring::createEmpty();
4514
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004515 ASTContext &Ctx = D->getASTContext();
4516 index::CodegenNameGenerator CGNameGen(Ctx);
4517 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004518}
4519
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004520CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4521 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4522 return nullptr;
4523
4524 const Decl *D = getCursorDecl(C);
4525 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4526 return nullptr;
4527
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004528 ASTContext &Ctx = D->getASTContext();
4529 index::CodegenNameGenerator CGNameGen(Ctx);
4530 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004531 return cxstring::createSet(Manglings);
4532}
4533
Guy Benyei11169dd2012-12-18 14:30:41 +00004534CXString clang_getCursorDisplayName(CXCursor C) {
4535 if (!clang_isDeclaration(C.kind))
4536 return clang_getCursorSpelling(C);
4537
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004538 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004540 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004541
4542 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004543 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 D = FunTmpl->getTemplatedDecl();
4545
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004546 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 SmallString<64> Str;
4548 llvm::raw_svector_ostream OS(Str);
4549 OS << *Function;
4550 if (Function->getPrimaryTemplate())
4551 OS << "<>";
4552 OS << "(";
4553 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4554 if (I)
4555 OS << ", ";
4556 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4557 }
4558
4559 if (Function->isVariadic()) {
4560 if (Function->getNumParams())
4561 OS << ", ";
4562 OS << "...";
4563 }
4564 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004565 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 }
4567
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004568 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 SmallString<64> Str;
4570 llvm::raw_svector_ostream OS(Str);
4571 OS << *ClassTemplate;
4572 OS << "<";
4573 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4574 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4575 if (I)
4576 OS << ", ";
4577
4578 NamedDecl *Param = Params->getParam(I);
4579 if (Param->getIdentifier()) {
4580 OS << Param->getIdentifier()->getName();
4581 continue;
4582 }
4583
4584 // There is no parameter name, which makes this tricky. Try to come up
4585 // with something useful that isn't too long.
4586 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4587 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4588 else if (NonTypeTemplateParmDecl *NTTP
4589 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4590 OS << NTTP->getType().getAsString(Policy);
4591 else
4592 OS << "template<...> class";
4593 }
4594
4595 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004596 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 }
4598
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004599 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4601 // If the type was explicitly written, use that.
4602 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004603 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004604
Benjamin Kramer9170e912013-02-22 15:46:01 +00004605 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 llvm::raw_svector_ostream OS(Str);
4607 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004608 TemplateSpecializationType::PrintTemplateArgumentList(
4609 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004610 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 }
4612
4613 return clang_getCursorSpelling(C);
4614}
4615
4616CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4617 switch (Kind) {
4618 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004619 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004621 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004623 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004625 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004627 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004629 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004631 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004633 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004635 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004637 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004639 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004641 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004643 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004645 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004647 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004649 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004650 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004651 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004653 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004654 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004655 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004657 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004659 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004661 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004663 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004665 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004667 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004669 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004671 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004673 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004675 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004677 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004678 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004679 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004680 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004681 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004682 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004683 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004685 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004687 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004689 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004691 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004693 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004694 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004695 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004696 case CXCursor_OMPArraySectionExpr:
4697 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004699 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004701 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004703 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004704 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004705 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004706 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004707 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004708 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004709 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004711 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004712 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004713 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004715 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004716 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004717 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004719 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004721 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004722 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004723 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004725 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004726 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004727 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004729 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004731 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004732 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004733 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004735 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004737 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004738 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004739 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004740 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004741 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004743 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004745 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004747 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004748 case CXCursor_ObjCAvailabilityCheckExpr:
4749 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004750 case CXCursor_ObjCSelfExpr:
4751 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004753 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004755 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004756 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004757 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004759 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004761 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004762 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004763 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004765 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004767 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004768 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004769 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004770 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004771 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004773 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004775 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004777 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004779 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004781 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004783 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004785 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004786 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004787 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004789 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004791 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004793 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004795 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004796 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004797 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004798 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004799 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004801 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004803 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004805 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004806 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004807 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004808 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004809 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004811 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004813 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004814 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004815 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004817 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004818 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004819 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004821 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004823 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004824 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004825 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004826 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004827 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004829 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004830 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004831 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004833 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004835 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004837 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004838 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004839 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004840 case CXCursor_SEHLeaveStmt:
4841 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004843 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004845 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004847 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004848 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004849 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004851 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004853 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004855 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004856 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004857 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004859 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004861 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004862 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004863 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004864 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004865 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004866 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004867 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004869 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004870 case CXCursor_PackedAttr:
4871 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004872 case CXCursor_PureAttr:
4873 return cxstring::createRef("attribute(pure)");
4874 case CXCursor_ConstAttr:
4875 return cxstring::createRef("attribute(const)");
4876 case CXCursor_NoDuplicateAttr:
4877 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00004878 case CXCursor_CUDAConstantAttr:
4879 return cxstring::createRef("attribute(constant)");
4880 case CXCursor_CUDADeviceAttr:
4881 return cxstring::createRef("attribute(device)");
4882 case CXCursor_CUDAGlobalAttr:
4883 return cxstring::createRef("attribute(global)");
4884 case CXCursor_CUDAHostAttr:
4885 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00004886 case CXCursor_CUDASharedAttr:
4887 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004888 case CXCursor_VisibilityAttr:
4889 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00004890 case CXCursor_DLLExport:
4891 return cxstring::createRef("attribute(dllexport)");
4892 case CXCursor_DLLImport:
4893 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004895 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004896 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004897 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004899 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004901 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00004902 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004903 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00004904 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004905 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004907 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004909 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004910 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004911 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004913 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00004914 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004915 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004916 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004917 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004919 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004921 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004923 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00004924 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004925 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00004926 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004927 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004929 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004931 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00004932 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004933 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004935 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004937 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004939 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004941 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004942 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004943 return cxstring::createRef("OMPParallelDirective");
4944 case CXCursor_OMPSimdDirective:
4945 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00004946 case CXCursor_OMPForDirective:
4947 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00004948 case CXCursor_OMPForSimdDirective:
4949 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004950 case CXCursor_OMPSectionsDirective:
4951 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004952 case CXCursor_OMPSectionDirective:
4953 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004954 case CXCursor_OMPSingleDirective:
4955 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00004956 case CXCursor_OMPMasterDirective:
4957 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004958 case CXCursor_OMPCriticalDirective:
4959 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00004960 case CXCursor_OMPParallelForDirective:
4961 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00004962 case CXCursor_OMPParallelForSimdDirective:
4963 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004964 case CXCursor_OMPParallelSectionsDirective:
4965 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004966 case CXCursor_OMPTaskDirective:
4967 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00004968 case CXCursor_OMPTaskyieldDirective:
4969 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004970 case CXCursor_OMPBarrierDirective:
4971 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00004972 case CXCursor_OMPTaskwaitDirective:
4973 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004974 case CXCursor_OMPTaskgroupDirective:
4975 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00004976 case CXCursor_OMPFlushDirective:
4977 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004978 case CXCursor_OMPOrderedDirective:
4979 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00004980 case CXCursor_OMPAtomicDirective:
4981 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004982 case CXCursor_OMPTargetDirective:
4983 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00004984 case CXCursor_OMPTargetDataDirective:
4985 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00004986 case CXCursor_OMPTargetEnterDataDirective:
4987 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00004988 case CXCursor_OMPTargetExitDataDirective:
4989 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004990 case CXCursor_OMPTargetParallelDirective:
4991 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004992 case CXCursor_OMPTargetParallelForDirective:
4993 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00004994 case CXCursor_OMPTargetUpdateDirective:
4995 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00004996 case CXCursor_OMPTeamsDirective:
4997 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004998 case CXCursor_OMPCancellationPointDirective:
4999 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005000 case CXCursor_OMPCancelDirective:
5001 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005002 case CXCursor_OMPTaskLoopDirective:
5003 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005004 case CXCursor_OMPTaskLoopSimdDirective:
5005 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005006 case CXCursor_OMPDistributeDirective:
5007 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005008 case CXCursor_OMPDistributeParallelForDirective:
5009 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005010 case CXCursor_OMPDistributeParallelForSimdDirective:
5011 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005012 case CXCursor_OMPDistributeSimdDirective:
5013 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005014 case CXCursor_OMPTargetParallelForSimdDirective:
5015 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005016 case CXCursor_OMPTargetSimdDirective:
5017 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005018 case CXCursor_OMPTeamsDistributeDirective:
5019 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005020 case CXCursor_OMPTeamsDistributeSimdDirective:
5021 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005022 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5023 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005024 case CXCursor_OMPTeamsDistributeParallelForDirective:
5025 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005026 case CXCursor_OMPTargetTeamsDirective:
5027 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005028 case CXCursor_OMPTargetTeamsDistributeDirective:
5029 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005030 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5031 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005032 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5033 return cxstring::createRef(
5034 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005035 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5036 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005037 case CXCursor_OverloadCandidate:
5038 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005039 case CXCursor_TypeAliasTemplateDecl:
5040 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005041 case CXCursor_StaticAssert:
5042 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005043 case CXCursor_FriendDecl:
5044 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 }
5046
5047 llvm_unreachable("Unhandled CXCursorKind");
5048}
5049
5050struct GetCursorData {
5051 SourceLocation TokenBeginLoc;
5052 bool PointsAtMacroArgExpansion;
5053 bool VisitedObjCPropertyImplDecl;
5054 SourceLocation VisitedDeclaratorDeclStartLoc;
5055 CXCursor &BestCursor;
5056
5057 GetCursorData(SourceManager &SM,
5058 SourceLocation tokenBegin, CXCursor &outputCursor)
5059 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5060 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5061 VisitedObjCPropertyImplDecl = false;
5062 }
5063};
5064
5065static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5066 CXCursor parent,
5067 CXClientData client_data) {
5068 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5069 CXCursor *BestCursor = &Data->BestCursor;
5070
5071 // If we point inside a macro argument we should provide info of what the
5072 // token is so use the actual cursor, don't replace it with a macro expansion
5073 // cursor.
5074 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5075 return CXChildVisit_Recurse;
5076
5077 if (clang_isDeclaration(cursor.kind)) {
5078 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005079 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5081 if (MD->isImplicit())
5082 return CXChildVisit_Break;
5083
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005084 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5086 // Check that when we have multiple @class references in the same line,
5087 // that later ones do not override the previous ones.
5088 // If we have:
5089 // @class Foo, Bar;
5090 // source ranges for both start at '@', so 'Bar' will end up overriding
5091 // 'Foo' even though the cursor location was at 'Foo'.
5092 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5093 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005094 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5096 if (PrevID != ID &&
5097 !PrevID->isThisDeclarationADefinition() &&
5098 !ID->isThisDeclarationADefinition())
5099 return CXChildVisit_Break;
5100 }
5101
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005102 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5104 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5105 // Check that when we have multiple declarators in the same line,
5106 // that later ones do not override the previous ones.
5107 // If we have:
5108 // int Foo, Bar;
5109 // source ranges for both start at 'int', so 'Bar' will end up overriding
5110 // 'Foo' even though the cursor location was at 'Foo'.
5111 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5112 return CXChildVisit_Break;
5113 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5114
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005115 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5117 (void)PropImp;
5118 // Check that when we have multiple @synthesize in the same line,
5119 // that later ones do not override the previous ones.
5120 // If we have:
5121 // @synthesize Foo, Bar;
5122 // source ranges for both start at '@', so 'Bar' will end up overriding
5123 // 'Foo' even though the cursor location was at 'Foo'.
5124 if (Data->VisitedObjCPropertyImplDecl)
5125 return CXChildVisit_Break;
5126 Data->VisitedObjCPropertyImplDecl = true;
5127 }
5128 }
5129
5130 if (clang_isExpression(cursor.kind) &&
5131 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005132 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 // Avoid having the cursor of an expression replace the declaration cursor
5134 // when the expression source range overlaps the declaration range.
5135 // This can happen for C++ constructor expressions whose range generally
5136 // include the variable declaration, e.g.:
5137 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5138 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5139 D->getLocation() == Data->TokenBeginLoc)
5140 return CXChildVisit_Break;
5141 }
5142 }
5143
5144 // If our current best cursor is the construction of a temporary object,
5145 // don't replace that cursor with a type reference, because we want
5146 // clang_getCursor() to point at the constructor.
5147 if (clang_isExpression(BestCursor->kind) &&
5148 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5149 cursor.kind == CXCursor_TypeRef) {
5150 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5151 // as having the actual point on the type reference.
5152 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5153 return CXChildVisit_Recurse;
5154 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005155
5156 // If we already have an Objective-C superclass reference, don't
5157 // update it further.
5158 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5159 return CXChildVisit_Break;
5160
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 *BestCursor = cursor;
5162 return CXChildVisit_Recurse;
5163}
5164
5165CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005166 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005167 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005169 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005170
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005171 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5173
5174 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5175 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5176
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005177 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 CXFile SearchFile;
5179 unsigned SearchLine, SearchColumn;
5180 CXFile ResultFile;
5181 unsigned ResultLine, ResultColumn;
5182 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5183 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5184 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005185
5186 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5187 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005188 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005189 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 SearchFileName = clang_getFileName(SearchFile);
5191 ResultFileName = clang_getFileName(ResultFile);
5192 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5193 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005194 *Log << llvm::format("(%s:%d:%d) = %s",
5195 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5196 clang_getCString(KindSpelling))
5197 << llvm::format("(%s:%d:%d):%s%s",
5198 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5199 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 clang_disposeString(SearchFileName);
5201 clang_disposeString(ResultFileName);
5202 clang_disposeString(KindSpelling);
5203 clang_disposeString(USR);
5204
5205 CXCursor Definition = clang_getCursorDefinition(Result);
5206 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5207 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5208 CXString DefinitionKindSpelling
5209 = clang_getCursorKindSpelling(Definition.kind);
5210 CXFile DefinitionFile;
5211 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005212 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005213 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005215 *Log << llvm::format(" -> %s(%s:%d:%d)",
5216 clang_getCString(DefinitionKindSpelling),
5217 clang_getCString(DefinitionFileName),
5218 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 clang_disposeString(DefinitionFileName);
5220 clang_disposeString(DefinitionKindSpelling);
5221 }
5222 }
5223
5224 return Result;
5225}
5226
5227CXCursor clang_getNullCursor(void) {
5228 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5229}
5230
5231unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005232 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5233 // can't set consistently. For example, when visiting a DeclStmt we will set
5234 // it but we don't set it on the result of clang_getCursorDefinition for
5235 // a reference of the same declaration.
5236 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5237 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5238 // to provide that kind of info.
5239 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005240 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005241 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005242 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005243
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 return X == Y;
5245}
5246
5247unsigned clang_hashCursor(CXCursor C) {
5248 unsigned Index = 0;
5249 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5250 Index = 1;
5251
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005252 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 std::make_pair(C.kind, C.data[Index]));
5254}
5255
5256unsigned clang_isInvalid(enum CXCursorKind K) {
5257 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5258}
5259
5260unsigned clang_isDeclaration(enum CXCursorKind K) {
5261 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5262 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5263}
5264
5265unsigned clang_isReference(enum CXCursorKind K) {
5266 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5267}
5268
5269unsigned clang_isExpression(enum CXCursorKind K) {
5270 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5271}
5272
5273unsigned clang_isStatement(enum CXCursorKind K) {
5274 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5275}
5276
5277unsigned clang_isAttribute(enum CXCursorKind K) {
5278 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5279}
5280
5281unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5282 return K == CXCursor_TranslationUnit;
5283}
5284
5285unsigned clang_isPreprocessing(enum CXCursorKind K) {
5286 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5287}
5288
5289unsigned clang_isUnexposed(enum CXCursorKind K) {
5290 switch (K) {
5291 case CXCursor_UnexposedDecl:
5292 case CXCursor_UnexposedExpr:
5293 case CXCursor_UnexposedStmt:
5294 case CXCursor_UnexposedAttr:
5295 return true;
5296 default:
5297 return false;
5298 }
5299}
5300
5301CXCursorKind clang_getCursorKind(CXCursor C) {
5302 return C.kind;
5303}
5304
5305CXSourceLocation clang_getCursorLocation(CXCursor C) {
5306 if (clang_isReference(C.kind)) {
5307 switch (C.kind) {
5308 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005309 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 = getCursorObjCSuperClassRef(C);
5311 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5312 }
5313
5314 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005315 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 = getCursorObjCProtocolRef(C);
5317 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5318 }
5319
5320 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005321 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 = getCursorObjCClassRef(C);
5323 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5324 }
5325
5326 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005327 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005328 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5329 }
5330
5331 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005332 std::pair<const TemplateDecl *, SourceLocation> P =
5333 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5335 }
5336
5337 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005338 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5340 }
5341
5342 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005343 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5345 }
5346
5347 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005348 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5350 }
5351
5352 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005353 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 if (!BaseSpec)
5355 return clang_getNullLocation();
5356
5357 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5358 return cxloc::translateSourceLocation(getCursorContext(C),
5359 TSInfo->getTypeLoc().getBeginLoc());
5360
5361 return cxloc::translateSourceLocation(getCursorContext(C),
5362 BaseSpec->getLocStart());
5363 }
5364
5365 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005366 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5368 }
5369
5370 case CXCursor_OverloadedDeclRef:
5371 return cxloc::translateSourceLocation(getCursorContext(C),
5372 getCursorOverloadedDeclRef(C).second);
5373
5374 default:
5375 // FIXME: Need a way to enumerate all non-reference cases.
5376 llvm_unreachable("Missed a reference kind");
5377 }
5378 }
5379
5380 if (clang_isExpression(C.kind))
5381 return cxloc::translateSourceLocation(getCursorContext(C),
5382 getLocationFromExpr(getCursorExpr(C)));
5383
5384 if (clang_isStatement(C.kind))
5385 return cxloc::translateSourceLocation(getCursorContext(C),
5386 getCursorStmt(C)->getLocStart());
5387
5388 if (C.kind == CXCursor_PreprocessingDirective) {
5389 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5390 return cxloc::translateSourceLocation(getCursorContext(C), L);
5391 }
5392
5393 if (C.kind == CXCursor_MacroExpansion) {
5394 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005395 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005396 return cxloc::translateSourceLocation(getCursorContext(C), L);
5397 }
5398
5399 if (C.kind == CXCursor_MacroDefinition) {
5400 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5401 return cxloc::translateSourceLocation(getCursorContext(C), L);
5402 }
5403
5404 if (C.kind == CXCursor_InclusionDirective) {
5405 SourceLocation L
5406 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5407 return cxloc::translateSourceLocation(getCursorContext(C), L);
5408 }
5409
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005410 if (clang_isAttribute(C.kind)) {
5411 SourceLocation L
5412 = cxcursor::getCursorAttr(C)->getLocation();
5413 return cxloc::translateSourceLocation(getCursorContext(C), L);
5414 }
5415
Guy Benyei11169dd2012-12-18 14:30:41 +00005416 if (!clang_isDeclaration(C.kind))
5417 return clang_getNullLocation();
5418
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005419 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005420 if (!D)
5421 return clang_getNullLocation();
5422
5423 SourceLocation Loc = D->getLocation();
5424 // FIXME: Multiple variables declared in a single declaration
5425 // currently lack the information needed to correctly determine their
5426 // ranges when accounting for the type-specifier. We use context
5427 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5428 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005429 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 if (!cxcursor::isFirstInDeclGroup(C))
5431 Loc = VD->getLocation();
5432 }
5433
5434 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005435 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005436 Loc = MD->getSelectorStartLoc();
5437
5438 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5439}
5440
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005441} // end extern "C"
5442
Guy Benyei11169dd2012-12-18 14:30:41 +00005443CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5444 assert(TU);
5445
5446 // Guard against an invalid SourceLocation, or we may assert in one
5447 // of the following calls.
5448 if (SLoc.isInvalid())
5449 return clang_getNullCursor();
5450
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005451 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005452
5453 // Translate the given source location to make it point at the beginning of
5454 // the token under the cursor.
5455 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5456 CXXUnit->getASTContext().getLangOpts());
5457
5458 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5459 if (SLoc.isValid()) {
5460 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5461 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5462 /*VisitPreprocessorLast=*/true,
5463 /*VisitIncludedEntities=*/false,
5464 SourceLocation(SLoc));
5465 CursorVis.visitFileRegion();
5466 }
5467
5468 return Result;
5469}
5470
5471static SourceRange getRawCursorExtent(CXCursor C) {
5472 if (clang_isReference(C.kind)) {
5473 switch (C.kind) {
5474 case CXCursor_ObjCSuperClassRef:
5475 return getCursorObjCSuperClassRef(C).second;
5476
5477 case CXCursor_ObjCProtocolRef:
5478 return getCursorObjCProtocolRef(C).second;
5479
5480 case CXCursor_ObjCClassRef:
5481 return getCursorObjCClassRef(C).second;
5482
5483 case CXCursor_TypeRef:
5484 return getCursorTypeRef(C).second;
5485
5486 case CXCursor_TemplateRef:
5487 return getCursorTemplateRef(C).second;
5488
5489 case CXCursor_NamespaceRef:
5490 return getCursorNamespaceRef(C).second;
5491
5492 case CXCursor_MemberRef:
5493 return getCursorMemberRef(C).second;
5494
5495 case CXCursor_CXXBaseSpecifier:
5496 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5497
5498 case CXCursor_LabelRef:
5499 return getCursorLabelRef(C).second;
5500
5501 case CXCursor_OverloadedDeclRef:
5502 return getCursorOverloadedDeclRef(C).second;
5503
5504 case CXCursor_VariableRef:
5505 return getCursorVariableRef(C).second;
5506
5507 default:
5508 // FIXME: Need a way to enumerate all non-reference cases.
5509 llvm_unreachable("Missed a reference kind");
5510 }
5511 }
5512
5513 if (clang_isExpression(C.kind))
5514 return getCursorExpr(C)->getSourceRange();
5515
5516 if (clang_isStatement(C.kind))
5517 return getCursorStmt(C)->getSourceRange();
5518
5519 if (clang_isAttribute(C.kind))
5520 return getCursorAttr(C)->getRange();
5521
5522 if (C.kind == CXCursor_PreprocessingDirective)
5523 return cxcursor::getCursorPreprocessingDirective(C);
5524
5525 if (C.kind == CXCursor_MacroExpansion) {
5526 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005527 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005528 return TU->mapRangeFromPreamble(Range);
5529 }
5530
5531 if (C.kind == CXCursor_MacroDefinition) {
5532 ASTUnit *TU = getCursorASTUnit(C);
5533 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5534 return TU->mapRangeFromPreamble(Range);
5535 }
5536
5537 if (C.kind == CXCursor_InclusionDirective) {
5538 ASTUnit *TU = getCursorASTUnit(C);
5539 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5540 return TU->mapRangeFromPreamble(Range);
5541 }
5542
5543 if (C.kind == CXCursor_TranslationUnit) {
5544 ASTUnit *TU = getCursorASTUnit(C);
5545 FileID MainID = TU->getSourceManager().getMainFileID();
5546 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5547 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5548 return SourceRange(Start, End);
5549 }
5550
5551 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005552 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005553 if (!D)
5554 return SourceRange();
5555
5556 SourceRange R = D->getSourceRange();
5557 // FIXME: Multiple variables declared in a single declaration
5558 // currently lack the information needed to correctly determine their
5559 // ranges when accounting for the type-specifier. We use context
5560 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5561 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005562 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005563 if (!cxcursor::isFirstInDeclGroup(C))
5564 R.setBegin(VD->getLocation());
5565 }
5566 return R;
5567 }
5568 return SourceRange();
5569}
5570
5571/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5572/// the decl-specifier-seq for declarations.
5573static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5574 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005575 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 if (!D)
5577 return SourceRange();
5578
5579 SourceRange R = D->getSourceRange();
5580
5581 // Adjust the start of the location for declarations preceded by
5582 // declaration specifiers.
5583 SourceLocation StartLoc;
5584 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5585 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5586 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005587 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5589 StartLoc = TI->getTypeLoc().getLocStart();
5590 }
5591
5592 if (StartLoc.isValid() && R.getBegin().isValid() &&
5593 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5594 R.setBegin(StartLoc);
5595
5596 // FIXME: Multiple variables declared in a single declaration
5597 // currently lack the information needed to correctly determine their
5598 // ranges when accounting for the type-specifier. We use context
5599 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5600 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005601 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005602 if (!cxcursor::isFirstInDeclGroup(C))
5603 R.setBegin(VD->getLocation());
5604 }
5605
5606 return R;
5607 }
5608
5609 return getRawCursorExtent(C);
5610}
5611
Guy Benyei11169dd2012-12-18 14:30:41 +00005612CXSourceRange clang_getCursorExtent(CXCursor C) {
5613 SourceRange R = getRawCursorExtent(C);
5614 if (R.isInvalid())
5615 return clang_getNullRange();
5616
5617 return cxloc::translateSourceRange(getCursorContext(C), R);
5618}
5619
5620CXCursor clang_getCursorReferenced(CXCursor C) {
5621 if (clang_isInvalid(C.kind))
5622 return clang_getNullCursor();
5623
5624 CXTranslationUnit tu = getCursorTU(C);
5625 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005626 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005627 if (!D)
5628 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005629 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005630 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005631 if (const ObjCPropertyImplDecl *PropImpl =
5632 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005633 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5634 return MakeCXCursor(Property, tu);
5635
5636 return C;
5637 }
5638
5639 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005640 const Expr *E = getCursorExpr(C);
5641 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005642 if (D) {
5643 CXCursor declCursor = MakeCXCursor(D, tu);
5644 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5645 declCursor);
5646 return declCursor;
5647 }
5648
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005649 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005650 return MakeCursorOverloadedDeclRef(Ovl, tu);
5651
5652 return clang_getNullCursor();
5653 }
5654
5655 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005656 const Stmt *S = getCursorStmt(C);
5657 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 if (LabelDecl *label = Goto->getLabel())
5659 if (LabelStmt *labelS = label->getStmt())
5660 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5661
5662 return clang_getNullCursor();
5663 }
Richard Smith66a81862015-05-04 02:25:31 +00005664
Guy Benyei11169dd2012-12-18 14:30:41 +00005665 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005666 if (const MacroDefinitionRecord *Def =
5667 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005668 return MakeMacroDefinitionCursor(Def, tu);
5669 }
5670
5671 if (!clang_isReference(C.kind))
5672 return clang_getNullCursor();
5673
5674 switch (C.kind) {
5675 case CXCursor_ObjCSuperClassRef:
5676 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5677
5678 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005679 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5680 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005681 return MakeCXCursor(Def, tu);
5682
5683 return MakeCXCursor(Prot, tu);
5684 }
5685
5686 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005687 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5688 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 return MakeCXCursor(Def, tu);
5690
5691 return MakeCXCursor(Class, tu);
5692 }
5693
5694 case CXCursor_TypeRef:
5695 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5696
5697 case CXCursor_TemplateRef:
5698 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5699
5700 case CXCursor_NamespaceRef:
5701 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5702
5703 case CXCursor_MemberRef:
5704 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5705
5706 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005707 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005708 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5709 tu ));
5710 }
5711
5712 case CXCursor_LabelRef:
5713 // FIXME: We end up faking the "parent" declaration here because we
5714 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005715 return MakeCXCursor(getCursorLabelRef(C).first,
5716 cxtu::getASTUnit(tu)->getASTContext()
5717 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005718 tu);
5719
5720 case CXCursor_OverloadedDeclRef:
5721 return C;
5722
5723 case CXCursor_VariableRef:
5724 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5725
5726 default:
5727 // We would prefer to enumerate all non-reference cursor kinds here.
5728 llvm_unreachable("Unhandled reference cursor kind");
5729 }
5730}
5731
5732CXCursor clang_getCursorDefinition(CXCursor C) {
5733 if (clang_isInvalid(C.kind))
5734 return clang_getNullCursor();
5735
5736 CXTranslationUnit TU = getCursorTU(C);
5737
5738 bool WasReference = false;
5739 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5740 C = clang_getCursorReferenced(C);
5741 WasReference = true;
5742 }
5743
5744 if (C.kind == CXCursor_MacroExpansion)
5745 return clang_getCursorReferenced(C);
5746
5747 if (!clang_isDeclaration(C.kind))
5748 return clang_getNullCursor();
5749
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005750 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005751 if (!D)
5752 return clang_getNullCursor();
5753
5754 switch (D->getKind()) {
5755 // Declaration kinds that don't really separate the notions of
5756 // declaration and definition.
5757 case Decl::Namespace:
5758 case Decl::Typedef:
5759 case Decl::TypeAlias:
5760 case Decl::TypeAliasTemplate:
5761 case Decl::TemplateTypeParm:
5762 case Decl::EnumConstant:
5763 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005764 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005765 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005766 case Decl::IndirectField:
5767 case Decl::ObjCIvar:
5768 case Decl::ObjCAtDefsField:
5769 case Decl::ImplicitParam:
5770 case Decl::ParmVar:
5771 case Decl::NonTypeTemplateParm:
5772 case Decl::TemplateTemplateParm:
5773 case Decl::ObjCCategoryImpl:
5774 case Decl::ObjCImplementation:
5775 case Decl::AccessSpec:
5776 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005777 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005778 case Decl::ObjCPropertyImpl:
5779 case Decl::FileScopeAsm:
5780 case Decl::StaticAssert:
5781 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005782 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005783 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005784 case Decl::Label: // FIXME: Is this right??
5785 case Decl::ClassScopeFunctionSpecialization:
5786 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005787 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005788 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005789 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005790 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005791 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005792 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005793 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005794 return C;
5795
5796 // Declaration kinds that don't make any sense here, but are
5797 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005798 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005799 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005800 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005801 break;
5802
5803 // Declaration kinds for which the definition is not resolvable.
5804 case Decl::UnresolvedUsingTypename:
5805 case Decl::UnresolvedUsingValue:
5806 break;
5807
5808 case Decl::UsingDirective:
5809 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5810 TU);
5811
5812 case Decl::NamespaceAlias:
5813 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5814
5815 case Decl::Enum:
5816 case Decl::Record:
5817 case Decl::CXXRecord:
5818 case Decl::ClassTemplateSpecialization:
5819 case Decl::ClassTemplatePartialSpecialization:
5820 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5821 return MakeCXCursor(Def, TU);
5822 return clang_getNullCursor();
5823
5824 case Decl::Function:
5825 case Decl::CXXMethod:
5826 case Decl::CXXConstructor:
5827 case Decl::CXXDestructor:
5828 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005829 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005830 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005831 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005832 return clang_getNullCursor();
5833 }
5834
Larisse Voufo39a1e502013-08-06 01:03:05 +00005835 case Decl::Var:
5836 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005837 case Decl::VarTemplatePartialSpecialization:
5838 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005839 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005840 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 return MakeCXCursor(Def, TU);
5842 return clang_getNullCursor();
5843 }
5844
5845 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005846 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005847 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5848 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5849 return clang_getNullCursor();
5850 }
5851
5852 case Decl::ClassTemplate: {
5853 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5854 ->getDefinition())
5855 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5856 TU);
5857 return clang_getNullCursor();
5858 }
5859
Larisse Voufo39a1e502013-08-06 01:03:05 +00005860 case Decl::VarTemplate: {
5861 if (VarDecl *Def =
5862 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5863 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5864 return clang_getNullCursor();
5865 }
5866
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 case Decl::Using:
5868 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5869 D->getLocation(), TU);
5870
5871 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005872 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 return clang_getCursorDefinition(
5874 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5875 TU));
5876
5877 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005878 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005879 if (Method->isThisDeclarationADefinition())
5880 return C;
5881
5882 // Dig out the method definition in the associated
5883 // @implementation, if we have it.
5884 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005885 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005886 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5887 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5888 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5889 Method->isInstanceMethod()))
5890 if (Def->isThisDeclarationADefinition())
5891 return MakeCXCursor(Def, TU);
5892
5893 return clang_getNullCursor();
5894 }
5895
5896 case Decl::ObjCCategory:
5897 if (ObjCCategoryImplDecl *Impl
5898 = cast<ObjCCategoryDecl>(D)->getImplementation())
5899 return MakeCXCursor(Impl, TU);
5900 return clang_getNullCursor();
5901
5902 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005903 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 return MakeCXCursor(Def, TU);
5905 return clang_getNullCursor();
5906
5907 case Decl::ObjCInterface: {
5908 // There are two notions of a "definition" for an Objective-C
5909 // class: the interface and its implementation. When we resolved a
5910 // reference to an Objective-C class, produce the @interface as
5911 // the definition; when we were provided with the interface,
5912 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005913 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00005914 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005915 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005916 return MakeCXCursor(Def, TU);
5917 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5918 return MakeCXCursor(Impl, TU);
5919 return clang_getNullCursor();
5920 }
5921
5922 case Decl::ObjCProperty:
5923 // FIXME: We don't really know where to find the
5924 // ObjCPropertyImplDecls that implement this property.
5925 return clang_getNullCursor();
5926
5927 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005928 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00005929 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005930 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005931 return MakeCXCursor(Def, TU);
5932
5933 return clang_getNullCursor();
5934
5935 case Decl::Friend:
5936 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5937 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5938 return clang_getNullCursor();
5939
5940 case Decl::FriendTemplate:
5941 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5942 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5943 return clang_getNullCursor();
5944 }
5945
5946 return clang_getNullCursor();
5947}
5948
5949unsigned clang_isCursorDefinition(CXCursor C) {
5950 if (!clang_isDeclaration(C.kind))
5951 return 0;
5952
5953 return clang_getCursorDefinition(C) == C;
5954}
5955
5956CXCursor clang_getCanonicalCursor(CXCursor C) {
5957 if (!clang_isDeclaration(C.kind))
5958 return C;
5959
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005960 if (const Decl *D = getCursorDecl(C)) {
5961 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005962 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5963 return MakeCXCursor(CatD, getCursorTU(C));
5964
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005965 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5966 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00005967 return MakeCXCursor(IFD, getCursorTU(C));
5968
5969 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5970 }
5971
5972 return C;
5973}
5974
5975int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5976 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5977}
5978
5979unsigned clang_getNumOverloadedDecls(CXCursor C) {
5980 if (C.kind != CXCursor_OverloadedDeclRef)
5981 return 0;
5982
5983 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005984 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00005985 return E->getNumDecls();
5986
5987 if (OverloadedTemplateStorage *S
5988 = Storage.dyn_cast<OverloadedTemplateStorage*>())
5989 return S->size();
5990
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005991 const Decl *D = Storage.get<const Decl *>();
5992 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005993 return Using->shadow_size();
5994
5995 return 0;
5996}
5997
5998CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5999 if (cursor.kind != CXCursor_OverloadedDeclRef)
6000 return clang_getNullCursor();
6001
6002 if (index >= clang_getNumOverloadedDecls(cursor))
6003 return clang_getNullCursor();
6004
6005 CXTranslationUnit TU = getCursorTU(cursor);
6006 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006007 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006008 return MakeCXCursor(E->decls_begin()[index], TU);
6009
6010 if (OverloadedTemplateStorage *S
6011 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6012 return MakeCXCursor(S->begin()[index], TU);
6013
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006014 const Decl *D = Storage.get<const Decl *>();
6015 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006016 // FIXME: This is, unfortunately, linear time.
6017 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6018 std::advance(Pos, index);
6019 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6020 }
6021
6022 return clang_getNullCursor();
6023}
6024
6025void clang_getDefinitionSpellingAndExtent(CXCursor C,
6026 const char **startBuf,
6027 const char **endBuf,
6028 unsigned *startLine,
6029 unsigned *startColumn,
6030 unsigned *endLine,
6031 unsigned *endColumn) {
6032 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006033 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006034 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6035
6036 SourceManager &SM = FD->getASTContext().getSourceManager();
6037 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6038 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6039 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6040 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6041 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6042 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6043}
6044
6045
6046CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6047 unsigned PieceIndex) {
6048 RefNamePieces Pieces;
6049
6050 switch (C.kind) {
6051 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006052 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006053 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6054 E->getQualifierLoc().getSourceRange());
6055 break;
6056
6057 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006058 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6059 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6060 Pieces =
6061 buildPieces(NameFlags, false, E->getNameInfo(),
6062 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6063 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006064 break;
6065
6066 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006067 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006068 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006069 const Expr *Callee = OCE->getCallee();
6070 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006071 Callee = ICE->getSubExpr();
6072
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006073 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6075 DRE->getQualifierLoc().getSourceRange());
6076 }
6077 break;
6078
6079 default:
6080 break;
6081 }
6082
6083 if (Pieces.empty()) {
6084 if (PieceIndex == 0)
6085 return clang_getCursorExtent(C);
6086 } else if (PieceIndex < Pieces.size()) {
6087 SourceRange R = Pieces[PieceIndex];
6088 if (R.isValid())
6089 return cxloc::translateSourceRange(getCursorContext(C), R);
6090 }
6091
6092 return clang_getNullRange();
6093}
6094
6095void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006096 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6097 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006098}
6099
6100void clang_executeOnThread(void (*fn)(void*), void *user_data,
6101 unsigned stack_size) {
6102 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6103}
6104
Guy Benyei11169dd2012-12-18 14:30:41 +00006105//===----------------------------------------------------------------------===//
6106// Token-based Operations.
6107//===----------------------------------------------------------------------===//
6108
6109/* CXToken layout:
6110 * int_data[0]: a CXTokenKind
6111 * int_data[1]: starting token location
6112 * int_data[2]: token length
6113 * int_data[3]: reserved
6114 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6115 * otherwise unused.
6116 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006117CXTokenKind clang_getTokenKind(CXToken CXTok) {
6118 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6119}
6120
6121CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6122 switch (clang_getTokenKind(CXTok)) {
6123 case CXToken_Identifier:
6124 case CXToken_Keyword:
6125 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006126 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 ->getNameStart());
6128
6129 case CXToken_Literal: {
6130 // We have stashed the starting pointer in the ptr_data field. Use it.
6131 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006132 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006133 }
6134
6135 case CXToken_Punctuation:
6136 case CXToken_Comment:
6137 break;
6138 }
6139
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006140 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006141 LOG_BAD_TU(TU);
6142 return cxstring::createEmpty();
6143 }
6144
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 // We have to find the starting buffer pointer the hard way, by
6146 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006147 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006148 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006149 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006150
6151 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6152 std::pair<FileID, unsigned> LocInfo
6153 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6154 bool Invalid = false;
6155 StringRef Buffer
6156 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6157 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006158 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006159
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006160 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006161}
6162
6163CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006164 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006165 LOG_BAD_TU(TU);
6166 return clang_getNullLocation();
6167 }
6168
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006169 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 if (!CXXUnit)
6171 return clang_getNullLocation();
6172
6173 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6174 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6175}
6176
6177CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006178 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006179 LOG_BAD_TU(TU);
6180 return clang_getNullRange();
6181 }
6182
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006183 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 if (!CXXUnit)
6185 return clang_getNullRange();
6186
6187 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6188 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6189}
6190
6191static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6192 SmallVectorImpl<CXToken> &CXTokens) {
6193 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6194 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006195 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006197 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006198
6199 // Cannot tokenize across files.
6200 if (BeginLocInfo.first != EndLocInfo.first)
6201 return;
6202
6203 // Create a lexer
6204 bool Invalid = false;
6205 StringRef Buffer
6206 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6207 if (Invalid)
6208 return;
6209
6210 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6211 CXXUnit->getASTContext().getLangOpts(),
6212 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6213 Lex.SetCommentRetentionState(true);
6214
6215 // Lex tokens until we hit the end of the range.
6216 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6217 Token Tok;
6218 bool previousWasAt = false;
6219 do {
6220 // Lex the next token
6221 Lex.LexFromRawLexer(Tok);
6222 if (Tok.is(tok::eof))
6223 break;
6224
6225 // Initialize the CXToken.
6226 CXToken CXTok;
6227
6228 // - Common fields
6229 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6230 CXTok.int_data[2] = Tok.getLength();
6231 CXTok.int_data[3] = 0;
6232
6233 // - Kind-specific fields
6234 if (Tok.isLiteral()) {
6235 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006236 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 } else if (Tok.is(tok::raw_identifier)) {
6238 // Lookup the identifier to determine whether we have a keyword.
6239 IdentifierInfo *II
6240 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6241
6242 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6243 CXTok.int_data[0] = CXToken_Keyword;
6244 }
6245 else {
6246 CXTok.int_data[0] = Tok.is(tok::identifier)
6247 ? CXToken_Identifier
6248 : CXToken_Keyword;
6249 }
6250 CXTok.ptr_data = II;
6251 } else if (Tok.is(tok::comment)) {
6252 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006253 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006254 } else {
6255 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006256 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006257 }
6258 CXTokens.push_back(CXTok);
6259 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006260 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006261}
6262
6263void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6264 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006265 LOG_FUNC_SECTION {
6266 *Log << TU << ' ' << Range;
6267 }
6268
Guy Benyei11169dd2012-12-18 14:30:41 +00006269 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006270 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 if (NumTokens)
6272 *NumTokens = 0;
6273
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006274 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006275 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006276 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006277 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006278
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006279 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006280 if (!CXXUnit || !Tokens || !NumTokens)
6281 return;
6282
6283 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6284
6285 SourceRange R = cxloc::translateCXSourceRange(Range);
6286 if (R.isInvalid())
6287 return;
6288
6289 SmallVector<CXToken, 32> CXTokens;
6290 getTokens(CXXUnit, R, CXTokens);
6291
6292 if (CXTokens.empty())
6293 return;
6294
6295 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6296 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6297 *NumTokens = CXTokens.size();
6298}
6299
6300void clang_disposeTokens(CXTranslationUnit TU,
6301 CXToken *Tokens, unsigned NumTokens) {
6302 free(Tokens);
6303}
6304
Guy Benyei11169dd2012-12-18 14:30:41 +00006305//===----------------------------------------------------------------------===//
6306// Token annotation APIs.
6307//===----------------------------------------------------------------------===//
6308
Guy Benyei11169dd2012-12-18 14:30:41 +00006309static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6310 CXCursor parent,
6311 CXClientData client_data);
6312static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6313 CXClientData client_data);
6314
6315namespace {
6316class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006317 CXToken *Tokens;
6318 CXCursor *Cursors;
6319 unsigned NumTokens;
6320 unsigned TokIdx;
6321 unsigned PreprocessingTokIdx;
6322 CursorVisitor AnnotateVis;
6323 SourceManager &SrcMgr;
6324 bool HasContextSensitiveKeywords;
6325
6326 struct PostChildrenInfo {
6327 CXCursor Cursor;
6328 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006329 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 unsigned BeforeChildrenTokenIdx;
6331 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006332 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006333
6334 CXToken &getTok(unsigned Idx) {
6335 assert(Idx < NumTokens);
6336 return Tokens[Idx];
6337 }
6338 const CXToken &getTok(unsigned Idx) const {
6339 assert(Idx < NumTokens);
6340 return Tokens[Idx];
6341 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006342 bool MoreTokens() const { return TokIdx < NumTokens; }
6343 unsigned NextToken() const { return TokIdx; }
6344 void AdvanceToken() { ++TokIdx; }
6345 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006346 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 }
6348 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006349 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006350 }
6351 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006352 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 }
6354
6355 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006356 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006357 SourceRange);
6358
6359public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006360 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006361 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006362 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006363 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006364 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006365 AnnotateTokensVisitor, this,
6366 /*VisitPreprocessorLast=*/true,
6367 /*VisitIncludedEntities=*/false,
6368 RegionOfInterest,
6369 /*VisitDeclsOnly=*/false,
6370 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006371 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 HasContextSensitiveKeywords(false) { }
6373
6374 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6375 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6376 bool postVisitChildren(CXCursor cursor);
6377 void AnnotateTokens();
6378
6379 /// \brief Determine whether the annotator saw any cursors that have
6380 /// context-sensitive keywords.
6381 bool hasContextSensitiveKeywords() const {
6382 return HasContextSensitiveKeywords;
6383 }
6384
6385 ~AnnotateTokensWorker() {
6386 assert(PostChildrenInfos.empty());
6387 }
6388};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006389}
Guy Benyei11169dd2012-12-18 14:30:41 +00006390
6391void AnnotateTokensWorker::AnnotateTokens() {
6392 // Walk the AST within the region of interest, annotating tokens
6393 // along the way.
6394 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006395}
Guy Benyei11169dd2012-12-18 14:30:41 +00006396
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006397static inline void updateCursorAnnotation(CXCursor &Cursor,
6398 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006399 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006400 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006401 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006402}
6403
6404/// \brief It annotates and advances tokens with a cursor until the comparison
6405//// between the cursor location and the source range is the same as
6406/// \arg compResult.
6407///
6408/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6409/// Pass RangeOverlap to annotate tokens inside a range.
6410void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6411 RangeComparisonResult compResult,
6412 SourceRange range) {
6413 while (MoreTokens()) {
6414 const unsigned I = NextToken();
6415 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006416 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6417 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006418
6419 SourceLocation TokLoc = GetTokenLoc(I);
6420 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006421 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 AdvanceToken();
6423 continue;
6424 }
6425 break;
6426 }
6427}
6428
6429/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006430/// \returns true if it advanced beyond all macro tokens, false otherwise.
6431bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 CXCursor updateC,
6433 RangeComparisonResult compResult,
6434 SourceRange range) {
6435 assert(MoreTokens());
6436 assert(isFunctionMacroToken(NextToken()) &&
6437 "Should be called only for macro arg tokens");
6438
6439 // This works differently than annotateAndAdvanceTokens; because expanded
6440 // macro arguments can have arbitrary translation-unit source order, we do not
6441 // advance the token index one by one until a token fails the range test.
6442 // We only advance once past all of the macro arg tokens if all of them
6443 // pass the range test. If one of them fails we keep the token index pointing
6444 // at the start of the macro arg tokens so that the failing token will be
6445 // annotated by a subsequent annotation try.
6446
6447 bool atLeastOneCompFail = false;
6448
6449 unsigned I = NextToken();
6450 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6451 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6452 if (TokLoc.isFileID())
6453 continue; // not macro arg token, it's parens or comma.
6454 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6455 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6456 Cursors[I] = updateC;
6457 } else
6458 atLeastOneCompFail = true;
6459 }
6460
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006461 if (atLeastOneCompFail)
6462 return false;
6463
6464 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6465 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006466}
6467
6468enum CXChildVisitResult
6469AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006470 SourceRange cursorRange = getRawCursorExtent(cursor);
6471 if (cursorRange.isInvalid())
6472 return CXChildVisit_Recurse;
6473
6474 if (!HasContextSensitiveKeywords) {
6475 // Objective-C properties can have context-sensitive keywords.
6476 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006477 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006478 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6479 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6480 }
6481 // Objective-C methods can have context-sensitive keywords.
6482 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6483 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006484 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6486 if (Method->getObjCDeclQualifier())
6487 HasContextSensitiveKeywords = true;
6488 else {
David Majnemer59f77922016-06-24 04:05:48 +00006489 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006490 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 HasContextSensitiveKeywords = true;
6492 break;
6493 }
6494 }
6495 }
6496 }
6497 }
6498 // C++ methods can have context-sensitive keywords.
6499 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006500 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006501 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6502 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6503 HasContextSensitiveKeywords = true;
6504 }
6505 }
6506 // C++ classes can have context-sensitive keywords.
6507 else if (cursor.kind == CXCursor_StructDecl ||
6508 cursor.kind == CXCursor_ClassDecl ||
6509 cursor.kind == CXCursor_ClassTemplate ||
6510 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006511 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 if (D->hasAttr<FinalAttr>())
6513 HasContextSensitiveKeywords = true;
6514 }
6515 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006516
6517 // Don't override a property annotation with its getter/setter method.
6518 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6519 parent.kind == CXCursor_ObjCPropertyDecl)
6520 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006521
6522 if (clang_isPreprocessing(cursor.kind)) {
6523 // Items in the preprocessing record are kept separate from items in
6524 // declarations, so we keep a separate token index.
6525 unsigned SavedTokIdx = TokIdx;
6526 TokIdx = PreprocessingTokIdx;
6527
6528 // Skip tokens up until we catch up to the beginning of the preprocessing
6529 // entry.
6530 while (MoreTokens()) {
6531 const unsigned I = NextToken();
6532 SourceLocation TokLoc = GetTokenLoc(I);
6533 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6534 case RangeBefore:
6535 AdvanceToken();
6536 continue;
6537 case RangeAfter:
6538 case RangeOverlap:
6539 break;
6540 }
6541 break;
6542 }
6543
6544 // Look at all of the tokens within this range.
6545 while (MoreTokens()) {
6546 const unsigned I = NextToken();
6547 SourceLocation TokLoc = GetTokenLoc(I);
6548 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6549 case RangeBefore:
6550 llvm_unreachable("Infeasible");
6551 case RangeAfter:
6552 break;
6553 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006554 // For macro expansions, just note where the beginning of the macro
6555 // expansion occurs.
6556 if (cursor.kind == CXCursor_MacroExpansion) {
6557 if (TokLoc == cursorRange.getBegin())
6558 Cursors[I] = cursor;
6559 AdvanceToken();
6560 break;
6561 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006562 // We may have already annotated macro names inside macro definitions.
6563 if (Cursors[I].kind != CXCursor_MacroExpansion)
6564 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006566 continue;
6567 }
6568 break;
6569 }
6570
6571 // Save the preprocessing token index; restore the non-preprocessing
6572 // token index.
6573 PreprocessingTokIdx = TokIdx;
6574 TokIdx = SavedTokIdx;
6575 return CXChildVisit_Recurse;
6576 }
6577
6578 if (cursorRange.isInvalid())
6579 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006580
6581 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 const enum CXCursorKind K = clang_getCursorKind(parent);
6584 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006585 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6586 // Attributes are annotated out-of-order, skip tokens until we reach it.
6587 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006588 ? clang_getNullCursor() : parent;
6589
6590 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6591
6592 // Avoid having the cursor of an expression "overwrite" the annotation of the
6593 // variable declaration that it belongs to.
6594 // This can happen for C++ constructor expressions whose range generally
6595 // include the variable declaration, e.g.:
6596 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006597 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006598 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006599 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006600 const unsigned I = NextToken();
6601 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6602 E->getLocStart() == D->getLocation() &&
6603 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006604 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 AdvanceToken();
6606 }
6607 }
6608 }
6609
6610 // Before recursing into the children keep some state that we are going
6611 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6612 // extra work after the child nodes are visited.
6613 // Note that we don't call VisitChildren here to avoid traversing statements
6614 // code-recursively which can blow the stack.
6615
6616 PostChildrenInfo Info;
6617 Info.Cursor = cursor;
6618 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006619 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006620 Info.BeforeChildrenTokenIdx = NextToken();
6621 PostChildrenInfos.push_back(Info);
6622
6623 return CXChildVisit_Recurse;
6624}
6625
6626bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6627 if (PostChildrenInfos.empty())
6628 return false;
6629 const PostChildrenInfo &Info = PostChildrenInfos.back();
6630 if (!clang_equalCursors(Info.Cursor, cursor))
6631 return false;
6632
6633 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6634 const unsigned AfterChildren = NextToken();
6635 SourceRange cursorRange = Info.CursorRange;
6636
6637 // Scan the tokens that are at the end of the cursor, but are not captured
6638 // but the child cursors.
6639 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6640
6641 // Scan the tokens that are at the beginning of the cursor, but are not
6642 // capture by the child cursors.
6643 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6644 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6645 break;
6646
6647 Cursors[I] = cursor;
6648 }
6649
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006650 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6651 // encountered the attribute cursor.
6652 if (clang_isAttribute(cursor.kind))
6653 TokIdx = Info.BeforeReachingCursorIdx;
6654
Guy Benyei11169dd2012-12-18 14:30:41 +00006655 PostChildrenInfos.pop_back();
6656 return false;
6657}
6658
6659static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6660 CXCursor parent,
6661 CXClientData client_data) {
6662 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6663}
6664
6665static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6666 CXClientData client_data) {
6667 return static_cast<AnnotateTokensWorker*>(client_data)->
6668 postVisitChildren(cursor);
6669}
6670
6671namespace {
6672
6673/// \brief Uses the macro expansions in the preprocessing record to find
6674/// and mark tokens that are macro arguments. This info is used by the
6675/// AnnotateTokensWorker.
6676class MarkMacroArgTokensVisitor {
6677 SourceManager &SM;
6678 CXToken *Tokens;
6679 unsigned NumTokens;
6680 unsigned CurIdx;
6681
6682public:
6683 MarkMacroArgTokensVisitor(SourceManager &SM,
6684 CXToken *tokens, unsigned numTokens)
6685 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6686
6687 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6688 if (cursor.kind != CXCursor_MacroExpansion)
6689 return CXChildVisit_Continue;
6690
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006691 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006692 if (macroRange.getBegin() == macroRange.getEnd())
6693 return CXChildVisit_Continue; // it's not a function macro.
6694
6695 for (; CurIdx < NumTokens; ++CurIdx) {
6696 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6697 macroRange.getBegin()))
6698 break;
6699 }
6700
6701 if (CurIdx == NumTokens)
6702 return CXChildVisit_Break;
6703
6704 for (; CurIdx < NumTokens; ++CurIdx) {
6705 SourceLocation tokLoc = getTokenLoc(CurIdx);
6706 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6707 break;
6708
6709 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6710 }
6711
6712 if (CurIdx == NumTokens)
6713 return CXChildVisit_Break;
6714
6715 return CXChildVisit_Continue;
6716 }
6717
6718private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006719 CXToken &getTok(unsigned Idx) {
6720 assert(Idx < NumTokens);
6721 return Tokens[Idx];
6722 }
6723 const CXToken &getTok(unsigned Idx) const {
6724 assert(Idx < NumTokens);
6725 return Tokens[Idx];
6726 }
6727
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006729 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006730 }
6731
6732 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6733 // The third field is reserved and currently not used. Use it here
6734 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006735 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 }
6737};
6738
6739} // end anonymous namespace
6740
6741static CXChildVisitResult
6742MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6743 CXClientData client_data) {
6744 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6745 parent);
6746}
6747
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006748/// \brief Used by \c annotatePreprocessorTokens.
6749/// \returns true if lexing was finished, false otherwise.
6750static bool lexNext(Lexer &Lex, Token &Tok,
6751 unsigned &NextIdx, unsigned NumTokens) {
6752 if (NextIdx >= NumTokens)
6753 return true;
6754
6755 ++NextIdx;
6756 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006757 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006758}
6759
Guy Benyei11169dd2012-12-18 14:30:41 +00006760static void annotatePreprocessorTokens(CXTranslationUnit TU,
6761 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006762 CXCursor *Cursors,
6763 CXToken *Tokens,
6764 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006765 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006766
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006767 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006768 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6769 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006770 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006771 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006772 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006773
6774 if (BeginLocInfo.first != EndLocInfo.first)
6775 return;
6776
6777 StringRef Buffer;
6778 bool Invalid = false;
6779 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6780 if (Buffer.empty() || Invalid)
6781 return;
6782
6783 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6784 CXXUnit->getASTContext().getLangOpts(),
6785 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6786 Buffer.end());
6787 Lex.SetCommentRetentionState(true);
6788
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006789 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006790 // Lex tokens in raw mode until we hit the end of the range, to avoid
6791 // entering #includes or expanding macros.
6792 while (true) {
6793 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006794 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6795 break;
6796 unsigned TokIdx = NextIdx-1;
6797 assert(Tok.getLocation() ==
6798 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006799
6800 reprocess:
6801 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006802 // We have found a preprocessing directive. Annotate the tokens
6803 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006804 //
6805 // FIXME: Some simple tests here could identify macro definitions and
6806 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006807
6808 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006809 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6810 break;
6811
Craig Topper69186e72014-06-08 08:38:04 +00006812 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006813 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006814 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6815 break;
6816
6817 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006818 IdentifierInfo &II =
6819 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006820 SourceLocation MappedTokLoc =
6821 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6822 MI = getMacroInfo(II, MappedTokLoc, TU);
6823 }
6824 }
6825
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006826 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006827 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006828 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6829 finished = true;
6830 break;
6831 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006832 // If we are in a macro definition, check if the token was ever a
6833 // macro name and annotate it if that's the case.
6834 if (MI) {
6835 SourceLocation SaveLoc = Tok.getLocation();
6836 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006837 MacroDefinitionRecord *MacroDef =
6838 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006839 Tok.setLocation(SaveLoc);
6840 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006841 Cursors[NextIdx - 1] =
6842 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006843 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006844 } while (!Tok.isAtStartOfLine());
6845
6846 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6847 assert(TokIdx <= LastIdx);
6848 SourceLocation EndLoc =
6849 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6850 CXCursor Cursor =
6851 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6852
6853 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006854 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006855
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006856 if (finished)
6857 break;
6858 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006859 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 }
6861}
6862
6863// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006864static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6865 CXToken *Tokens, unsigned NumTokens,
6866 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006867 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6869 setThreadBackgroundPriority();
6870
6871 // Determine the region of interest, which contains all of the tokens.
6872 SourceRange RegionOfInterest;
6873 RegionOfInterest.setBegin(
6874 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6875 RegionOfInterest.setEnd(
6876 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6877 Tokens[NumTokens-1])));
6878
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 // Relex the tokens within the source range to look for preprocessing
6880 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006881 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006882
6883 // If begin location points inside a macro argument, set it to the expansion
6884 // location so we can have the full context when annotating semantically.
6885 {
6886 SourceManager &SM = CXXUnit->getSourceManager();
6887 SourceLocation Loc =
6888 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6889 if (Loc.isMacroID())
6890 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6891 }
6892
Guy Benyei11169dd2012-12-18 14:30:41 +00006893 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6894 // Search and mark tokens that are macro argument expansions.
6895 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6896 Tokens, NumTokens);
6897 CursorVisitor MacroArgMarker(TU,
6898 MarkMacroArgTokensVisitorDelegate, &Visitor,
6899 /*VisitPreprocessorLast=*/true,
6900 /*VisitIncludedEntities=*/false,
6901 RegionOfInterest);
6902 MacroArgMarker.visitPreprocessedEntitiesInRegion();
6903 }
6904
6905 // Annotate all of the source locations in the region of interest that map to
6906 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006907 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00006908
6909 // FIXME: We use a ridiculous stack size here because the data-recursion
6910 // algorithm uses a large stack frame than the non-data recursive version,
6911 // and AnnotationTokensWorker currently transforms the data-recursion
6912 // algorithm back into a traditional recursion by explicitly calling
6913 // VisitChildren(). We will need to remove this explicit recursive call.
6914 W.AnnotateTokens();
6915
6916 // If we ran into any entities that involve context-sensitive keywords,
6917 // take another pass through the tokens to mark them as such.
6918 if (W.hasContextSensitiveKeywords()) {
6919 for (unsigned I = 0; I != NumTokens; ++I) {
6920 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6921 continue;
6922
6923 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6924 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006925 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6927 if (Property->getPropertyAttributesAsWritten() != 0 &&
6928 llvm::StringSwitch<bool>(II->getName())
6929 .Case("readonly", true)
6930 .Case("assign", true)
6931 .Case("unsafe_unretained", true)
6932 .Case("readwrite", true)
6933 .Case("retain", true)
6934 .Case("copy", true)
6935 .Case("nonatomic", true)
6936 .Case("atomic", true)
6937 .Case("getter", true)
6938 .Case("setter", true)
6939 .Case("strong", true)
6940 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00006941 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00006942 .Default(false))
6943 Tokens[I].int_data[0] = CXToken_Keyword;
6944 }
6945 continue;
6946 }
6947
6948 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6949 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6950 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6951 if (llvm::StringSwitch<bool>(II->getName())
6952 .Case("in", true)
6953 .Case("out", true)
6954 .Case("inout", true)
6955 .Case("oneway", true)
6956 .Case("bycopy", true)
6957 .Case("byref", true)
6958 .Default(false))
6959 Tokens[I].int_data[0] = CXToken_Keyword;
6960 continue;
6961 }
6962
6963 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6964 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6965 Tokens[I].int_data[0] = CXToken_Keyword;
6966 continue;
6967 }
6968 }
6969 }
6970}
6971
Guy Benyei11169dd2012-12-18 14:30:41 +00006972void clang_annotateTokens(CXTranslationUnit TU,
6973 CXToken *Tokens, unsigned NumTokens,
6974 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006975 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006976 LOG_BAD_TU(TU);
6977 return;
6978 }
6979 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006980 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006982 }
6983
6984 LOG_FUNC_SECTION {
6985 *Log << TU << ' ';
6986 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6987 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6988 *Log << clang_getRange(bloc, eloc);
6989 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006990
6991 // Any token we don't specifically annotate will have a NULL cursor.
6992 CXCursor C = clang_getNullCursor();
6993 for (unsigned I = 0; I != NumTokens; ++I)
6994 Cursors[I] = C;
6995
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006996 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 if (!CXXUnit)
6998 return;
6999
7000 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007001
7002 auto AnnotateTokensImpl = [=]() {
7003 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7004 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007005 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007006 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007007 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7008 }
7009}
7010
Guy Benyei11169dd2012-12-18 14:30:41 +00007011//===----------------------------------------------------------------------===//
7012// Operations for querying linkage of a cursor.
7013//===----------------------------------------------------------------------===//
7014
Guy Benyei11169dd2012-12-18 14:30:41 +00007015CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7016 if (!clang_isDeclaration(cursor.kind))
7017 return CXLinkage_Invalid;
7018
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007019 const Decl *D = cxcursor::getCursorDecl(cursor);
7020 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007021 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007022 case NoLinkage:
7023 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Guy Benyei11169dd2012-12-18 14:30:41 +00007024 case InternalLinkage: return CXLinkage_Internal;
7025 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
7026 case ExternalLinkage: return CXLinkage_External;
7027 };
7028
7029 return CXLinkage_Invalid;
7030}
Guy Benyei11169dd2012-12-18 14:30:41 +00007031
7032//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007033// Operations for querying visibility of a cursor.
7034//===----------------------------------------------------------------------===//
7035
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007036CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7037 if (!clang_isDeclaration(cursor.kind))
7038 return CXVisibility_Invalid;
7039
7040 const Decl *D = cxcursor::getCursorDecl(cursor);
7041 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7042 switch (ND->getVisibility()) {
7043 case HiddenVisibility: return CXVisibility_Hidden;
7044 case ProtectedVisibility: return CXVisibility_Protected;
7045 case DefaultVisibility: return CXVisibility_Default;
7046 };
7047
7048 return CXVisibility_Invalid;
7049}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007050
7051//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007052// Operations for querying language of a cursor.
7053//===----------------------------------------------------------------------===//
7054
7055static CXLanguageKind getDeclLanguage(const Decl *D) {
7056 if (!D)
7057 return CXLanguage_C;
7058
7059 switch (D->getKind()) {
7060 default:
7061 break;
7062 case Decl::ImplicitParam:
7063 case Decl::ObjCAtDefsField:
7064 case Decl::ObjCCategory:
7065 case Decl::ObjCCategoryImpl:
7066 case Decl::ObjCCompatibleAlias:
7067 case Decl::ObjCImplementation:
7068 case Decl::ObjCInterface:
7069 case Decl::ObjCIvar:
7070 case Decl::ObjCMethod:
7071 case Decl::ObjCProperty:
7072 case Decl::ObjCPropertyImpl:
7073 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007074 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007075 return CXLanguage_ObjC;
7076 case Decl::CXXConstructor:
7077 case Decl::CXXConversion:
7078 case Decl::CXXDestructor:
7079 case Decl::CXXMethod:
7080 case Decl::CXXRecord:
7081 case Decl::ClassTemplate:
7082 case Decl::ClassTemplatePartialSpecialization:
7083 case Decl::ClassTemplateSpecialization:
7084 case Decl::Friend:
7085 case Decl::FriendTemplate:
7086 case Decl::FunctionTemplate:
7087 case Decl::LinkageSpec:
7088 case Decl::Namespace:
7089 case Decl::NamespaceAlias:
7090 case Decl::NonTypeTemplateParm:
7091 case Decl::StaticAssert:
7092 case Decl::TemplateTemplateParm:
7093 case Decl::TemplateTypeParm:
7094 case Decl::UnresolvedUsingTypename:
7095 case Decl::UnresolvedUsingValue:
7096 case Decl::Using:
7097 case Decl::UsingDirective:
7098 case Decl::UsingShadow:
7099 return CXLanguage_CPlusPlus;
7100 }
7101
7102 return CXLanguage_C;
7103}
7104
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007105static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7106 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007107 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007108
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007109 switch (D->getAvailability()) {
7110 case AR_Available:
7111 case AR_NotYetIntroduced:
7112 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007113 return getCursorAvailabilityForDecl(
7114 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007115 return CXAvailability_Available;
7116
7117 case AR_Deprecated:
7118 return CXAvailability_Deprecated;
7119
7120 case AR_Unavailable:
7121 return CXAvailability_NotAvailable;
7122 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007123
7124 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007125}
7126
Guy Benyei11169dd2012-12-18 14:30:41 +00007127enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7128 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007129 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7130 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007131
7132 return CXAvailability_Available;
7133}
7134
7135static CXVersion convertVersion(VersionTuple In) {
7136 CXVersion Out = { -1, -1, -1 };
7137 if (In.empty())
7138 return Out;
7139
7140 Out.Major = In.getMajor();
7141
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007142 Optional<unsigned> Minor = In.getMinor();
7143 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007144 Out.Minor = *Minor;
7145 else
7146 return Out;
7147
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007148 Optional<unsigned> Subminor = In.getSubminor();
7149 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007150 Out.Subminor = *Subminor;
7151
7152 return Out;
7153}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007154
7155static int getCursorPlatformAvailabilityForDecl(const Decl *D,
7156 int *always_deprecated,
7157 CXString *deprecated_message,
7158 int *always_unavailable,
7159 CXString *unavailable_message,
7160 CXPlatformAvailability *availability,
7161 int availability_size) {
7162 bool HadAvailAttr = false;
7163 int N = 0;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007164 for (auto A : D->attrs()) {
7165 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007166 HadAvailAttr = true;
7167 if (always_deprecated)
7168 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007169 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007170 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007171 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007172 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007173 continue;
7174 }
7175
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007176 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007177 HadAvailAttr = true;
7178 if (always_unavailable)
7179 *always_unavailable = 1;
7180 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007181 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007182 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7183 }
7184 continue;
7185 }
7186
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007187 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007188 HadAvailAttr = true;
7189 if (N < availability_size) {
7190 availability[N].Platform
7191 = cxstring::createDup(Avail->getPlatform()->getName());
7192 availability[N].Introduced = convertVersion(Avail->getIntroduced());
7193 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
7194 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
7195 availability[N].Unavailable = Avail->getUnavailable();
7196 availability[N].Message = cxstring::createDup(Avail->getMessage());
7197 }
7198 ++N;
7199 }
7200 }
7201
7202 if (!HadAvailAttr)
7203 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7204 return getCursorPlatformAvailabilityForDecl(
7205 cast<Decl>(EnumConst->getDeclContext()),
7206 always_deprecated,
7207 deprecated_message,
7208 always_unavailable,
7209 unavailable_message,
7210 availability,
7211 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007212
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007213 return N;
7214}
7215
Guy Benyei11169dd2012-12-18 14:30:41 +00007216int clang_getCursorPlatformAvailability(CXCursor cursor,
7217 int *always_deprecated,
7218 CXString *deprecated_message,
7219 int *always_unavailable,
7220 CXString *unavailable_message,
7221 CXPlatformAvailability *availability,
7222 int availability_size) {
7223 if (always_deprecated)
7224 *always_deprecated = 0;
7225 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007226 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007227 if (always_unavailable)
7228 *always_unavailable = 0;
7229 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007230 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007231
Guy Benyei11169dd2012-12-18 14:30:41 +00007232 if (!clang_isDeclaration(cursor.kind))
7233 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007234
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007235 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007236 if (!D)
7237 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007238
7239 return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
7240 deprecated_message,
7241 always_unavailable,
7242 unavailable_message,
7243 availability,
7244 availability_size);
Guy Benyei11169dd2012-12-18 14:30:41 +00007245}
7246
7247void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7248 clang_disposeString(availability->Platform);
7249 clang_disposeString(availability->Message);
7250}
7251
7252CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7253 if (clang_isDeclaration(cursor.kind))
7254 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7255
7256 return CXLanguage_Invalid;
7257}
7258
7259 /// \brief If the given cursor is the "templated" declaration
7260 /// descibing a class or function template, return the class or
7261 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007262static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007263 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007264 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007265
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007266 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007267 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7268 return FunTmpl;
7269
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007270 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7272 return ClassTmpl;
7273
7274 return D;
7275}
7276
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007277
7278enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7279 StorageClass sc = SC_None;
7280 const Decl *D = getCursorDecl(C);
7281 if (D) {
7282 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7283 sc = FD->getStorageClass();
7284 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7285 sc = VD->getStorageClass();
7286 } else {
7287 return CX_SC_Invalid;
7288 }
7289 } else {
7290 return CX_SC_Invalid;
7291 }
7292 switch (sc) {
7293 case SC_None:
7294 return CX_SC_None;
7295 case SC_Extern:
7296 return CX_SC_Extern;
7297 case SC_Static:
7298 return CX_SC_Static;
7299 case SC_PrivateExtern:
7300 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007301 case SC_Auto:
7302 return CX_SC_Auto;
7303 case SC_Register:
7304 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007305 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007306 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007307}
7308
Guy Benyei11169dd2012-12-18 14:30:41 +00007309CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7310 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007311 if (const Decl *D = getCursorDecl(cursor)) {
7312 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007313 if (!DC)
7314 return clang_getNullCursor();
7315
7316 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7317 getCursorTU(cursor));
7318 }
7319 }
7320
7321 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007322 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007323 return MakeCXCursor(D, getCursorTU(cursor));
7324 }
7325
7326 return clang_getNullCursor();
7327}
7328
7329CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7330 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007331 if (const Decl *D = getCursorDecl(cursor)) {
7332 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 if (!DC)
7334 return clang_getNullCursor();
7335
7336 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7337 getCursorTU(cursor));
7338 }
7339 }
7340
7341 // FIXME: Note that we can't easily compute the lexical context of a
7342 // statement or expression, so we return nothing.
7343 return clang_getNullCursor();
7344}
7345
7346CXFile clang_getIncludedFile(CXCursor cursor) {
7347 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007348 return nullptr;
7349
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007350 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007351 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007352}
7353
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007354unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7355 if (C.kind != CXCursor_ObjCPropertyDecl)
7356 return CXObjCPropertyAttr_noattr;
7357
7358 unsigned Result = CXObjCPropertyAttr_noattr;
7359 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7360 ObjCPropertyDecl::PropertyAttributeKind Attr =
7361 PD->getPropertyAttributesAsWritten();
7362
7363#define SET_CXOBJCPROP_ATTR(A) \
7364 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7365 Result |= CXObjCPropertyAttr_##A
7366 SET_CXOBJCPROP_ATTR(readonly);
7367 SET_CXOBJCPROP_ATTR(getter);
7368 SET_CXOBJCPROP_ATTR(assign);
7369 SET_CXOBJCPROP_ATTR(readwrite);
7370 SET_CXOBJCPROP_ATTR(retain);
7371 SET_CXOBJCPROP_ATTR(copy);
7372 SET_CXOBJCPROP_ATTR(nonatomic);
7373 SET_CXOBJCPROP_ATTR(setter);
7374 SET_CXOBJCPROP_ATTR(atomic);
7375 SET_CXOBJCPROP_ATTR(weak);
7376 SET_CXOBJCPROP_ATTR(strong);
7377 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007378 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007379#undef SET_CXOBJCPROP_ATTR
7380
7381 return Result;
7382}
7383
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007384unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7385 if (!clang_isDeclaration(C.kind))
7386 return CXObjCDeclQualifier_None;
7387
7388 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7389 const Decl *D = getCursorDecl(C);
7390 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7391 QT = MD->getObjCDeclQualifier();
7392 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7393 QT = PD->getObjCDeclQualifier();
7394 if (QT == Decl::OBJC_TQ_None)
7395 return CXObjCDeclQualifier_None;
7396
7397 unsigned Result = CXObjCDeclQualifier_None;
7398 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7399 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7400 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7401 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7402 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7403 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7404
7405 return Result;
7406}
7407
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007408unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7409 if (!clang_isDeclaration(C.kind))
7410 return 0;
7411
7412 const Decl *D = getCursorDecl(C);
7413 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7414 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7415 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7416 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7417
7418 return 0;
7419}
7420
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007421unsigned clang_Cursor_isVariadic(CXCursor C) {
7422 if (!clang_isDeclaration(C.kind))
7423 return 0;
7424
7425 const Decl *D = getCursorDecl(C);
7426 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7427 return FD->isVariadic();
7428 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7429 return MD->isVariadic();
7430
7431 return 0;
7432}
7433
Guy Benyei11169dd2012-12-18 14:30:41 +00007434CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7435 if (!clang_isDeclaration(C.kind))
7436 return clang_getNullRange();
7437
7438 const Decl *D = getCursorDecl(C);
7439 ASTContext &Context = getCursorContext(C);
7440 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7441 if (!RC)
7442 return clang_getNullRange();
7443
7444 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7445}
7446
7447CXString clang_Cursor_getRawCommentText(CXCursor C) {
7448 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007449 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007450
7451 const Decl *D = getCursorDecl(C);
7452 ASTContext &Context = getCursorContext(C);
7453 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7454 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7455 StringRef();
7456
7457 // Don't duplicate the string because RawText points directly into source
7458 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007459 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007460}
7461
7462CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7463 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007464 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007465
7466 const Decl *D = getCursorDecl(C);
7467 const ASTContext &Context = getCursorContext(C);
7468 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7469
7470 if (RC) {
7471 StringRef BriefText = RC->getBriefText(Context);
7472
7473 // Don't duplicate the string because RawComment ensures that this memory
7474 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007475 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007476 }
7477
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007478 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007479}
7480
Guy Benyei11169dd2012-12-18 14:30:41 +00007481CXModule clang_Cursor_getModule(CXCursor C) {
7482 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007483 if (const ImportDecl *ImportD =
7484 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007485 return ImportD->getImportedModule();
7486 }
7487
Craig Topper69186e72014-06-08 08:38:04 +00007488 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007489}
7490
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007491CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7492 if (isNotUsableTU(TU)) {
7493 LOG_BAD_TU(TU);
7494 return nullptr;
7495 }
7496 if (!File)
7497 return nullptr;
7498 FileEntry *FE = static_cast<FileEntry *>(File);
7499
7500 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7501 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7502 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7503
Richard Smithfeb54b62014-10-23 02:01:19 +00007504 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007505}
7506
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007507CXFile clang_Module_getASTFile(CXModule CXMod) {
7508 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007509 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007510 Module *Mod = static_cast<Module*>(CXMod);
7511 return const_cast<FileEntry *>(Mod->getASTFile());
7512}
7513
Guy Benyei11169dd2012-12-18 14:30:41 +00007514CXModule clang_Module_getParent(CXModule CXMod) {
7515 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007516 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007517 Module *Mod = static_cast<Module*>(CXMod);
7518 return Mod->Parent;
7519}
7520
7521CXString clang_Module_getName(CXModule CXMod) {
7522 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007523 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007524 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007525 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007526}
7527
7528CXString clang_Module_getFullName(CXModule CXMod) {
7529 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007530 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007532 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007533}
7534
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007535int clang_Module_isSystem(CXModule CXMod) {
7536 if (!CXMod)
7537 return 0;
7538 Module *Mod = static_cast<Module*>(CXMod);
7539 return Mod->IsSystem;
7540}
7541
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007542unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7543 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007544 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007545 LOG_BAD_TU(TU);
7546 return 0;
7547 }
7548 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007549 return 0;
7550 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007551 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7552 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7553 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007554}
7555
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007556CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7557 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007558 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007559 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007560 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007561 }
7562 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007563 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007564 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007565 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007566
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007567 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7568 if (Index < TopHeaders.size())
7569 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007570
Craig Topper69186e72014-06-08 08:38:04 +00007571 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007572}
7573
Guy Benyei11169dd2012-12-18 14:30:41 +00007574//===----------------------------------------------------------------------===//
7575// C++ AST instrospection.
7576//===----------------------------------------------------------------------===//
7577
Jonathan Coe29565352016-04-27 12:48:25 +00007578unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7579 if (!clang_isDeclaration(C.kind))
7580 return 0;
7581
7582 const Decl *D = cxcursor::getCursorDecl(C);
7583 const CXXConstructorDecl *Constructor =
7584 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7585 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7586}
7587
7588unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7589 if (!clang_isDeclaration(C.kind))
7590 return 0;
7591
7592 const Decl *D = cxcursor::getCursorDecl(C);
7593 const CXXConstructorDecl *Constructor =
7594 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7595 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7596}
7597
7598unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7599 if (!clang_isDeclaration(C.kind))
7600 return 0;
7601
7602 const Decl *D = cxcursor::getCursorDecl(C);
7603 const CXXConstructorDecl *Constructor =
7604 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7605 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7606}
7607
7608unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7609 if (!clang_isDeclaration(C.kind))
7610 return 0;
7611
7612 const Decl *D = cxcursor::getCursorDecl(C);
7613 const CXXConstructorDecl *Constructor =
7614 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7615 // Passing 'false' excludes constructors marked 'explicit'.
7616 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7617}
7618
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007619unsigned clang_CXXField_isMutable(CXCursor C) {
7620 if (!clang_isDeclaration(C.kind))
7621 return 0;
7622
7623 if (const auto D = cxcursor::getCursorDecl(C))
7624 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7625 return FD->isMutable() ? 1 : 0;
7626 return 0;
7627}
7628
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007629unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7630 if (!clang_isDeclaration(C.kind))
7631 return 0;
7632
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007633 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007634 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007635 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007636 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7637}
7638
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007639unsigned clang_CXXMethod_isConst(CXCursor C) {
7640 if (!clang_isDeclaration(C.kind))
7641 return 0;
7642
7643 const Decl *D = cxcursor::getCursorDecl(C);
7644 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007645 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007646 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7647}
7648
Jonathan Coe29565352016-04-27 12:48:25 +00007649unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7650 if (!clang_isDeclaration(C.kind))
7651 return 0;
7652
7653 const Decl *D = cxcursor::getCursorDecl(C);
7654 const CXXMethodDecl *Method =
7655 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7656 return (Method && Method->isDefaulted()) ? 1 : 0;
7657}
7658
Guy Benyei11169dd2012-12-18 14:30:41 +00007659unsigned clang_CXXMethod_isStatic(CXCursor C) {
7660 if (!clang_isDeclaration(C.kind))
7661 return 0;
7662
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007663 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007664 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007665 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 return (Method && Method->isStatic()) ? 1 : 0;
7667}
7668
7669unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7670 if (!clang_isDeclaration(C.kind))
7671 return 0;
7672
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007673 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007674 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007675 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007676 return (Method && Method->isVirtual()) ? 1 : 0;
7677}
Guy Benyei11169dd2012-12-18 14:30:41 +00007678
7679//===----------------------------------------------------------------------===//
7680// Attribute introspection.
7681//===----------------------------------------------------------------------===//
7682
Guy Benyei11169dd2012-12-18 14:30:41 +00007683CXType clang_getIBOutletCollectionType(CXCursor C) {
7684 if (C.kind != CXCursor_IBOutletCollectionAttr)
7685 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7686
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007687 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007688 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7689
7690 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7691}
Guy Benyei11169dd2012-12-18 14:30:41 +00007692
7693//===----------------------------------------------------------------------===//
7694// Inspecting memory usage.
7695//===----------------------------------------------------------------------===//
7696
7697typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7698
7699static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7700 enum CXTUResourceUsageKind k,
7701 unsigned long amount) {
7702 CXTUResourceUsageEntry entry = { k, amount };
7703 entries.push_back(entry);
7704}
7705
Guy Benyei11169dd2012-12-18 14:30:41 +00007706const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7707 const char *str = "";
7708 switch (kind) {
7709 case CXTUResourceUsage_AST:
7710 str = "ASTContext: expressions, declarations, and types";
7711 break;
7712 case CXTUResourceUsage_Identifiers:
7713 str = "ASTContext: identifiers";
7714 break;
7715 case CXTUResourceUsage_Selectors:
7716 str = "ASTContext: selectors";
7717 break;
7718 case CXTUResourceUsage_GlobalCompletionResults:
7719 str = "Code completion: cached global results";
7720 break;
7721 case CXTUResourceUsage_SourceManagerContentCache:
7722 str = "SourceManager: content cache allocator";
7723 break;
7724 case CXTUResourceUsage_AST_SideTables:
7725 str = "ASTContext: side tables";
7726 break;
7727 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7728 str = "SourceManager: malloc'ed memory buffers";
7729 break;
7730 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7731 str = "SourceManager: mmap'ed memory buffers";
7732 break;
7733 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7734 str = "ExternalASTSource: malloc'ed memory buffers";
7735 break;
7736 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7737 str = "ExternalASTSource: mmap'ed memory buffers";
7738 break;
7739 case CXTUResourceUsage_Preprocessor:
7740 str = "Preprocessor: malloc'ed memory";
7741 break;
7742 case CXTUResourceUsage_PreprocessingRecord:
7743 str = "Preprocessor: PreprocessingRecord";
7744 break;
7745 case CXTUResourceUsage_SourceManager_DataStructures:
7746 str = "SourceManager: data structures and tables";
7747 break;
7748 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7749 str = "Preprocessor: header search tables";
7750 break;
7751 }
7752 return str;
7753}
7754
7755CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007756 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007757 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007758 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007759 return usage;
7760 }
7761
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007762 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007763 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007764 ASTContext &astContext = astUnit->getASTContext();
7765
7766 // How much memory is used by AST nodes and types?
7767 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7768 (unsigned long) astContext.getASTAllocatedMemory());
7769
7770 // How much memory is used by identifiers?
7771 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7772 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7773
7774 // How much memory is used for selectors?
7775 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7776 (unsigned long) astContext.Selectors.getTotalMemory());
7777
7778 // How much memory is used by ASTContext's side tables?
7779 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7780 (unsigned long) astContext.getSideTableAllocatedMemory());
7781
7782 // How much memory is used for caching global code completion results?
7783 unsigned long completionBytes = 0;
7784 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00007785 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007786 completionBytes = completionAllocator->getTotalMemory();
7787 }
7788 createCXTUResourceUsageEntry(*entries,
7789 CXTUResourceUsage_GlobalCompletionResults,
7790 completionBytes);
7791
7792 // How much memory is being used by SourceManager's content cache?
7793 createCXTUResourceUsageEntry(*entries,
7794 CXTUResourceUsage_SourceManagerContentCache,
7795 (unsigned long) astContext.getSourceManager().getContentCacheSize());
7796
7797 // How much memory is being used by the MemoryBuffer's in SourceManager?
7798 const SourceManager::MemoryBufferSizes &srcBufs =
7799 astUnit->getSourceManager().getMemoryBufferSizes();
7800
7801 createCXTUResourceUsageEntry(*entries,
7802 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7803 (unsigned long) srcBufs.malloc_bytes);
7804 createCXTUResourceUsageEntry(*entries,
7805 CXTUResourceUsage_SourceManager_Membuffer_MMap,
7806 (unsigned long) srcBufs.mmap_bytes);
7807 createCXTUResourceUsageEntry(*entries,
7808 CXTUResourceUsage_SourceManager_DataStructures,
7809 (unsigned long) astContext.getSourceManager()
7810 .getDataStructureSizes());
7811
7812 // How much memory is being used by the ExternalASTSource?
7813 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7814 const ExternalASTSource::MemoryBufferSizes &sizes =
7815 esrc->getMemoryBufferSizes();
7816
7817 createCXTUResourceUsageEntry(*entries,
7818 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7819 (unsigned long) sizes.malloc_bytes);
7820 createCXTUResourceUsageEntry(*entries,
7821 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7822 (unsigned long) sizes.mmap_bytes);
7823 }
7824
7825 // How much memory is being used by the Preprocessor?
7826 Preprocessor &pp = astUnit->getPreprocessor();
7827 createCXTUResourceUsageEntry(*entries,
7828 CXTUResourceUsage_Preprocessor,
7829 pp.getTotalMemory());
7830
7831 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7832 createCXTUResourceUsageEntry(*entries,
7833 CXTUResourceUsage_PreprocessingRecord,
7834 pRec->getTotalMemory());
7835 }
7836
7837 createCXTUResourceUsageEntry(*entries,
7838 CXTUResourceUsage_Preprocessor_HeaderSearch,
7839 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00007840
Guy Benyei11169dd2012-12-18 14:30:41 +00007841 CXTUResourceUsage usage = { (void*) entries.get(),
7842 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00007843 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00007844 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00007845 return usage;
7846}
7847
7848void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7849 if (usage.data)
7850 delete (MemUsageEntries*) usage.data;
7851}
7852
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007853CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7854 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007855 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00007856 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007857
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007858 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007859 LOG_BAD_TU(TU);
7860 return skipped;
7861 }
7862
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007863 if (!file)
7864 return skipped;
7865
7866 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7867 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7868 if (!ppRec)
7869 return skipped;
7870
7871 ASTContext &Ctx = astUnit->getASTContext();
7872 SourceManager &sm = Ctx.getSourceManager();
7873 FileEntry *fileEntry = static_cast<FileEntry *>(file);
7874 FileID wantedFileID = sm.translateFile(fileEntry);
7875
7876 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7877 std::vector<SourceRange> wantedRanges;
7878 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7879 i != ei; ++i) {
7880 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7881 wantedRanges.push_back(*i);
7882 }
7883
7884 skipped->count = wantedRanges.size();
7885 skipped->ranges = new CXSourceRange[skipped->count];
7886 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7887 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7888
7889 return skipped;
7890}
7891
Cameron Desrochersd8091282016-08-18 15:43:55 +00007892CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
7893 CXSourceRangeList *skipped = new CXSourceRangeList;
7894 skipped->count = 0;
7895 skipped->ranges = nullptr;
7896
7897 if (isNotUsableTU(TU)) {
7898 LOG_BAD_TU(TU);
7899 return skipped;
7900 }
7901
7902 ASTUnit *astUnit = cxtu::getASTUnit(TU);
7903 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7904 if (!ppRec)
7905 return skipped;
7906
7907 ASTContext &Ctx = astUnit->getASTContext();
7908
7909 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7910
7911 skipped->count = SkippedRanges.size();
7912 skipped->ranges = new CXSourceRange[skipped->count];
7913 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7914 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
7915
7916 return skipped;
7917}
7918
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00007919void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7920 if (ranges) {
7921 delete[] ranges->ranges;
7922 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00007923 }
7924}
7925
Guy Benyei11169dd2012-12-18 14:30:41 +00007926void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7927 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7928 for (unsigned I = 0; I != Usage.numEntries; ++I)
7929 fprintf(stderr, " %s: %lu\n",
7930 clang_getTUResourceUsageName(Usage.entries[I].kind),
7931 Usage.entries[I].amount);
7932
7933 clang_disposeCXTUResourceUsage(Usage);
7934}
7935
7936//===----------------------------------------------------------------------===//
7937// Misc. utility functions.
7938//===----------------------------------------------------------------------===//
7939
7940/// Default to using an 8 MB stack size on "safety" threads.
7941static unsigned SafetyStackThreadSize = 8 << 20;
7942
7943namespace clang {
7944
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007945bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00007946 unsigned Size) {
7947 if (!Size)
7948 Size = GetSafetyThreadStackSize();
7949 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007950 return CRC.RunSafelyOnThread(Fn, Size);
7951 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00007952}
7953
7954unsigned GetSafetyThreadStackSize() {
7955 return SafetyStackThreadSize;
7956}
7957
7958void SetSafetyThreadStackSize(unsigned Value) {
7959 SafetyStackThreadSize = Value;
7960}
7961
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007962}
Guy Benyei11169dd2012-12-18 14:30:41 +00007963
7964void clang::setThreadBackgroundPriority() {
7965 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7966 return;
7967
Alp Toker1a86ad22014-07-06 06:24:00 +00007968#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00007969 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7970#endif
7971}
7972
7973void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7974 if (!Unit)
7975 return;
7976
7977 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
7978 DEnd = Unit->stored_diag_end();
7979 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00007980 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 CXString Msg = clang_formatDiagnostic(&Diag,
7982 clang_defaultDiagnosticDisplayOptions());
7983 fprintf(stderr, "%s\n", clang_getCString(Msg));
7984 clang_disposeString(Msg);
7985 }
7986#ifdef LLVM_ON_WIN32
7987 // On Windows, force a flush, since there may be multiple copies of
7988 // stderr and stdout in the file system, all with different buffers
7989 // but writing to the same device.
7990 fflush(stderr);
7991#endif
7992}
7993
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007994MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7995 SourceLocation MacroDefLoc,
7996 CXTranslationUnit TU){
7997 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00007998 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007999 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008000 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008001
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008002 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008003 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008004 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008005 if (MD) {
8006 for (MacroDirective::DefInfo
8007 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8008 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8009 return Def.getMacroInfo();
8010 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008011 }
8012
Craig Topper69186e72014-06-08 08:38:04 +00008013 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008014}
8015
Richard Smith66a81862015-05-04 02:25:31 +00008016const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008017 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008018 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008019 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008020 const IdentifierInfo *II = MacroDef->getName();
8021 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008022 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008023
8024 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8025}
8026
Richard Smith66a81862015-05-04 02:25:31 +00008027MacroDefinitionRecord *
8028cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8029 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008030 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008031 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008032 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008033 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008034
8035 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008036 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008037 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8038 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008039 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008040
8041 // Check that the token is inside the definition and not its argument list.
8042 SourceManager &SM = Unit->getSourceManager();
8043 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008044 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008045 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008046 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008047
8048 Preprocessor &PP = Unit->getPreprocessor();
8049 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8050 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008051 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008052
Alp Toker2d57cea2014-05-17 04:53:25 +00008053 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008054 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008055 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008056
8057 // Check that the identifier is not one of the macro arguments.
8058 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
Craig Topper69186e72014-06-08 08:38:04 +00008059 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008060
Richard Smith20e883e2015-04-29 23:20:19 +00008061 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008062 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008063 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008064
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008065 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008066}
8067
Richard Smith66a81862015-05-04 02:25:31 +00008068MacroDefinitionRecord *
8069cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8070 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008071 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008072 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008073
8074 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008075 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008076 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008077 Preprocessor &PP = Unit->getPreprocessor();
8078 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008079 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008080 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8081 Token Tok;
8082 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008083 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008084
8085 return checkForMacroInMacroDefinition(MI, Tok, TU);
8086}
8087
Guy Benyei11169dd2012-12-18 14:30:41 +00008088CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008089 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008090}
8091
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008092Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8093 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008094 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008095 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008096 if (Unit->isMainFileAST())
8097 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008098 return *this;
8099 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008100 } else {
8101 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008102 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008103 return *this;
8104}
8105
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008106Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8107 *this << FE->getName();
8108 return *this;
8109}
8110
8111Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8112 CXString cursorName = clang_getCursorDisplayName(cursor);
8113 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8114 clang_disposeString(cursorName);
8115 return *this;
8116}
8117
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008118Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8119 CXFile File;
8120 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008121 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008122 CXString FileName = clang_getFileName(File);
8123 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8124 clang_disposeString(FileName);
8125 return *this;
8126}
8127
8128Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8129 CXSourceLocation BLoc = clang_getRangeStart(range);
8130 CXSourceLocation ELoc = clang_getRangeEnd(range);
8131
8132 CXFile BFile;
8133 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008134 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008135
8136 CXFile EFile;
8137 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008138 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008139
8140 CXString BFileName = clang_getFileName(BFile);
8141 if (BFile == EFile) {
8142 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8143 BLine, BColumn, ELine, EColumn);
8144 } else {
8145 CXString EFileName = clang_getFileName(EFile);
8146 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8147 BLine, BColumn)
8148 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8149 ELine, EColumn);
8150 clang_disposeString(EFileName);
8151 }
8152 clang_disposeString(BFileName);
8153 return *this;
8154}
8155
8156Logger &cxindex::Logger::operator<<(CXString Str) {
8157 *this << clang_getCString(Str);
8158 return *this;
8159}
8160
8161Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8162 LogOS << Fmt;
8163 return *this;
8164}
8165
Chandler Carruth37ad2582014-06-27 15:14:39 +00008166static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8167
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008168cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008169 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008170
8171 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8172
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008173 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008174 OS << "[libclang:" << Name << ':';
8175
Alp Toker1a86ad22014-07-06 06:24:00 +00008176#ifdef USE_DARWIN_THREADS
8177 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008178 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8179 OS << tid << ':';
8180#endif
8181
8182 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8183 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008184 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008185
8186 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008187 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008188 OS << "--------------------------------------------------\n";
8189 }
8190}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008191
8192#ifdef CLANG_TOOL_EXTRA_BUILD
8193// This anchor is used to force the linker to link the clang-tidy plugin.
8194extern volatile int ClangTidyPluginAnchorSource;
8195static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8196 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008197
8198// This anchor is used to force the linker to link the clang-include-fixer
8199// plugin.
8200extern volatile int ClangIncludeFixerPluginAnchorSource;
8201static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8202 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008203#endif