blob: 26b1f5e2b1d531e730c24ddaa1aa97226c9fc2aa [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"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000029#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/Basic/Version.h"
31#include "clang/Frontend/ASTUnit.h"
32#include "clang/Frontend/CompilerInstance.h"
33#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000034#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000035#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000040#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000041#include "llvm/ADT/Optional.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000044#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "llvm/Support/Compiler.h"
46#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000047#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000048#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000051#include "llvm/Support/Program.h"
52#include "llvm/Support/SaveAndRestore.h"
53#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000054#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "llvm/Support/Threading.h"
56#include "llvm/Support/Timer.h"
57#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000058
Alp Toker1a86ad22014-07-06 06:24:00 +000059#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
60#define USE_DARWIN_THREADS
61#endif
62
63#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000064#include <pthread.h>
65#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000066
67using namespace clang;
68using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000069using namespace clang::cxtu;
70using namespace clang::cxindex;
71
David Blaikieea4395e2017-01-06 19:49:01 +000072CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
73 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000074 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000075 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000076 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000077 CXTranslationUnit D = new CXTranslationUnitImpl();
78 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000079 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000080 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000082 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000083 D->CommentToXML = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000084 return D;
85}
86
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000087bool cxtu::isASTReadError(ASTUnit *AU) {
88 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
89 DEnd = AU->stored_diag_end();
90 D != DEnd; ++D) {
91 if (D->getLevel() >= DiagnosticsEngine::Error &&
92 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
93 diag::DiagCat_AST_Deserialization_Issue)
94 return true;
95 }
96 return false;
97}
98
Guy Benyei11169dd2012-12-18 14:30:41 +000099cxtu::CXTUOwner::~CXTUOwner() {
100 if (TU)
101 clang_disposeTranslationUnit(TU);
102}
103
104/// \brief Compare two source ranges to determine their relative position in
105/// the translation unit.
106static RangeComparisonResult RangeCompare(SourceManager &SM,
107 SourceRange R1,
108 SourceRange R2) {
109 assert(R1.isValid() && "First range is invalid?");
110 assert(R2.isValid() && "Second range is invalid?");
111 if (R1.getEnd() != R2.getBegin() &&
112 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
113 return RangeBefore;
114 if (R2.getEnd() != R1.getBegin() &&
115 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
116 return RangeAfter;
117 return RangeOverlap;
118}
119
120/// \brief Determine if a source location falls within, before, or after a
121/// a given source range.
122static RangeComparisonResult LocationCompare(SourceManager &SM,
123 SourceLocation L, SourceRange R) {
124 assert(R.isValid() && "First range is invalid?");
125 assert(L.isValid() && "Second range is invalid?");
126 if (L == R.getBegin() || L == R.getEnd())
127 return RangeOverlap;
128 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
129 return RangeBefore;
130 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
131 return RangeAfter;
132 return RangeOverlap;
133}
134
135/// \brief Translate a Clang source range into a CIndex source range.
136///
137/// Clang internally represents ranges where the end location points to the
138/// start of the token at the end. However, for external clients it is more
139/// useful to have a CXSourceRange be a proper half-open interval. This routine
140/// does the appropriate translation.
141CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
142 const LangOptions &LangOpts,
143 const CharSourceRange &R) {
144 // We want the last character in this location, so we will adjust the
145 // location accordingly.
146 SourceLocation EndLoc = R.getEnd();
147 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
148 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000149 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000150 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
151 SM, LangOpts);
152 EndLoc = EndLoc.getLocWithOffset(Length);
153 }
154
Bill Wendlingeade3622013-01-23 08:25:41 +0000155 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000156 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000157 R.getBegin().getRawEncoding(),
158 EndLoc.getRawEncoding()
159 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 return Result;
161}
162
163//===----------------------------------------------------------------------===//
164// Cursor visitor.
165//===----------------------------------------------------------------------===//
166
167static SourceRange getRawCursorExtent(CXCursor C);
168static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
169
170
171RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
172 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
173}
174
175/// \brief Visit the given cursor and, if requested by the visitor,
176/// its children.
177///
178/// \param Cursor the cursor to visit.
179///
180/// \param CheckedRegionOfInterest if true, then the caller already checked
181/// that this cursor is within the region of interest.
182///
183/// \returns true if the visitation should be aborted, false if it
184/// should continue.
185bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
186 if (clang_isInvalid(Cursor.kind))
187 return false;
188
189 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000190 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000191 if (!D) {
192 assert(0 && "Invalid declaration cursor");
193 return true; // abort.
194 }
195
196 // Ignore implicit declarations, unless it's an objc method because
197 // currently we should report implicit methods for properties when indexing.
198 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
199 return false;
200 }
201
202 // If we have a range of interest, and this cursor doesn't intersect with it,
203 // we're done.
204 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
205 SourceRange Range = getRawCursorExtent(Cursor);
206 if (Range.isInvalid() || CompareRegionOfInterest(Range))
207 return false;
208 }
209
210 switch (Visitor(Cursor, Parent, ClientData)) {
211 case CXChildVisit_Break:
212 return true;
213
214 case CXChildVisit_Continue:
215 return false;
216
217 case CXChildVisit_Recurse: {
218 bool ret = VisitChildren(Cursor);
219 if (PostChildrenVisitor)
220 if (PostChildrenVisitor(Cursor, ClientData))
221 return true;
222 return ret;
223 }
224 }
225
226 llvm_unreachable("Invalid CXChildVisitResult!");
227}
228
229static bool visitPreprocessedEntitiesInRange(SourceRange R,
230 PreprocessingRecord &PPRec,
231 CursorVisitor &Visitor) {
232 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
233 FileID FID;
234
235 if (!Visitor.shouldVisitIncludedEntities()) {
236 // If the begin/end of the range lie in the same FileID, do the optimization
237 // where we skip preprocessed entities that do not come from the same FileID.
238 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
239 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
240 FID = FileID();
241 }
242
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000243 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
244 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000245 PPRec, FID);
246}
247
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000248bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000250 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000251
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000252 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000253 SourceManager &SM = Unit->getSourceManager();
254
255 std::pair<FileID, unsigned>
256 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
257 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
258
259 if (End.first != Begin.first) {
260 // If the end does not reside in the same file, try to recover by
261 // picking the end of the file of begin location.
262 End.first = Begin.first;
263 End.second = SM.getFileIDSize(Begin.first);
264 }
265
266 assert(Begin.first == End.first);
267 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000268 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000269
270 FileID File = Begin.first;
271 unsigned Offset = Begin.second;
272 unsigned Length = End.second - Begin.second;
273
274 if (!VisitDeclsOnly && !VisitPreprocessorLast)
275 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000276 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000277
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000278 if (visitDeclsFromFileRegion(File, Offset, Length))
279 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000280
281 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000282 return visitPreprocessedEntitiesInRegion();
283
284 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000285}
286
287static bool isInLexicalContext(Decl *D, DeclContext *DC) {
288 if (!DC)
289 return false;
290
291 for (DeclContext *DeclDC = D->getLexicalDeclContext();
292 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
293 if (DeclDC == DC)
294 return true;
295 }
296 return false;
297}
298
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000299bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000301 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 SourceManager &SM = Unit->getSourceManager();
303 SourceRange Range = RegionOfInterest;
304
305 SmallVector<Decl *, 16> Decls;
306 Unit->findFileRegionDecls(File, Offset, Length, Decls);
307
308 // If we didn't find any file level decls for the file, try looking at the
309 // file that it was included from.
310 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
311 bool Invalid = false;
312 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
313 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000314 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000315
316 SourceLocation Outer;
317 if (SLEntry.isFile())
318 Outer = SLEntry.getFile().getIncludeLoc();
319 else
320 Outer = SLEntry.getExpansion().getExpansionLocStart();
321 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000322 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000323
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000324 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000325 Length = 0;
326 Unit->findFileRegionDecls(File, Offset, Length, Decls);
327 }
328
329 assert(!Decls.empty());
330
331 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000332 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000333 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
334 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000335 Decl *D = *DIt;
336 if (D->getSourceRange().isInvalid())
337 continue;
338
339 if (isInLexicalContext(D, CurDC))
340 continue;
341
342 CurDC = dyn_cast<DeclContext>(D);
343
344 if (TagDecl *TD = dyn_cast<TagDecl>(D))
345 if (!TD->isFreeStanding())
346 continue;
347
348 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
349 if (CompRes == RangeBefore)
350 continue;
351 if (CompRes == RangeAfter)
352 break;
353
354 assert(CompRes == RangeOverlap);
355 VisitedAtLeastOnce = true;
356
357 if (isa<ObjCContainerDecl>(D)) {
358 FileDI_current = &DIt;
359 FileDE_current = DE;
360 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000361 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000362 }
363
364 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000365 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 }
367
368 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000369 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000370
371 // No Decls overlapped with the range. Move up the lexical context until there
372 // is a context that contains the range or we reach the translation unit
373 // level.
374 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
375 : (*(DIt-1))->getLexicalDeclContext();
376
377 while (DC && !DC->isTranslationUnit()) {
378 Decl *D = cast<Decl>(DC);
379 SourceRange CurDeclRange = D->getSourceRange();
380 if (CurDeclRange.isInvalid())
381 break;
382
383 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000384 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
385 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000386 }
387
388 DC = D->getLexicalDeclContext();
389 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000390
391 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000392}
393
394bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
395 if (!AU->getPreprocessor().getPreprocessingRecord())
396 return false;
397
398 PreprocessingRecord &PPRec
399 = *AU->getPreprocessor().getPreprocessingRecord();
400 SourceManager &SM = AU->getSourceManager();
401
402 if (RegionOfInterest.isValid()) {
403 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
404 SourceLocation B = MappedRange.getBegin();
405 SourceLocation E = MappedRange.getEnd();
406
407 if (AU->isInPreambleFileID(B)) {
408 if (SM.isLoadedSourceLocation(E))
409 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
410 PPRec, *this);
411
412 // Beginning of range lies in the preamble but it also extends beyond
413 // it into the main file. Split the range into 2 parts, one covering
414 // the preamble and another covering the main file. This allows subsequent
415 // calls to visitPreprocessedEntitiesInRange to accept a source range that
416 // lies in the same FileID, allowing it to skip preprocessed entities that
417 // do not come from the same FileID.
418 bool breaked =
419 visitPreprocessedEntitiesInRange(
420 SourceRange(B, AU->getEndOfPreambleFileID()),
421 PPRec, *this);
422 if (breaked) return true;
423 return visitPreprocessedEntitiesInRange(
424 SourceRange(AU->getStartOfMainFileID(), E),
425 PPRec, *this);
426 }
427
428 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
429 }
430
431 bool OnlyLocalDecls
432 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
433
434 if (OnlyLocalDecls)
435 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
436 PPRec);
437
438 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
439}
440
441template<typename InputIterator>
442bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
443 InputIterator Last,
444 PreprocessingRecord &PPRec,
445 FileID FID) {
446 for (; First != Last; ++First) {
447 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
448 continue;
449
450 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000451 if (!PPE)
452 continue;
453
Guy Benyei11169dd2012-12-18 14:30:41 +0000454 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
455 if (Visit(MakeMacroExpansionCursor(ME, TU)))
456 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000457
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 continue;
459 }
Richard Smith66a81862015-05-04 02:25:31 +0000460
461 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000462 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
463 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000464
Guy Benyei11169dd2012-12-18 14:30:41 +0000465 continue;
466 }
467
468 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
469 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
470 return true;
471
472 continue;
473 }
474 }
475
476 return false;
477}
478
479/// \brief Visit the children of the given cursor.
480///
481/// \returns true if the visitation should be aborted, false if it
482/// should continue.
483bool CursorVisitor::VisitChildren(CXCursor Cursor) {
484 if (clang_isReference(Cursor.kind) &&
485 Cursor.kind != CXCursor_CXXBaseSpecifier) {
486 // By definition, references have no children.
487 return false;
488 }
489
490 // Set the Parent field to Cursor, then back to its old value once we're
491 // done.
492 SetParentRAII SetParent(Parent, StmtParent, Cursor);
493
494 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000495 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000496 if (!D)
497 return false;
498
499 return VisitAttributes(D) || Visit(D);
500 }
501
502 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000503 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000504 return Visit(S);
505
506 return false;
507 }
508
509 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000510 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000511 return Visit(E);
512
513 return false;
514 }
515
516 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000517 CXTranslationUnit TU = getCursorTU(Cursor);
518 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000519
520 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
521 for (unsigned I = 0; I != 2; ++I) {
522 if (VisitOrder[I]) {
523 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
524 RegionOfInterest.isInvalid()) {
525 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
526 TLEnd = CXXUnit->top_level_end();
527 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000528 const Optional<bool> V = handleDeclForVisitation(*TL);
529 if (!V.hasValue())
530 continue;
531 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000532 }
533 } else if (VisitDeclContext(
534 CXXUnit->getASTContext().getTranslationUnitDecl()))
535 return true;
536 continue;
537 }
538
539 // Walk the preprocessing record.
540 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
541 visitPreprocessedEntitiesInRegion();
542 }
543
544 return false;
545 }
546
547 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000548 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000549 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
550 return Visit(BaseTSInfo->getTypeLoc());
551 }
552 }
553 }
554
555 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000556 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000558 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000559 return Visit(cxcursor::MakeCursorObjCClassRef(
560 ObjT->getInterface(),
561 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 }
563
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000564 // If pointing inside a macro definition, check if the token is an identifier
565 // that was ever defined as a macro. In such a case, create a "pseudo" macro
566 // expansion cursor for that token.
567 SourceLocation BeginLoc = RegionOfInterest.getBegin();
568 if (Cursor.kind == CXCursor_MacroDefinition &&
569 BeginLoc == RegionOfInterest.getEnd()) {
570 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000571 const MacroInfo *MI =
572 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000573 if (MacroDefinitionRecord *MacroDef =
574 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000575 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
576 }
577
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 // Nothing to visit at the moment.
579 return false;
580}
581
582bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
583 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
584 if (Visit(TSInfo->getTypeLoc()))
585 return true;
586
587 if (Stmt *Body = B->getBody())
588 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
589
590 return false;
591}
592
Ted Kremenek03325582013-02-21 01:29:01 +0000593Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000594 if (RegionOfInterest.isValid()) {
595 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
596 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000597 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000598
599 switch (CompareRegionOfInterest(Range)) {
600 case RangeBefore:
601 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000602 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000603
604 case RangeAfter:
605 // This declaration comes after the region of interest; we're done.
606 return false;
607
608 case RangeOverlap:
609 // This declaration overlaps the region of interest; visit it.
610 break;
611 }
612 }
613 return true;
614}
615
616bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
617 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
618
619 // FIXME: Eventually remove. This part of a hack to support proper
620 // iteration over all Decls contained lexically within an ObjC container.
621 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
622 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
623
624 for ( ; I != E; ++I) {
625 Decl *D = *I;
626 if (D->getLexicalDeclContext() != DC)
627 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000628 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000629 if (!V.hasValue())
630 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000631 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000632 }
633 return false;
634}
635
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000636Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
637 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
638
639 // Ignore synthesized ivars here, otherwise if we have something like:
640 // @synthesize prop = _prop;
641 // and '_prop' is not declared, we will encounter a '_prop' ivar before
642 // encountering the 'prop' synthesize declaration and we will think that
643 // we passed the region-of-interest.
644 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
645 if (ivarD->getSynthesize())
646 return None;
647 }
648
649 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
650 // declarations is a mismatch with the compiler semantics.
651 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
652 auto *ID = cast<ObjCInterfaceDecl>(D);
653 if (!ID->isThisDeclarationADefinition())
654 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
655
656 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
657 auto *PD = cast<ObjCProtocolDecl>(D);
658 if (!PD->isThisDeclarationADefinition())
659 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
660 }
661
662 const Optional<bool> V = shouldVisitCursor(Cursor);
663 if (!V.hasValue())
664 return None;
665 if (!V.getValue())
666 return false;
667 if (Visit(Cursor, true))
668 return true;
669 return None;
670}
671
Guy Benyei11169dd2012-12-18 14:30:41 +0000672bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
673 llvm_unreachable("Translation units are visited directly by Visit()");
674}
675
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000676bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
677 if (VisitTemplateParameters(D->getTemplateParameters()))
678 return true;
679
680 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
681}
682
Guy Benyei11169dd2012-12-18 14:30:41 +0000683bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
684 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
685 return Visit(TSInfo->getTypeLoc());
686
687 return false;
688}
689
690bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
691 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
692 return Visit(TSInfo->getTypeLoc());
693
694 return false;
695}
696
697bool CursorVisitor::VisitTagDecl(TagDecl *D) {
698 return VisitDeclContext(D);
699}
700
701bool CursorVisitor::VisitClassTemplateSpecializationDecl(
702 ClassTemplateSpecializationDecl *D) {
703 bool ShouldVisitBody = false;
704 switch (D->getSpecializationKind()) {
705 case TSK_Undeclared:
706 case TSK_ImplicitInstantiation:
707 // Nothing to visit
708 return false;
709
710 case TSK_ExplicitInstantiationDeclaration:
711 case TSK_ExplicitInstantiationDefinition:
712 break;
713
714 case TSK_ExplicitSpecialization:
715 ShouldVisitBody = true;
716 break;
717 }
718
719 // Visit the template arguments used in the specialization.
720 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
721 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000722 if (TemplateSpecializationTypeLoc TSTLoc =
723 TL.getAs<TemplateSpecializationTypeLoc>()) {
724 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
725 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 return true;
727 }
728 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000729
730 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000731}
732
733bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
734 ClassTemplatePartialSpecializationDecl *D) {
735 // FIXME: Visit the "outer" template parameter lists on the TagDecl
736 // before visiting these template parameters.
737 if (VisitTemplateParameters(D->getTemplateParameters()))
738 return true;
739
740 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000741 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
742 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
743 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000744 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
745 return true;
746
747 return VisitCXXRecordDecl(D);
748}
749
750bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
751 // Visit the default argument.
752 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
753 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
754 if (Visit(DefArg->getTypeLoc()))
755 return true;
756
757 return false;
758}
759
760bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
761 if (Expr *Init = D->getInitExpr())
762 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
763 return false;
764}
765
766bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000767 unsigned NumParamList = DD->getNumTemplateParameterLists();
768 for (unsigned i = 0; i < NumParamList; i++) {
769 TemplateParameterList* Params = DD->getTemplateParameterList(i);
770 if (VisitTemplateParameters(Params))
771 return true;
772 }
773
Guy Benyei11169dd2012-12-18 14:30:41 +0000774 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
775 if (Visit(TSInfo->getTypeLoc()))
776 return true;
777
778 // Visit the nested-name-specifier, if present.
779 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
780 if (VisitNestedNameSpecifierLoc(QualifierLoc))
781 return true;
782
783 return false;
784}
785
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000786/// \brief Compare two base or member initializers based on their source order.
787static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
788 CXXCtorInitializer *const *Y) {
789 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
790}
791
Guy Benyei11169dd2012-12-18 14:30:41 +0000792bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000793 unsigned NumParamList = ND->getNumTemplateParameterLists();
794 for (unsigned i = 0; i < NumParamList; i++) {
795 TemplateParameterList* Params = ND->getTemplateParameterList(i);
796 if (VisitTemplateParameters(Params))
797 return true;
798 }
799
Guy Benyei11169dd2012-12-18 14:30:41 +0000800 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
801 // Visit the function declaration's syntactic components in the order
802 // written. This requires a bit of work.
803 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000804 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000805
806 // If we have a function declared directly (without the use of a typedef),
807 // visit just the return type. Otherwise, just visit the function's type
808 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000809 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 (!FTL && Visit(TL)))
811 return true;
812
813 // Visit the nested-name-specifier, if present.
814 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
815 if (VisitNestedNameSpecifierLoc(QualifierLoc))
816 return true;
817
818 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000819 if (!isa<CXXDestructorDecl>(ND))
820 if (VisitDeclarationNameInfo(ND->getNameInfo()))
821 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000822
823 // FIXME: Visit explicitly-specified template arguments!
824
825 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000826 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000827 return true;
828
Bill Wendling44426052012-12-20 19:22:21 +0000829 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 }
831
832 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
833 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
834 // Find the initializers that were written in the source.
835 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000836 for (auto *I : Constructor->inits()) {
837 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000838 continue;
839
Aaron Ballman0ad78302014-03-13 17:34:31 +0000840 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000841 }
842
843 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000844 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
845 &CompareCXXCtorInitializers);
846
Guy Benyei11169dd2012-12-18 14:30:41 +0000847 // Visit the initializers in source order
848 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
849 CXXCtorInitializer *Init = WrittenInits[I];
850 if (Init->isAnyMemberInitializer()) {
851 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
852 Init->getMemberLocation(), TU)))
853 return true;
854 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
855 if (Visit(TInfo->getTypeLoc()))
856 return true;
857 }
858
859 // Visit the initializer value.
860 if (Expr *Initializer = Init->getInit())
861 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
862 return true;
863 }
864 }
865
866 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
867 return true;
868 }
869
870 return false;
871}
872
873bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
874 if (VisitDeclaratorDecl(D))
875 return true;
876
877 if (Expr *BitWidth = D->getBitWidth())
878 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
879
880 return false;
881}
882
883bool CursorVisitor::VisitVarDecl(VarDecl *D) {
884 if (VisitDeclaratorDecl(D))
885 return true;
886
887 if (Expr *Init = D->getInit())
888 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
889
890 return false;
891}
892
893bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
894 if (VisitDeclaratorDecl(D))
895 return true;
896
897 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
898 if (Expr *DefArg = D->getDefaultArgument())
899 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
900
901 return false;
902}
903
904bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
905 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
906 // before visiting these template parameters.
907 if (VisitTemplateParameters(D->getTemplateParameters()))
908 return true;
909
910 return VisitFunctionDecl(D->getTemplatedDecl());
911}
912
913bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
914 // FIXME: Visit the "outer" template parameter lists on the TagDecl
915 // before visiting these template parameters.
916 if (VisitTemplateParameters(D->getTemplateParameters()))
917 return true;
918
919 return VisitCXXRecordDecl(D->getTemplatedDecl());
920}
921
922bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
923 if (VisitTemplateParameters(D->getTemplateParameters()))
924 return true;
925
926 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
927 VisitTemplateArgumentLoc(D->getDefaultArgument()))
928 return true;
929
930 return false;
931}
932
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000933bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
934 // Visit the bound, if it's explicit.
935 if (D->hasExplicitBound()) {
936 if (auto TInfo = D->getTypeSourceInfo()) {
937 if (Visit(TInfo->getTypeLoc()))
938 return true;
939 }
940 }
941
942 return false;
943}
944
Guy Benyei11169dd2012-12-18 14:30:41 +0000945bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000946 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 if (Visit(TSInfo->getTypeLoc()))
948 return true;
949
David Majnemer59f77922016-06-24 04:05:48 +0000950 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000951 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 return true;
953 }
954
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000955 return ND->isThisDeclarationADefinition() &&
956 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000957}
958
959template <typename DeclIt>
960static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
961 SourceManager &SM, SourceLocation EndLoc,
962 SmallVectorImpl<Decl *> &Decls) {
963 DeclIt next = *DI_current;
964 while (++next != DE_current) {
965 Decl *D_next = *next;
966 if (!D_next)
967 break;
968 SourceLocation L = D_next->getLocStart();
969 if (!L.isValid())
970 break;
971 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
972 *DI_current = next;
973 Decls.push_back(D_next);
974 continue;
975 }
976 break;
977 }
978}
979
Guy Benyei11169dd2012-12-18 14:30:41 +0000980bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
981 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
982 // an @implementation can lexically contain Decls that are not properly
983 // nested in the AST. When we identify such cases, we need to retrofit
984 // this nesting here.
985 if (!DI_current && !FileDI_current)
986 return VisitDeclContext(D);
987
988 // Scan the Decls that immediately come after the container
989 // in the current DeclContext. If any fall within the
990 // container's lexical region, stash them into a vector
991 // for later processing.
992 SmallVector<Decl *, 24> DeclsInContainer;
993 SourceLocation EndLoc = D->getSourceRange().getEnd();
994 SourceManager &SM = AU->getSourceManager();
995 if (EndLoc.isValid()) {
996 if (DI_current) {
997 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
998 DeclsInContainer);
999 } else {
1000 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1001 DeclsInContainer);
1002 }
1003 }
1004
1005 // The common case.
1006 if (DeclsInContainer.empty())
1007 return VisitDeclContext(D);
1008
1009 // Get all the Decls in the DeclContext, and sort them with the
1010 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001011 for (auto *SubDecl : D->decls()) {
1012 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1013 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001014 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001015 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 }
1017
1018 // Now sort the Decls so that they appear in lexical order.
1019 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001020 [&SM](Decl *A, Decl *B) {
1021 SourceLocation L_A = A->getLocStart();
1022 SourceLocation L_B = B->getLocStart();
1023 assert(L_A.isValid() && L_B.isValid());
1024 return SM.isBeforeInTranslationUnit(L_A, L_B);
1025 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001026
1027 // Now visit the decls.
1028 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1029 E = DeclsInContainer.end(); I != E; ++I) {
1030 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001031 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 if (!V.hasValue())
1033 continue;
1034 if (!V.getValue())
1035 return false;
1036 if (Visit(Cursor, true))
1037 return true;
1038 }
1039 return false;
1040}
1041
1042bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1043 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1044 TU)))
1045 return true;
1046
Douglas Gregore9d95f12015-07-07 03:57:35 +00001047 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1048 return true;
1049
Guy Benyei11169dd2012-12-18 14:30:41 +00001050 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1051 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1052 E = ND->protocol_end(); I != E; ++I, ++PL)
1053 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1054 return true;
1055
1056 return VisitObjCContainerDecl(ND);
1057}
1058
1059bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1060 if (!PID->isThisDeclarationADefinition())
1061 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1062
1063 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1064 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1065 E = PID->protocol_end(); I != E; ++I, ++PL)
1066 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1067 return true;
1068
1069 return VisitObjCContainerDecl(PID);
1070}
1071
1072bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1073 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1074 return true;
1075
1076 // FIXME: This implements a workaround with @property declarations also being
1077 // installed in the DeclContext for the @interface. Eventually this code
1078 // should be removed.
1079 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1080 if (!CDecl || !CDecl->IsClassExtension())
1081 return false;
1082
1083 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1084 if (!ID)
1085 return false;
1086
1087 IdentifierInfo *PropertyId = PD->getIdentifier();
1088 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001089 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1090 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001091
1092 if (!prevDecl)
1093 return false;
1094
1095 // Visit synthesized methods since they will be skipped when visiting
1096 // the @interface.
1097 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1098 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1099 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1100 return true;
1101
1102 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1103 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1104 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1105 return true;
1106
1107 return false;
1108}
1109
Douglas Gregore9d95f12015-07-07 03:57:35 +00001110bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1111 if (!typeParamList)
1112 return false;
1113
1114 for (auto *typeParam : *typeParamList) {
1115 // Visit the type parameter.
1116 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1117 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001118 }
1119
1120 return false;
1121}
1122
Guy Benyei11169dd2012-12-18 14:30:41 +00001123bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1124 if (!D->isThisDeclarationADefinition()) {
1125 // Forward declaration is treated like a reference.
1126 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1127 }
1128
Douglas Gregore9d95f12015-07-07 03:57:35 +00001129 // Objective-C type parameters.
1130 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1131 return true;
1132
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 // Issue callbacks for super class.
1134 if (D->getSuperClass() &&
1135 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1136 D->getSuperClassLoc(),
1137 TU)))
1138 return true;
1139
Douglas Gregore9d95f12015-07-07 03:57:35 +00001140 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1141 if (Visit(SuperClassTInfo->getTypeLoc()))
1142 return true;
1143
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1145 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1146 E = D->protocol_end(); I != E; ++I, ++PL)
1147 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1148 return true;
1149
1150 return VisitObjCContainerDecl(D);
1151}
1152
1153bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1154 return VisitObjCContainerDecl(D);
1155}
1156
1157bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1158 // 'ID' could be null when dealing with invalid code.
1159 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1160 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1161 return true;
1162
1163 return VisitObjCImplDecl(D);
1164}
1165
1166bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1167#if 0
1168 // Issue callbacks for super class.
1169 // FIXME: No source location information!
1170 if (D->getSuperClass() &&
1171 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1172 D->getSuperClassLoc(),
1173 TU)))
1174 return true;
1175#endif
1176
1177 return VisitObjCImplDecl(D);
1178}
1179
1180bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1181 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1182 if (PD->isIvarNameSpecified())
1183 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1184
1185 return false;
1186}
1187
1188bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1189 return VisitDeclContext(D);
1190}
1191
1192bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1193 // Visit nested-name-specifier.
1194 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1195 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1196 return true;
1197
1198 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1199 D->getTargetNameLoc(), TU));
1200}
1201
1202bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1203 // Visit nested-name-specifier.
1204 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1205 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1206 return true;
1207 }
1208
1209 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1210 return true;
1211
1212 return VisitDeclarationNameInfo(D->getNameInfo());
1213}
1214
1215bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1216 // Visit nested-name-specifier.
1217 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1218 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1219 return true;
1220
1221 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1222 D->getIdentLocation(), TU));
1223}
1224
1225bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1226 // Visit nested-name-specifier.
1227 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1228 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1229 return true;
1230 }
1231
1232 return VisitDeclarationNameInfo(D->getNameInfo());
1233}
1234
1235bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1236 UnresolvedUsingTypenameDecl *D) {
1237 // Visit nested-name-specifier.
1238 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1239 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1240 return true;
1241
1242 return false;
1243}
1244
Olivier Goffart81978012016-06-09 16:15:55 +00001245bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1246 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1247 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001248 if (StringLiteral *Message = D->getMessage())
1249 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1250 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001251 return false;
1252}
1253
Olivier Goffartd211c642016-11-04 06:29:27 +00001254bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1255 if (NamedDecl *FriendD = D->getFriendDecl()) {
1256 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1257 return true;
1258 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1259 if (Visit(TI->getTypeLoc()))
1260 return true;
1261 }
1262 return false;
1263}
1264
Guy Benyei11169dd2012-12-18 14:30:41 +00001265bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1266 switch (Name.getName().getNameKind()) {
1267 case clang::DeclarationName::Identifier:
1268 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001269 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001270 case clang::DeclarationName::CXXOperatorName:
1271 case clang::DeclarationName::CXXUsingDirective:
1272 return false;
Richard Smith35845152017-02-07 01:37:30 +00001273
Guy Benyei11169dd2012-12-18 14:30:41 +00001274 case clang::DeclarationName::CXXConstructorName:
1275 case clang::DeclarationName::CXXDestructorName:
1276 case clang::DeclarationName::CXXConversionFunctionName:
1277 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1278 return Visit(TSInfo->getTypeLoc());
1279 return false;
1280
1281 case clang::DeclarationName::ObjCZeroArgSelector:
1282 case clang::DeclarationName::ObjCOneArgSelector:
1283 case clang::DeclarationName::ObjCMultiArgSelector:
1284 // FIXME: Per-identifier location info?
1285 return false;
1286 }
1287
1288 llvm_unreachable("Invalid DeclarationName::Kind!");
1289}
1290
1291bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1292 SourceRange Range) {
1293 // FIXME: This whole routine is a hack to work around the lack of proper
1294 // source information in nested-name-specifiers (PR5791). Since we do have
1295 // a beginning source location, we can visit the first component of the
1296 // nested-name-specifier, if it's a single-token component.
1297 if (!NNS)
1298 return false;
1299
1300 // Get the first component in the nested-name-specifier.
1301 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1302 NNS = Prefix;
1303
1304 switch (NNS->getKind()) {
1305 case NestedNameSpecifier::Namespace:
1306 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1307 TU));
1308
1309 case NestedNameSpecifier::NamespaceAlias:
1310 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1311 Range.getBegin(), TU));
1312
1313 case NestedNameSpecifier::TypeSpec: {
1314 // If the type has a form where we know that the beginning of the source
1315 // range matches up with a reference cursor. Visit the appropriate reference
1316 // cursor.
1317 const Type *T = NNS->getAsType();
1318 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1319 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1320 if (const TagType *Tag = dyn_cast<TagType>(T))
1321 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1322 if (const TemplateSpecializationType *TST
1323 = dyn_cast<TemplateSpecializationType>(T))
1324 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1325 break;
1326 }
1327
1328 case NestedNameSpecifier::TypeSpecWithTemplate:
1329 case NestedNameSpecifier::Global:
1330 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001331 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 break;
1333 }
1334
1335 return false;
1336}
1337
1338bool
1339CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1340 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1341 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1342 Qualifiers.push_back(Qualifier);
1343
1344 while (!Qualifiers.empty()) {
1345 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1346 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1347 switch (NNS->getKind()) {
1348 case NestedNameSpecifier::Namespace:
1349 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1350 Q.getLocalBeginLoc(),
1351 TU)))
1352 return true;
1353
1354 break;
1355
1356 case NestedNameSpecifier::NamespaceAlias:
1357 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1358 Q.getLocalBeginLoc(),
1359 TU)))
1360 return true;
1361
1362 break;
1363
1364 case NestedNameSpecifier::TypeSpec:
1365 case NestedNameSpecifier::TypeSpecWithTemplate:
1366 if (Visit(Q.getTypeLoc()))
1367 return true;
1368
1369 break;
1370
1371 case NestedNameSpecifier::Global:
1372 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001373 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 break;
1375 }
1376 }
1377
1378 return false;
1379}
1380
1381bool CursorVisitor::VisitTemplateParameters(
1382 const TemplateParameterList *Params) {
1383 if (!Params)
1384 return false;
1385
1386 for (TemplateParameterList::const_iterator P = Params->begin(),
1387 PEnd = Params->end();
1388 P != PEnd; ++P) {
1389 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1390 return true;
1391 }
1392
1393 return false;
1394}
1395
1396bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1397 switch (Name.getKind()) {
1398 case TemplateName::Template:
1399 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1400
1401 case TemplateName::OverloadedTemplate:
1402 // Visit the overloaded template set.
1403 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1404 return true;
1405
1406 return false;
1407
1408 case TemplateName::DependentTemplate:
1409 // FIXME: Visit nested-name-specifier.
1410 return false;
1411
1412 case TemplateName::QualifiedTemplate:
1413 // FIXME: Visit nested-name-specifier.
1414 return Visit(MakeCursorTemplateRef(
1415 Name.getAsQualifiedTemplateName()->getDecl(),
1416 Loc, TU));
1417
1418 case TemplateName::SubstTemplateTemplateParm:
1419 return Visit(MakeCursorTemplateRef(
1420 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1421 Loc, TU));
1422
1423 case TemplateName::SubstTemplateTemplateParmPack:
1424 return Visit(MakeCursorTemplateRef(
1425 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1426 Loc, TU));
1427 }
1428
1429 llvm_unreachable("Invalid TemplateName::Kind!");
1430}
1431
1432bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1433 switch (TAL.getArgument().getKind()) {
1434 case TemplateArgument::Null:
1435 case TemplateArgument::Integral:
1436 case TemplateArgument::Pack:
1437 return false;
1438
1439 case TemplateArgument::Type:
1440 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1441 return Visit(TSInfo->getTypeLoc());
1442 return false;
1443
1444 case TemplateArgument::Declaration:
1445 if (Expr *E = TAL.getSourceDeclExpression())
1446 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1447 return false;
1448
1449 case TemplateArgument::NullPtr:
1450 if (Expr *E = TAL.getSourceNullPtrExpression())
1451 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1452 return false;
1453
1454 case TemplateArgument::Expression:
1455 if (Expr *E = TAL.getSourceExpression())
1456 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1457 return false;
1458
1459 case TemplateArgument::Template:
1460 case TemplateArgument::TemplateExpansion:
1461 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1462 return true;
1463
1464 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1465 TAL.getTemplateNameLoc());
1466 }
1467
1468 llvm_unreachable("Invalid TemplateArgument::Kind!");
1469}
1470
1471bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1472 return VisitDeclContext(D);
1473}
1474
1475bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1476 return Visit(TL.getUnqualifiedLoc());
1477}
1478
1479bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1480 ASTContext &Context = AU->getASTContext();
1481
1482 // Some builtin types (such as Objective-C's "id", "sel", and
1483 // "Class") have associated declarations. Create cursors for those.
1484 QualType VisitType;
1485 switch (TL.getTypePtr()->getKind()) {
1486
1487 case BuiltinType::Void:
1488 case BuiltinType::NullPtr:
1489 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001490#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1491 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001492#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001493 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001494 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001495 case BuiltinType::OCLClkEvent:
1496 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001497 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}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002267void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2268 const OMPTaskReductionClause *C) {
2269 VisitOMPClauseList(C);
2270 VisitOMPClauseWithPostUpdate(C);
2271 for (auto *E : C->privates()) {
2272 Visitor->AddStmt(E);
2273 }
2274 for (auto *E : C->lhs_exprs()) {
2275 Visitor->AddStmt(E);
2276 }
2277 for (auto *E : C->rhs_exprs()) {
2278 Visitor->AddStmt(E);
2279 }
2280 for (auto *E : C->reduction_ops()) {
2281 Visitor->AddStmt(E);
2282 }
2283}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002284void OMPClauseEnqueue::VisitOMPInReductionClause(
2285 const OMPInReductionClause *C) {
2286 VisitOMPClauseList(C);
2287 VisitOMPClauseWithPostUpdate(C);
2288 for (auto *E : C->privates()) {
2289 Visitor->AddStmt(E);
2290 }
2291 for (auto *E : C->lhs_exprs()) {
2292 Visitor->AddStmt(E);
2293 }
2294 for (auto *E : C->rhs_exprs()) {
2295 Visitor->AddStmt(E);
2296 }
2297 for (auto *E : C->reduction_ops()) {
2298 Visitor->AddStmt(E);
2299 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002300 for (auto *E : C->taskgroup_descriptors())
2301 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002302}
Alexander Musman8dba6642014-04-22 13:09:42 +00002303void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2304 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002305 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002306 for (const auto *E : C->privates()) {
2307 Visitor->AddStmt(E);
2308 }
Alexander Musman3276a272015-03-21 10:12:56 +00002309 for (const auto *E : C->inits()) {
2310 Visitor->AddStmt(E);
2311 }
2312 for (const auto *E : C->updates()) {
2313 Visitor->AddStmt(E);
2314 }
2315 for (const auto *E : C->finals()) {
2316 Visitor->AddStmt(E);
2317 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002318 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002319 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002320}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002321void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2322 VisitOMPClauseList(C);
2323 Visitor->AddStmt(C->getAlignment());
2324}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002325void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2326 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002327 for (auto *E : C->source_exprs()) {
2328 Visitor->AddStmt(E);
2329 }
2330 for (auto *E : C->destination_exprs()) {
2331 Visitor->AddStmt(E);
2332 }
2333 for (auto *E : C->assignment_ops()) {
2334 Visitor->AddStmt(E);
2335 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002336}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002337void
2338OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2339 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002340 for (auto *E : C->source_exprs()) {
2341 Visitor->AddStmt(E);
2342 }
2343 for (auto *E : C->destination_exprs()) {
2344 Visitor->AddStmt(E);
2345 }
2346 for (auto *E : C->assignment_ops()) {
2347 Visitor->AddStmt(E);
2348 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002349}
Alexey Bataev6125da92014-07-21 11:26:11 +00002350void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2351 VisitOMPClauseList(C);
2352}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002353void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2354 VisitOMPClauseList(C);
2355}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002356void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2357 VisitOMPClauseList(C);
2358}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002359void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2360 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002361 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002362 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002363}
Alexey Bataev3392d762016-02-16 11:18:12 +00002364void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2365 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002366void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2367 VisitOMPClauseList(C);
2368}
Samuel Antaoec172c62016-05-26 17:49:04 +00002369void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2370 VisitOMPClauseList(C);
2371}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002372void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2373 VisitOMPClauseList(C);
2374}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002375void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2376 VisitOMPClauseList(C);
2377}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002378}
Alexey Bataev756c1962013-09-24 03:17:45 +00002379
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002380void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2381 unsigned size = WL.size();
2382 OMPClauseEnqueue Visitor(this);
2383 Visitor.Visit(S);
2384 if (size == WL.size())
2385 return;
2386 // Now reverse the entries we just added. This will match the DFS
2387 // ordering performed by the worklist.
2388 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2389 std::reverse(I, E);
2390}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002391void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2393}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002394void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 AddDecl(B->getBlockDecl());
2396}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002397void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 EnqueueChildren(E);
2399 AddTypeLoc(E->getTypeSourceInfo());
2400}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002401void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002402 for (auto &I : llvm::reverse(S->body()))
2403 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002404}
2405void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002406VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 AddStmt(S->getSubStmt());
2408 AddDeclarationNameInfo(S);
2409 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2410 AddNestedNameSpecifierLoc(QualifierLoc);
2411}
2412
2413void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002414VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002415 if (E->hasExplicitTemplateArgs())
2416 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 AddDeclarationNameInfo(E);
2418 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2419 AddNestedNameSpecifierLoc(QualifierLoc);
2420 if (!E->isImplicitAccess())
2421 AddStmt(E->getBase());
2422}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002423void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 // Enqueue the initializer , if any.
2425 AddStmt(E->getInitializer());
2426 // Enqueue the array size, if any.
2427 AddStmt(E->getArraySize());
2428 // Enqueue the allocated type.
2429 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2430 // Enqueue the placement arguments.
2431 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2432 AddStmt(E->getPlacementArg(I-1));
2433}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002434void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2436 AddStmt(CE->getArg(I-1));
2437 AddStmt(CE->getCallee());
2438 AddStmt(CE->getArg(0));
2439}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002440void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2441 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 // Visit the name of the type being destroyed.
2443 AddTypeLoc(E->getDestroyedTypeInfo());
2444 // Visit the scope type that looks disturbingly like the nested-name-specifier
2445 // but isn't.
2446 AddTypeLoc(E->getScopeTypeInfo());
2447 // Visit the nested-name-specifier.
2448 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2449 AddNestedNameSpecifierLoc(QualifierLoc);
2450 // Visit base expression.
2451 AddStmt(E->getBase());
2452}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002453void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2454 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 AddTypeLoc(E->getTypeSourceInfo());
2456}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002457void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2458 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 EnqueueChildren(E);
2460 AddTypeLoc(E->getTypeSourceInfo());
2461}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002462void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 EnqueueChildren(E);
2464 if (E->isTypeOperand())
2465 AddTypeLoc(E->getTypeOperandSourceInfo());
2466}
2467
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002468void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2469 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 EnqueueChildren(E);
2471 AddTypeLoc(E->getTypeSourceInfo());
2472}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002473void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 EnqueueChildren(E);
2475 if (E->isTypeOperand())
2476 AddTypeLoc(E->getTypeOperandSourceInfo());
2477}
2478
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002479void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 EnqueueChildren(S);
2481 AddDecl(S->getExceptionDecl());
2482}
2483
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002484void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002485 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002486 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002487 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002488}
2489
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002490void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002491 if (DR->hasExplicitTemplateArgs())
2492 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 WL.push_back(DeclRefExprParts(DR, Parent));
2494}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002495void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2496 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002497 if (E->hasExplicitTemplateArgs())
2498 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 AddDeclarationNameInfo(E);
2500 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 unsigned size = WL.size();
2504 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002505 for (const auto *D : S->decls()) {
2506 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 isFirst = false;
2508 }
2509 if (size == WL.size())
2510 return;
2511 // Now reverse the entries we just added. This will match the DFS
2512 // ordering performed by the worklist.
2513 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2514 std::reverse(I, E);
2515}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002516void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002518 for (const DesignatedInitExpr::Designator &D :
2519 llvm::reverse(E->designators())) {
2520 if (D.isFieldDesignator()) {
2521 if (FieldDecl *Field = D.getField())
2522 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 continue;
2524 }
David Majnemerf7e36092016-06-23 00:15:04 +00002525 if (D.isArrayDesignator()) {
2526 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 continue;
2528 }
David Majnemerf7e36092016-06-23 00:15:04 +00002529 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2530 AddStmt(E->getArrayRangeEnd(D));
2531 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 }
2533}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 EnqueueChildren(E);
2536 AddTypeLoc(E->getTypeInfoAsWritten());
2537}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002538void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 AddStmt(FS->getBody());
2540 AddStmt(FS->getInc());
2541 AddStmt(FS->getCond());
2542 AddDecl(FS->getConditionVariable());
2543 AddStmt(FS->getInit());
2544}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002545void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2547}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002548void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 AddStmt(If->getElse());
2550 AddStmt(If->getThen());
2551 AddStmt(If->getCond());
2552 AddDecl(If->getConditionVariable());
2553}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002554void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 // We care about the syntactic form of the initializer list, only.
2556 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2557 IE = Syntactic;
2558 EnqueueChildren(IE);
2559}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002560void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 WL.push_back(MemberExprParts(M, Parent));
2562
2563 // If the base of the member access expression is an implicit 'this', don't
2564 // visit it.
2565 // FIXME: If we ever want to show these implicit accesses, this will be
2566 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002567 if (M->isImplicitAccess())
2568 return;
2569
2570 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2571 // real field that that we are interested in.
2572 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2573 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2574 if (FD->isAnonymousStructOrUnion()) {
2575 AddStmt(SubME->getBase());
2576 return;
2577 }
2578 }
2579 }
2580
2581 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002582}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002583void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 AddTypeLoc(E->getEncodedTypeSourceInfo());
2585}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002586void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 EnqueueChildren(M);
2588 AddTypeLoc(M->getClassReceiverTypeInfo());
2589}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002590void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 // Visit the components of the offsetof expression.
2592 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 const OffsetOfNode &Node = E->getComponent(I-1);
2594 switch (Node.getKind()) {
2595 case OffsetOfNode::Array:
2596 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2597 break;
2598 case OffsetOfNode::Field:
2599 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2600 break;
2601 case OffsetOfNode::Identifier:
2602 case OffsetOfNode::Base:
2603 continue;
2604 }
2605 }
2606 // Visit the type into which we're computing the offset.
2607 AddTypeLoc(E->getTypeSourceInfo());
2608}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002609void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002610 if (E->hasExplicitTemplateArgs())
2611 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 WL.push_back(OverloadExprParts(E, Parent));
2613}
2614void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002615 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 EnqueueChildren(E);
2617 if (E->isArgumentType())
2618 AddTypeLoc(E->getArgumentTypeInfo());
2619}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002620void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 EnqueueChildren(S);
2622}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002623void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 AddStmt(S->getBody());
2625 AddStmt(S->getCond());
2626 AddDecl(S->getConditionVariable());
2627}
2628
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002629void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 AddStmt(W->getBody());
2631 AddStmt(W->getCond());
2632 AddDecl(W->getConditionVariable());
2633}
2634
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002635void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 for (unsigned I = E->getNumArgs(); I > 0; --I)
2637 AddTypeLoc(E->getArg(I-1));
2638}
2639
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002640void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 AddTypeLoc(E->getQueriedTypeSourceInfo());
2642}
2643
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002644void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 EnqueueChildren(E);
2646}
2647
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002648void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 VisitOverloadExpr(U);
2650 if (!U->isImplicitAccess())
2651 AddStmt(U->getBase());
2652}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002653void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 AddStmt(E->getSubExpr());
2655 AddTypeLoc(E->getWrittenTypeInfo());
2656}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002657void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 WL.push_back(SizeOfPackExprParts(E, Parent));
2659}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002660void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 // If the opaque value has a source expression, just transparently
2662 // visit that. This is useful for (e.g.) pseudo-object expressions.
2663 if (Expr *SourceExpr = E->getSourceExpr())
2664 return Visit(SourceExpr);
2665}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002666void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 AddStmt(E->getBody());
2668 WL.push_back(LambdaExprParts(E, Parent));
2669}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002670void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 // Treat the expression like its syntactic form.
2672 Visit(E->getSyntacticForm());
2673}
2674
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002675void EnqueueVisitor::VisitOMPExecutableDirective(
2676 const OMPExecutableDirective *D) {
2677 EnqueueChildren(D);
2678 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2679 E = D->clauses().end();
2680 I != E; ++I)
2681 EnqueueChildren(*I);
2682}
2683
Alexander Musman3aaab662014-08-19 11:27:13 +00002684void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2685 VisitOMPExecutableDirective(D);
2686}
2687
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002688void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2689 VisitOMPExecutableDirective(D);
2690}
2691
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002692void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002693 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002694}
2695
Alexey Bataevf29276e2014-06-18 04:14:57 +00002696void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002697 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002698}
2699
Alexander Musmanf82886e2014-09-18 05:12:34 +00002700void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2701 VisitOMPLoopDirective(D);
2702}
2703
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002704void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2705 VisitOMPExecutableDirective(D);
2706}
2707
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002708void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2709 VisitOMPExecutableDirective(D);
2710}
2711
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002712void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2713 VisitOMPExecutableDirective(D);
2714}
2715
Alexander Musman80c22892014-07-17 08:54:58 +00002716void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2717 VisitOMPExecutableDirective(D);
2718}
2719
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002720void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2721 VisitOMPExecutableDirective(D);
2722 AddDeclarationNameInfo(D);
2723}
2724
Alexey Bataev4acb8592014-07-07 13:01:15 +00002725void
2726EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002727 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002728}
2729
Alexander Musmane4e893b2014-09-23 09:33:00 +00002730void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2731 const OMPParallelForSimdDirective *D) {
2732 VisitOMPLoopDirective(D);
2733}
2734
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002735void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2736 const OMPParallelSectionsDirective *D) {
2737 VisitOMPExecutableDirective(D);
2738}
2739
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002740void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2741 VisitOMPExecutableDirective(D);
2742}
2743
Alexey Bataev68446b72014-07-18 07:47:19 +00002744void
2745EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2746 VisitOMPExecutableDirective(D);
2747}
2748
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002749void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2750 VisitOMPExecutableDirective(D);
2751}
2752
Alexey Bataev2df347a2014-07-18 10:17:07 +00002753void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2754 VisitOMPExecutableDirective(D);
2755}
2756
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002757void EnqueueVisitor::VisitOMPTaskgroupDirective(
2758 const OMPTaskgroupDirective *D) {
2759 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002760 if (const Expr *E = D->getReductionRef())
2761 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002762}
2763
Alexey Bataev6125da92014-07-21 11:26:11 +00002764void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2765 VisitOMPExecutableDirective(D);
2766}
2767
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002768void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2769 VisitOMPExecutableDirective(D);
2770}
2771
Alexey Bataev0162e452014-07-22 10:10:35 +00002772void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2773 VisitOMPExecutableDirective(D);
2774}
2775
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002776void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2777 VisitOMPExecutableDirective(D);
2778}
2779
Michael Wong65f367f2015-07-21 13:44:28 +00002780void EnqueueVisitor::VisitOMPTargetDataDirective(const
2781 OMPTargetDataDirective *D) {
2782 VisitOMPExecutableDirective(D);
2783}
2784
Samuel Antaodf67fc42016-01-19 19:15:56 +00002785void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2786 const OMPTargetEnterDataDirective *D) {
2787 VisitOMPExecutableDirective(D);
2788}
2789
Samuel Antao72590762016-01-19 20:04:50 +00002790void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2791 const OMPTargetExitDataDirective *D) {
2792 VisitOMPExecutableDirective(D);
2793}
2794
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002795void EnqueueVisitor::VisitOMPTargetParallelDirective(
2796 const OMPTargetParallelDirective *D) {
2797 VisitOMPExecutableDirective(D);
2798}
2799
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002800void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2801 const OMPTargetParallelForDirective *D) {
2802 VisitOMPLoopDirective(D);
2803}
2804
Alexey Bataev13314bf2014-10-09 04:18:56 +00002805void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2806 VisitOMPExecutableDirective(D);
2807}
2808
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002809void EnqueueVisitor::VisitOMPCancellationPointDirective(
2810 const OMPCancellationPointDirective *D) {
2811 VisitOMPExecutableDirective(D);
2812}
2813
Alexey Bataev80909872015-07-02 11:25:17 +00002814void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2815 VisitOMPExecutableDirective(D);
2816}
2817
Alexey Bataev49f6e782015-12-01 04:18:41 +00002818void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2819 VisitOMPLoopDirective(D);
2820}
2821
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002822void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2823 const OMPTaskLoopSimdDirective *D) {
2824 VisitOMPLoopDirective(D);
2825}
2826
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002827void EnqueueVisitor::VisitOMPDistributeDirective(
2828 const OMPDistributeDirective *D) {
2829 VisitOMPLoopDirective(D);
2830}
2831
Carlo Bertolli9925f152016-06-27 14:55:37 +00002832void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2833 const OMPDistributeParallelForDirective *D) {
2834 VisitOMPLoopDirective(D);
2835}
2836
Kelvin Li4a39add2016-07-05 05:00:15 +00002837void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2838 const OMPDistributeParallelForSimdDirective *D) {
2839 VisitOMPLoopDirective(D);
2840}
2841
Kelvin Li787f3fc2016-07-06 04:45:38 +00002842void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2843 const OMPDistributeSimdDirective *D) {
2844 VisitOMPLoopDirective(D);
2845}
2846
Kelvin Lia579b912016-07-14 02:54:56 +00002847void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2848 const OMPTargetParallelForSimdDirective *D) {
2849 VisitOMPLoopDirective(D);
2850}
2851
Kelvin Li986330c2016-07-20 22:57:10 +00002852void EnqueueVisitor::VisitOMPTargetSimdDirective(
2853 const OMPTargetSimdDirective *D) {
2854 VisitOMPLoopDirective(D);
2855}
2856
Kelvin Li02532872016-08-05 14:37:37 +00002857void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2858 const OMPTeamsDistributeDirective *D) {
2859 VisitOMPLoopDirective(D);
2860}
2861
Kelvin Li4e325f72016-10-25 12:50:55 +00002862void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2863 const OMPTeamsDistributeSimdDirective *D) {
2864 VisitOMPLoopDirective(D);
2865}
2866
Kelvin Li579e41c2016-11-30 23:51:03 +00002867void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2868 const OMPTeamsDistributeParallelForSimdDirective *D) {
2869 VisitOMPLoopDirective(D);
2870}
2871
Kelvin Li7ade93f2016-12-09 03:24:30 +00002872void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2873 const OMPTeamsDistributeParallelForDirective *D) {
2874 VisitOMPLoopDirective(D);
2875}
2876
Kelvin Libf594a52016-12-17 05:48:59 +00002877void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2878 const OMPTargetTeamsDirective *D) {
2879 VisitOMPExecutableDirective(D);
2880}
2881
Kelvin Li83c451e2016-12-25 04:52:54 +00002882void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2883 const OMPTargetTeamsDistributeDirective *D) {
2884 VisitOMPLoopDirective(D);
2885}
2886
Kelvin Li80e8f562016-12-29 22:16:30 +00002887void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2888 const OMPTargetTeamsDistributeParallelForDirective *D) {
2889 VisitOMPLoopDirective(D);
2890}
2891
Kelvin Li1851df52017-01-03 05:23:48 +00002892void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2893 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2894 VisitOMPLoopDirective(D);
2895}
2896
Kelvin Lida681182017-01-10 18:08:18 +00002897void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2898 const OMPTargetTeamsDistributeSimdDirective *D) {
2899 VisitOMPLoopDirective(D);
2900}
2901
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002902void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2904}
2905
2906bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2907 if (RegionOfInterest.isValid()) {
2908 SourceRange Range = getRawCursorExtent(C);
2909 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2910 return false;
2911 }
2912 return true;
2913}
2914
2915bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2916 while (!WL.empty()) {
2917 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002918 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002919
2920 // Set the Parent field, then back to its old value once we're done.
2921 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2922
2923 switch (LI.getKind()) {
2924 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002925 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002926 if (!D)
2927 continue;
2928
2929 // For now, perform default visitation for Decls.
2930 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2931 cast<DeclVisit>(&LI)->isFirst())))
2932 return true;
2933
2934 continue;
2935 }
2936 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002937 for (const TemplateArgumentLoc &Arg :
2938 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2939 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 return true;
2941 }
2942 continue;
2943 }
2944 case VisitorJob::TypeLocVisitKind: {
2945 // Perform default visitation for TypeLocs.
2946 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2947 return true;
2948 continue;
2949 }
2950 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002951 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 if (LabelStmt *stmt = LS->getStmt()) {
2953 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2954 TU))) {
2955 return true;
2956 }
2957 }
2958 continue;
2959 }
2960
2961 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2962 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2963 if (VisitNestedNameSpecifierLoc(V->get()))
2964 return true;
2965 continue;
2966 }
2967
2968 case VisitorJob::DeclarationNameInfoVisitKind: {
2969 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2970 ->get()))
2971 return true;
2972 continue;
2973 }
2974 case VisitorJob::MemberRefVisitKind: {
2975 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2976 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2977 return true;
2978 continue;
2979 }
2980 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002981 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 if (!S)
2983 continue;
2984
2985 // Update the current cursor.
2986 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2987 if (!IsInRegionOfInterest(Cursor))
2988 continue;
2989 switch (Visitor(Cursor, Parent, ClientData)) {
2990 case CXChildVisit_Break: return true;
2991 case CXChildVisit_Continue: break;
2992 case CXChildVisit_Recurse:
2993 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002994 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 EnqueueWorkList(WL, S);
2996 break;
2997 }
2998 continue;
2999 }
3000 case VisitorJob::MemberExprPartsKind: {
3001 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003002 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003003
3004 // Visit the nested-name-specifier
3005 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3006 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3007 return true;
3008
3009 // Visit the declaration name.
3010 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3011 return true;
3012
3013 // Visit the explicitly-specified template arguments, if any.
3014 if (M->hasExplicitTemplateArgs()) {
3015 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3016 *ArgEnd = Arg + M->getNumTemplateArgs();
3017 Arg != ArgEnd; ++Arg) {
3018 if (VisitTemplateArgumentLoc(*Arg))
3019 return true;
3020 }
3021 }
3022 continue;
3023 }
3024 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003025 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003026 // Visit nested-name-specifier, if present.
3027 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3028 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3029 return true;
3030 // Visit declaration name.
3031 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3032 return true;
3033 continue;
3034 }
3035 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003036 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 // Visit the nested-name-specifier.
3038 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3039 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3040 return true;
3041 // Visit the declaration name.
3042 if (VisitDeclarationNameInfo(O->getNameInfo()))
3043 return true;
3044 // Visit the overloaded declaration reference.
3045 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3046 return true;
3047 continue;
3048 }
3049 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003050 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 NamedDecl *Pack = E->getPack();
3052 if (isa<TemplateTypeParmDecl>(Pack)) {
3053 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3054 E->getPackLoc(), TU)))
3055 return true;
3056
3057 continue;
3058 }
3059
3060 if (isa<TemplateTemplateParmDecl>(Pack)) {
3061 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3062 E->getPackLoc(), TU)))
3063 return true;
3064
3065 continue;
3066 }
3067
3068 // Non-type template parameter packs and function parameter packs are
3069 // treated like DeclRefExpr cursors.
3070 continue;
3071 }
3072
3073 case VisitorJob::LambdaExprPartsKind: {
3074 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003075 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3077 CEnd = E->explicit_capture_end();
3078 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003079 // FIXME: Lambda init-captures.
3080 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003082
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3084 C->getLocation(),
3085 TU)))
3086 return true;
3087 }
3088
3089 // Visit parameters and return type, if present.
3090 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3091 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3092 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3093 // Visit the whole type.
3094 if (Visit(TL))
3095 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003096 } else if (FunctionProtoTypeLoc Proto =
3097 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 if (E->hasExplicitParameters()) {
3099 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003100 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3101 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 return true;
3103 } else {
3104 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003105 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 return true;
3107 }
3108 }
3109 }
3110 break;
3111 }
3112
3113 case VisitorJob::PostChildrenVisitKind:
3114 if (PostChildrenVisitor(Parent, ClientData))
3115 return true;
3116 break;
3117 }
3118 }
3119 return false;
3120}
3121
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003122bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003123 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 if (!WorkListFreeList.empty()) {
3125 WL = WorkListFreeList.back();
3126 WL->clear();
3127 WorkListFreeList.pop_back();
3128 }
3129 else {
3130 WL = new VisitorWorkList();
3131 WorkListCache.push_back(WL);
3132 }
3133 EnqueueWorkList(*WL, S);
3134 bool result = RunVisitorWorkList(*WL);
3135 WorkListFreeList.push_back(WL);
3136 return result;
3137}
3138
3139namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003140typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003141RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3142 const DeclarationNameInfo &NI, SourceRange QLoc,
3143 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3145 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3146 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3147
3148 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3149
3150 RefNamePieces Pieces;
3151
3152 if (WantQualifier && QLoc.isValid())
3153 Pieces.push_back(QLoc);
3154
3155 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3156 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003157
3158 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3159 Pieces.push_back(*TemplateArgsLoc);
3160
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 if (Kind == DeclarationName::CXXOperatorName) {
3162 Pieces.push_back(SourceLocation::getFromRawEncoding(
3163 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3164 Pieces.push_back(SourceLocation::getFromRawEncoding(
3165 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3166 }
3167
3168 if (WantSinglePiece) {
3169 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3170 Pieces.clear();
3171 Pieces.push_back(R);
3172 }
3173
3174 return Pieces;
3175}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003176}
Guy Benyei11169dd2012-12-18 14:30:41 +00003177
3178//===----------------------------------------------------------------------===//
3179// Misc. API hooks.
3180//===----------------------------------------------------------------------===//
3181
Chad Rosier05c71aa2013-03-27 18:28:23 +00003182static void fatal_error_handler(void *user_data, const std::string& reason,
3183 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003184 // Write the result out to stderr avoiding errs() because raw_ostreams can
3185 // call report_fatal_error.
3186 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3187 ::abort();
3188}
3189
Chandler Carruth66660742014-06-27 16:37:27 +00003190namespace {
3191struct RegisterFatalErrorHandler {
3192 RegisterFatalErrorHandler() {
3193 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3194 }
3195};
3196}
3197
3198static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3199
Guy Benyei11169dd2012-12-18 14:30:41 +00003200CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3201 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 // We use crash recovery to make some of our APIs more reliable, implicitly
3203 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003204 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3205 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003206
Chandler Carruth66660742014-06-27 16:37:27 +00003207 // Look through the managed static to trigger construction of the managed
3208 // static which registers our fatal error handler. This ensures it is only
3209 // registered once.
3210 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003211
Adrian Prantlbc068582015-07-08 01:00:30 +00003212 // Initialize targets for clang module support.
3213 llvm::InitializeAllTargets();
3214 llvm::InitializeAllTargetMCs();
3215 llvm::InitializeAllAsmPrinters();
3216 llvm::InitializeAllAsmParsers();
3217
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003218 CIndexer *CIdxr = new CIndexer();
3219
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 if (excludeDeclarationsFromPCH)
3221 CIdxr->setOnlyLocalDecls();
3222 if (displayDiagnostics)
3223 CIdxr->setDisplayDiagnostics();
3224
3225 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3226 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3227 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3228 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3229 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3230 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3231
3232 return CIdxr;
3233}
3234
3235void clang_disposeIndex(CXIndex CIdx) {
3236 if (CIdx)
3237 delete static_cast<CIndexer *>(CIdx);
3238}
3239
3240void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3241 if (CIdx)
3242 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3243}
3244
3245unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3246 if (CIdx)
3247 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3248 return 0;
3249}
3250
3251void clang_toggleCrashRecovery(unsigned isEnabled) {
3252 if (isEnabled)
3253 llvm::CrashRecoveryContext::Enable();
3254 else
3255 llvm::CrashRecoveryContext::Disable();
3256}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003257
Guy Benyei11169dd2012-12-18 14:30:41 +00003258CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3259 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003260 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003261 enum CXErrorCode Result =
3262 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003263 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003264 assert((TU && Result == CXError_Success) ||
3265 (!TU && Result != CXError_Success));
3266 return TU;
3267}
3268
3269enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3270 const char *ast_filename,
3271 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003272 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003273 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003274
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003275 if (!CIdx || !ast_filename || !out_TU)
3276 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003277
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003278 LOG_FUNC_SECTION {
3279 *Log << ast_filename;
3280 }
3281
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3283 FileSystemOptions FileSystemOpts;
3284
Justin Bognerd512c1e2014-10-15 00:33:06 +00003285 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3286 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003287 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003288 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3289 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003290 FileSystemOpts, /*UseDebugInfo=*/false,
3291 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003292 /*CaptureDiagnostics=*/true,
3293 /*AllowPCHWithCompilerErrors=*/true,
3294 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003295 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003296 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003297}
3298
3299unsigned clang_defaultEditingTranslationUnitOptions() {
3300 return CXTranslationUnit_PrecompiledPreamble |
3301 CXTranslationUnit_CacheCompletionResults;
3302}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003303
Guy Benyei11169dd2012-12-18 14:30:41 +00003304CXTranslationUnit
3305clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3306 const char *source_filename,
3307 int num_command_line_args,
3308 const char * const *command_line_args,
3309 unsigned num_unsaved_files,
3310 struct CXUnsavedFile *unsaved_files) {
3311 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3312 return clang_parseTranslationUnit(CIdx, source_filename,
3313 command_line_args, num_command_line_args,
3314 unsaved_files, num_unsaved_files,
3315 Options);
3316}
3317
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003318static CXErrorCode
3319clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3320 const char *const *command_line_args,
3321 int num_command_line_args,
3322 ArrayRef<CXUnsavedFile> unsaved_files,
3323 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003324 // Set up the initial return values.
3325 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003326 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003327
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003328 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003329 if (!CIdx || !out_TU)
3330 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003331
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3333
3334 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3335 setThreadBackgroundPriority();
3336
3337 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003338 bool CreatePreambleOnFirstParse =
3339 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003340 // FIXME: Add a flag for modules.
3341 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003342 = (options & (CXTranslationUnit_Incomplete |
3343 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003344 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003345 = options & CXTranslationUnit_CacheCompletionResults;
3346 bool IncludeBriefCommentsInCodeCompletion
3347 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3348 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003349 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003350 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3351
3352 // Configure the diagnostics.
3353 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003354 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003355
Manuel Klimek016c0242016-03-01 10:56:19 +00003356 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003357 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003358
Guy Benyei11169dd2012-12-18 14:30:41 +00003359 // Recover resources if we crash before exiting this function.
3360 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3361 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003362 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003363
Ahmed Charlesb8984322014-03-07 20:03:18 +00003364 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3365 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003366
3367 // Recover resources if we crash before exiting this function.
3368 llvm::CrashRecoveryContextCleanupRegistrar<
3369 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3370
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003371 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003372 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003373 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003374 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 }
3376
Ahmed Charlesb8984322014-03-07 20:03:18 +00003377 std::unique_ptr<std::vector<const char *>> Args(
3378 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003379
3380 // Recover resources if we crash before exiting this method.
3381 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3382 ArgsCleanup(Args.get());
3383
3384 // Since the Clang C library is primarily used by batch tools dealing with
3385 // (often very broken) source code, where spell-checking can have a
3386 // significant negative impact on performance (particularly when
3387 // precompiled headers are involved), we disable it by default.
3388 // Only do this if we haven't found a spell-checking-related argument.
3389 bool FoundSpellCheckingArgument = false;
3390 for (int I = 0; I != num_command_line_args; ++I) {
3391 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3392 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3393 FoundSpellCheckingArgument = true;
3394 break;
3395 }
3396 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003397 Args->insert(Args->end(), command_line_args,
3398 command_line_args + num_command_line_args);
3399
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003400 if (!FoundSpellCheckingArgument)
3401 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3402
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 // The 'source_filename' argument is optional. If the caller does not
3404 // specify it then it is assumed that the source file is specified
3405 // in the actual argument list.
3406 // Put the source file after command_line_args otherwise if '-x' flag is
3407 // present it will be unused.
3408 if (source_filename)
3409 Args->push_back(source_filename);
3410
3411 // Do we need the detailed preprocessing record?
3412 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3413 Args->push_back("-Xclang");
3414 Args->push_back("-detailed-preprocessing-record");
3415 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003416
3417 // Suppress any editor placeholder diagnostics.
3418 Args->push_back("-fallow-editor-placeholders");
3419
Guy Benyei11169dd2012-12-18 14:30:41 +00003420 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003421 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003422 // Unless the user specified that they want the preamble on the first parse
3423 // set it up to be created on the first reparse. This makes the first parse
3424 // faster, trading for a slower (first) reparse.
3425 unsigned PrecompilePreambleAfterNParses =
3426 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003427 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003428 Args->data(), Args->data() + Args->size(),
3429 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003430 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3431 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003432 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3433 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003434 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003435 /*UserFilesAreVolatile=*/true, ForSerialization,
3436 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3437 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003438
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003439 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003440 if (!Unit && !ErrUnit)
3441 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003442
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 if (NumErrors != Diags->getClient()->getNumErrors()) {
3444 // Make sure to check that 'Unit' is non-NULL.
3445 if (CXXIdx->getDisplayDiagnostics())
3446 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3447 }
3448
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003449 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3450 return CXError_ASTReadError;
3451
David Blaikieea4395e2017-01-06 19:49:01 +00003452 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003453 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003454}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003455
3456CXTranslationUnit
3457clang_parseTranslationUnit(CXIndex CIdx,
3458 const char *source_filename,
3459 const char *const *command_line_args,
3460 int num_command_line_args,
3461 struct CXUnsavedFile *unsaved_files,
3462 unsigned num_unsaved_files,
3463 unsigned options) {
3464 CXTranslationUnit TU;
3465 enum CXErrorCode Result = clang_parseTranslationUnit2(
3466 CIdx, source_filename, command_line_args, num_command_line_args,
3467 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003468 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003469 assert((TU && Result == CXError_Success) ||
3470 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003471 return TU;
3472}
3473
3474enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003475 CXIndex CIdx, const char *source_filename,
3476 const char *const *command_line_args, int num_command_line_args,
3477 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3478 unsigned options, CXTranslationUnit *out_TU) {
3479 SmallVector<const char *, 4> Args;
3480 Args.push_back("clang");
3481 Args.append(command_line_args, command_line_args + num_command_line_args);
3482 return clang_parseTranslationUnit2FullArgv(
3483 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3484 num_unsaved_files, options, out_TU);
3485}
3486
3487enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3488 CXIndex CIdx, const char *source_filename,
3489 const char *const *command_line_args, int num_command_line_args,
3490 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3491 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003492 LOG_FUNC_SECTION {
3493 *Log << source_filename << ": ";
3494 for (int i = 0; i != num_command_line_args; ++i)
3495 *Log << command_line_args[i] << " ";
3496 }
3497
Alp Toker9d85b182014-07-07 01:23:14 +00003498 if (num_unsaved_files && !unsaved_files)
3499 return CXError_InvalidArguments;
3500
Alp Toker5c532982014-07-07 22:42:03 +00003501 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003502 auto ParseTranslationUnitImpl = [=, &result] {
3503 result = clang_parseTranslationUnit_Impl(
3504 CIdx, source_filename, command_line_args, num_command_line_args,
3505 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3506 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003507
3508 if (getenv("LIBCLANG_NOTHREADS")) {
3509 ParseTranslationUnitImpl();
3510 return result;
3511 }
3512
Guy Benyei11169dd2012-12-18 14:30:41 +00003513 llvm::CrashRecoveryContext CRC;
3514
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003515 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003516 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3517 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3518 fprintf(stderr, " 'command_line_args' : [");
3519 for (int i = 0; i != num_command_line_args; ++i) {
3520 if (i)
3521 fprintf(stderr, ", ");
3522 fprintf(stderr, "'%s'", command_line_args[i]);
3523 }
3524 fprintf(stderr, "],\n");
3525 fprintf(stderr, " 'unsaved_files' : [");
3526 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3527 if (i)
3528 fprintf(stderr, ", ");
3529 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3530 unsaved_files[i].Length);
3531 }
3532 fprintf(stderr, "],\n");
3533 fprintf(stderr, " 'options' : %d,\n", options);
3534 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003535
3536 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003537 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003538 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003539 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003540 }
Alp Toker5c532982014-07-07 22:42:03 +00003541
3542 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003543}
3544
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003545CXString clang_Type_getObjCEncoding(CXType CT) {
3546 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3547 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3548 std::string encoding;
3549 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3550 encoding);
3551
3552 return cxstring::createDup(encoding);
3553}
3554
3555static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3556 if (C.kind == CXCursor_MacroDefinition) {
3557 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3558 return MDR->getName();
3559 } else if (C.kind == CXCursor_MacroExpansion) {
3560 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3561 return ME.getName();
3562 }
3563 return nullptr;
3564}
3565
3566unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3567 const IdentifierInfo *II = getMacroIdentifier(C);
3568 if (!II) {
3569 return false;
3570 }
3571 ASTUnit *ASTU = getCursorASTUnit(C);
3572 Preprocessor &PP = ASTU->getPreprocessor();
3573 if (const MacroInfo *MI = PP.getMacroInfo(II))
3574 return MI->isFunctionLike();
3575 return false;
3576}
3577
3578unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3579 const IdentifierInfo *II = getMacroIdentifier(C);
3580 if (!II) {
3581 return false;
3582 }
3583 ASTUnit *ASTU = getCursorASTUnit(C);
3584 Preprocessor &PP = ASTU->getPreprocessor();
3585 if (const MacroInfo *MI = PP.getMacroInfo(II))
3586 return MI->isBuiltinMacro();
3587 return false;
3588}
3589
3590unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3591 const Decl *D = getCursorDecl(C);
3592 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3593 if (!FD) {
3594 return false;
3595 }
3596 return FD->isInlined();
3597}
3598
3599static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3600 if (callExpr->getNumArgs() != 1) {
3601 return nullptr;
3602 }
3603
3604 StringLiteral *S = nullptr;
3605 auto *arg = callExpr->getArg(0);
3606 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3607 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3608 auto *subExpr = I->getSubExprAsWritten();
3609
3610 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3611 return nullptr;
3612 }
3613
3614 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3615 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3616 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3617 } else {
3618 return nullptr;
3619 }
3620 return S;
3621}
3622
David Blaikie59272572016-04-13 18:23:33 +00003623struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003624 CXEvalResultKind EvalType;
3625 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003626 unsigned long long unsignedVal;
3627 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003628 double floatVal;
3629 char *stringVal;
3630 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003631 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003632 ~ExprEvalResult() {
3633 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3634 EvalType != CXEval_Int) {
3635 delete EvalData.stringVal;
3636 }
3637 }
3638};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003639
3640void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003641 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003642}
3643
3644CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3645 if (!E) {
3646 return CXEval_UnExposed;
3647 }
3648 return ((ExprEvalResult *)E)->EvalType;
3649}
3650
3651int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003652 return clang_EvalResult_getAsLongLong(E);
3653}
3654
3655long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003656 if (!E) {
3657 return 0;
3658 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003659 ExprEvalResult *Result = (ExprEvalResult*)E;
3660 if (Result->IsUnsignedInt)
3661 return Result->EvalData.unsignedVal;
3662 return Result->EvalData.intVal;
3663}
3664
3665unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3666 return ((ExprEvalResult *)E)->IsUnsignedInt;
3667}
3668
3669unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3670 if (!E) {
3671 return 0;
3672 }
3673
3674 ExprEvalResult *Result = (ExprEvalResult*)E;
3675 if (Result->IsUnsignedInt)
3676 return Result->EvalData.unsignedVal;
3677 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003678}
3679
3680double clang_EvalResult_getAsDouble(CXEvalResult E) {
3681 if (!E) {
3682 return 0;
3683 }
3684 return ((ExprEvalResult *)E)->EvalData.floatVal;
3685}
3686
3687const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3688 if (!E) {
3689 return nullptr;
3690 }
3691 return ((ExprEvalResult *)E)->EvalData.stringVal;
3692}
3693
3694static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3695 Expr::EvalResult ER;
3696 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003697 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003698 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003699
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003700 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003701 if (!expr->EvaluateAsRValue(ER, ctx))
3702 return nullptr;
3703
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003704 QualType rettype;
3705 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003706 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003707 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003708 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003709
David Blaikiebbc00882016-04-13 18:36:19 +00003710 if (ER.Val.isInt()) {
3711 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003712
3713 auto& val = ER.Val.getInt();
3714 if (val.isUnsigned()) {
3715 result->IsUnsignedInt = true;
3716 result->EvalData.unsignedVal = val.getZExtValue();
3717 } else {
3718 result->EvalData.intVal = val.getExtValue();
3719 }
3720
David Blaikiebbc00882016-04-13 18:36:19 +00003721 return result.release();
3722 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003723
David Blaikiebbc00882016-04-13 18:36:19 +00003724 if (ER.Val.isFloat()) {
3725 llvm::SmallVector<char, 100> Buffer;
3726 ER.Val.getFloat().toString(Buffer);
3727 std::string floatStr(Buffer.data(), Buffer.size());
3728 result->EvalType = CXEval_Float;
3729 bool ignored;
3730 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003731 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003732 llvm::APFloat::rmNearestTiesToEven, &ignored);
3733 result->EvalData.floatVal = apFloat.convertToDouble();
3734 return result.release();
3735 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003736
David Blaikiebbc00882016-04-13 18:36:19 +00003737 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3738 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3739 auto *subExpr = I->getSubExprAsWritten();
3740 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3741 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003742 const StringLiteral *StrE = nullptr;
3743 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003744 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003745
3746 if (ObjCExpr) {
3747 StrE = ObjCExpr->getString();
3748 result->EvalType = CXEval_ObjCStrLiteral;
3749 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003750 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003751 result->EvalType = CXEval_StrLiteral;
3752 }
3753
3754 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003755 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003756 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3757 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003758 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003759 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003760 }
3761 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3762 expr->getStmtClass() == Stmt::StringLiteralClass) {
3763 const StringLiteral *StrE = nullptr;
3764 const ObjCStringLiteral *ObjCExpr;
3765 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003766
David Blaikiebbc00882016-04-13 18:36:19 +00003767 if (ObjCExpr) {
3768 StrE = ObjCExpr->getString();
3769 result->EvalType = CXEval_ObjCStrLiteral;
3770 } else {
3771 StrE = cast<StringLiteral>(expr);
3772 result->EvalType = CXEval_StrLiteral;
3773 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003774
David Blaikiebbc00882016-04-13 18:36:19 +00003775 std::string strRef(StrE->getString().str());
3776 result->EvalData.stringVal = new char[strRef.size() + 1];
3777 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3778 result->EvalData.stringVal[strRef.size()] = '\0';
3779 return result.release();
3780 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003781
David Blaikiebbc00882016-04-13 18:36:19 +00003782 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3783 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003784
David Blaikiebbc00882016-04-13 18:36:19 +00003785 rettype = CC->getType();
3786 if (rettype.getAsString() == "CFStringRef" &&
3787 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003788
David Blaikiebbc00882016-04-13 18:36:19 +00003789 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3790 StringLiteral *S = getCFSTR_value(callExpr);
3791 if (S) {
3792 std::string strLiteral(S->getString().str());
3793 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003794
David Blaikiebbc00882016-04-13 18:36:19 +00003795 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3796 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3797 strLiteral.size());
3798 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003799 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003800 }
3801 }
3802
David Blaikiebbc00882016-04-13 18:36:19 +00003803 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3804 callExpr = static_cast<CallExpr *>(expr);
3805 rettype = callExpr->getCallReturnType(ctx);
3806
3807 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3808 return nullptr;
3809
3810 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3811 if (callExpr->getNumArgs() == 1 &&
3812 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3813 return nullptr;
3814 } else if (rettype.getAsString() == "CFStringRef") {
3815
3816 StringLiteral *S = getCFSTR_value(callExpr);
3817 if (S) {
3818 std::string strLiteral(S->getString().str());
3819 result->EvalType = CXEval_CFStr;
3820 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3821 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3822 strLiteral.size());
3823 result->EvalData.stringVal[strLiteral.size()] = '\0';
3824 return result.release();
3825 }
3826 }
3827 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3828 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3829 ValueDecl *V = D->getDecl();
3830 if (V->getKind() == Decl::Function) {
3831 std::string strName = V->getNameAsString();
3832 result->EvalType = CXEval_Other;
3833 result->EvalData.stringVal = new char[strName.size() + 1];
3834 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3835 result->EvalData.stringVal[strName.size()] = '\0';
3836 return result.release();
3837 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003838 }
3839
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003840 return nullptr;
3841}
3842
3843CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3844 const Decl *D = getCursorDecl(C);
3845 if (D) {
3846 const Expr *expr = nullptr;
3847 if (auto *Var = dyn_cast<VarDecl>(D)) {
3848 expr = Var->getInit();
3849 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3850 expr = Field->getInClassInitializer();
3851 }
3852 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003853 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3854 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003855 return nullptr;
3856 }
3857
3858 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3859 if (compoundStmt) {
3860 Expr *expr = nullptr;
3861 for (auto *bodyIterator : compoundStmt->body()) {
3862 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3863 break;
3864 }
3865 }
3866 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003867 return const_cast<CXEvalResult>(
3868 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003869 }
3870 return nullptr;
3871}
3872
3873unsigned clang_Cursor_hasAttrs(CXCursor C) {
3874 const Decl *D = getCursorDecl(C);
3875 if (!D) {
3876 return 0;
3877 }
3878
3879 if (D->hasAttrs()) {
3880 return 1;
3881 }
3882
3883 return 0;
3884}
Guy Benyei11169dd2012-12-18 14:30:41 +00003885unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3886 return CXSaveTranslationUnit_None;
3887}
3888
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003889static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3890 const char *FileName,
3891 unsigned options) {
3892 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3894 setThreadBackgroundPriority();
3895
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003896 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3897 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003898}
3899
3900int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3901 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003902 LOG_FUNC_SECTION {
3903 *Log << TU << ' ' << FileName;
3904 }
3905
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003906 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003907 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003909 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003910
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003911 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003912 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3913 if (!CXXUnit->hasSema())
3914 return CXSaveError_InvalidTU;
3915
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003916 CXSaveError result;
3917 auto SaveTranslationUnitImpl = [=, &result]() {
3918 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3919 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003920
3921 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3922 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003923 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003924
3925 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3926 PrintLibclangResourceUsage(TU);
3927
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003928 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 }
3930
3931 // We have an AST that has invalid nodes due to compiler errors.
3932 // Use a crash recovery thread for protection.
3933
3934 llvm::CrashRecoveryContext CRC;
3935
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003936 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003937 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3938 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3939 fprintf(stderr, " 'options' : %d,\n", options);
3940 fprintf(stderr, "}\n");
3941
3942 return CXSaveError_Unknown;
3943
3944 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3945 PrintLibclangResourceUsage(TU);
3946 }
3947
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003948 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003949}
3950
3951void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3952 if (CTUnit) {
3953 // If the translation unit has been marked as unsafe to free, just discard
3954 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003955 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3956 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003957 return;
3958
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003959 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003960 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3962 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003963 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003964 delete CTUnit;
3965 }
3966}
3967
Erik Verbruggen346066b2017-05-30 14:25:54 +00003968unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
3969 if (CTUnit) {
3970 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3971
3972 if (Unit && Unit->isUnsafeToFree())
3973 return false;
3974
3975 Unit->ResetForParse();
3976 return true;
3977 }
3978
3979 return false;
3980}
3981
Guy Benyei11169dd2012-12-18 14:30:41 +00003982unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3983 return CXReparse_None;
3984}
3985
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003986static CXErrorCode
3987clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3988 ArrayRef<CXUnsavedFile> unsaved_files,
3989 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003990 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003991 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003992 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003993 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003994 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003995
3996 // Reset the associated diagnostics.
3997 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003998 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003999
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004000 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4002 setThreadBackgroundPriority();
4003
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004004 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004006
4007 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4008 new std::vector<ASTUnit::RemappedFile>());
4009
Guy Benyei11169dd2012-12-18 14:30:41 +00004010 // Recover resources if we crash before exiting this function.
4011 llvm::CrashRecoveryContextCleanupRegistrar<
4012 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004013
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004014 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004015 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004016 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004017 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004019
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004020 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4021 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004022 return CXError_Success;
4023 if (isASTReadError(CXXUnit))
4024 return CXError_ASTReadError;
4025 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004026}
4027
4028int clang_reparseTranslationUnit(CXTranslationUnit TU,
4029 unsigned num_unsaved_files,
4030 struct CXUnsavedFile *unsaved_files,
4031 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004032 LOG_FUNC_SECTION {
4033 *Log << TU;
4034 }
4035
Alp Toker9d85b182014-07-07 01:23:14 +00004036 if (num_unsaved_files && !unsaved_files)
4037 return CXError_InvalidArguments;
4038
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004039 CXErrorCode result;
4040 auto ReparseTranslationUnitImpl = [=, &result]() {
4041 result = clang_reparseTranslationUnit_Impl(
4042 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4043 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004044
4045 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004046 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00004047 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 }
4049
4050 llvm::CrashRecoveryContext CRC;
4051
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004052 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004053 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004054 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004055 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4057 PrintLibclangResourceUsage(TU);
4058
Alp Toker5c532982014-07-07 22:42:03 +00004059 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004060}
4061
4062
4063CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004064 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004065 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004066 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004067 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004068
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004069 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004070 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004071}
4072
4073CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004074 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004075 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004076 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004077 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004078
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004079 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004080 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4081}
4082
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004083CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4084 if (isNotUsableTU(CTUnit)) {
4085 LOG_BAD_TU(CTUnit);
4086 return nullptr;
4087 }
4088
4089 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4090 impl->TranslationUnit = CTUnit;
4091 return impl;
4092}
4093
4094CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4095 if (!TargetInfo)
4096 return cxstring::createEmpty();
4097
4098 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4099 assert(!isNotUsableTU(CTUnit) &&
4100 "Unexpected unusable translation unit in TargetInfo");
4101
4102 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4103 std::string Triple =
4104 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4105 return cxstring::createDup(Triple);
4106}
4107
4108int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4109 if (!TargetInfo)
4110 return -1;
4111
4112 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4113 assert(!isNotUsableTU(CTUnit) &&
4114 "Unexpected unusable translation unit in TargetInfo");
4115
4116 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4117 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4118}
4119
4120void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4121 if (!TargetInfo)
4122 return;
4123
4124 delete TargetInfo;
4125}
4126
Guy Benyei11169dd2012-12-18 14:30:41 +00004127//===----------------------------------------------------------------------===//
4128// CXFile Operations.
4129//===----------------------------------------------------------------------===//
4130
Guy Benyei11169dd2012-12-18 14:30:41 +00004131CXString clang_getFileName(CXFile SFile) {
4132 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004133 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004134
4135 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004136 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004137}
4138
4139time_t clang_getFileTime(CXFile SFile) {
4140 if (!SFile)
4141 return 0;
4142
4143 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4144 return FEnt->getModificationTime();
4145}
4146
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004147CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004148 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004149 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004150 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004151 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004152
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004153 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004154
4155 FileManager &FMgr = CXXUnit->getFileManager();
4156 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4157}
4158
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004159unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4160 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004161 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004162 LOG_BAD_TU(TU);
4163 return 0;
4164 }
4165
4166 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004167 return 0;
4168
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004169 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004170 FileEntry *FEnt = static_cast<FileEntry *>(file);
4171 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4172 .isFileMultipleIncludeGuarded(FEnt);
4173}
4174
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004175int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4176 if (!file || !outID)
4177 return 1;
4178
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004179 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004180 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4181 outID->data[0] = ID.getDevice();
4182 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004183 outID->data[2] = FEnt->getModificationTime();
4184 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004185}
4186
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004187int clang_File_isEqual(CXFile file1, CXFile file2) {
4188 if (file1 == file2)
4189 return true;
4190
4191 if (!file1 || !file2)
4192 return false;
4193
4194 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4195 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4196 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4197}
4198
Guy Benyei11169dd2012-12-18 14:30:41 +00004199//===----------------------------------------------------------------------===//
4200// CXCursor Operations.
4201//===----------------------------------------------------------------------===//
4202
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004203static const Decl *getDeclFromExpr(const Stmt *E) {
4204 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 return getDeclFromExpr(CE->getSubExpr());
4206
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004207 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004209 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004211 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004213 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 if (PRE->isExplicitProperty())
4215 return PRE->getExplicitProperty();
4216 // It could be messaging both getter and setter as in:
4217 // ++myobj.myprop;
4218 // in which case prefer to associate the setter since it is less obvious
4219 // from inspecting the source that the setter is going to get called.
4220 if (PRE->isMessagingSetter())
4221 return PRE->getImplicitPropertySetter();
4222 return PRE->getImplicitPropertyGetter();
4223 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004224 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004225 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004226 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 if (Expr *Src = OVE->getSourceExpr())
4228 return getDeclFromExpr(Src);
4229
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004230 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004232 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004233 if (!CE->isElidable())
4234 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004235 if (const CXXInheritedCtorInitExpr *CE =
4236 dyn_cast<CXXInheritedCtorInitExpr>(E))
4237 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004238 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 return OME->getMethodDecl();
4240
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004241 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004243 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4245 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004246 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4248 isa<ParmVarDecl>(SizeOfPack->getPack()))
4249 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004250
4251 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004252}
4253
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004254static SourceLocation getLocationFromExpr(const Expr *E) {
4255 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 return getLocationFromExpr(CE->getSubExpr());
4257
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004258 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004260 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004262 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004264 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004266 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004268 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 return PropRef->getLocation();
4270
4271 return E->getLocStart();
4272}
4273
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004274extern "C" {
4275
Guy Benyei11169dd2012-12-18 14:30:41 +00004276unsigned clang_visitChildren(CXCursor parent,
4277 CXCursorVisitor visitor,
4278 CXClientData client_data) {
4279 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4280 /*VisitPreprocessorLast=*/false);
4281 return CursorVis.VisitChildren(parent);
4282}
4283
4284#ifndef __has_feature
4285#define __has_feature(x) 0
4286#endif
4287#if __has_feature(blocks)
4288typedef enum CXChildVisitResult
4289 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4290
4291static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4292 CXClientData client_data) {
4293 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4294 return block(cursor, parent);
4295}
4296#else
4297// If we are compiled with a compiler that doesn't have native blocks support,
4298// define and call the block manually, so the
4299typedef struct _CXChildVisitResult
4300{
4301 void *isa;
4302 int flags;
4303 int reserved;
4304 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4305 CXCursor);
4306} *CXCursorVisitorBlock;
4307
4308static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4309 CXClientData client_data) {
4310 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4311 return block->invoke(block, cursor, parent);
4312}
4313#endif
4314
4315
4316unsigned clang_visitChildrenWithBlock(CXCursor parent,
4317 CXCursorVisitorBlock block) {
4318 return clang_visitChildren(parent, visitWithBlock, block);
4319}
4320
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004321static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004323 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004324
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004325 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004327 if (const ObjCPropertyImplDecl *PropImpl =
4328 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004330 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004331
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004332 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004334 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004335
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004336 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 }
4338
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004339 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004340 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004341
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004342 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4344 // and returns different names. NamedDecl returns the class name and
4345 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004346 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004347
4348 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004349 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004350
4351 SmallString<1024> S;
4352 llvm::raw_svector_ostream os(S);
4353 ND->printName(os);
4354
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004355 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004356}
4357
4358CXString clang_getCursorSpelling(CXCursor C) {
4359 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004360 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004361
4362 if (clang_isReference(C.kind)) {
4363 switch (C.kind) {
4364 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004365 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004366 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 }
4368 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004369 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004370 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 }
4372 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004373 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004375 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 }
4377 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004378 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004379 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 }
4381 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004382 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 assert(Type && "Missing type decl");
4384
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004385 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 getAsString());
4387 }
4388 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004389 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 assert(Template && "Missing template decl");
4391
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004392 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004393 }
4394
4395 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004396 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 assert(NS && "Missing namespace decl");
4398
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004399 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 }
4401
4402 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004403 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 assert(Field && "Missing member decl");
4405
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004406 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 }
4408
4409 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004410 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 assert(Label && "Missing label");
4412
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004413 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004414 }
4415
4416 case CXCursor_OverloadedDeclRef: {
4417 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004418 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4419 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004420 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004421 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004423 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004424 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004425 OverloadedTemplateStorage *Ovl
4426 = Storage.get<OverloadedTemplateStorage*>();
4427 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004428 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004429 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 }
4431
4432 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004433 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 assert(Var && "Missing variable decl");
4435
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004436 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 }
4438
4439 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004440 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 }
4442 }
4443
4444 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004445 const Expr *E = getCursorExpr(C);
4446
4447 if (C.kind == CXCursor_ObjCStringLiteral ||
4448 C.kind == CXCursor_StringLiteral) {
4449 const StringLiteral *SLit;
4450 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4451 SLit = OSL->getString();
4452 } else {
4453 SLit = cast<StringLiteral>(E);
4454 }
4455 SmallString<256> Buf;
4456 llvm::raw_svector_ostream OS(Buf);
4457 SLit->outputString(OS);
4458 return cxstring::createDup(OS.str());
4459 }
4460
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004461 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 if (D)
4463 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004464 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 }
4466
4467 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004468 const Stmt *S = getCursorStmt(C);
4469 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004470 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004471
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004472 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 }
4474
4475 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004476 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 ->getNameStart());
4478
4479 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004480 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 ->getNameStart());
4482
4483 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004484 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004485
4486 if (clang_isDeclaration(C.kind))
4487 return getDeclSpelling(getCursorDecl(C));
4488
4489 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004490 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004491 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 }
4493
4494 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004495 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004496 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 }
4498
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004499 if (C.kind == CXCursor_PackedAttr) {
4500 return cxstring::createRef("packed");
4501 }
4502
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004503 if (C.kind == CXCursor_VisibilityAttr) {
4504 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4505 switch (AA->getVisibility()) {
4506 case VisibilityAttr::VisibilityType::Default:
4507 return cxstring::createRef("default");
4508 case VisibilityAttr::VisibilityType::Hidden:
4509 return cxstring::createRef("hidden");
4510 case VisibilityAttr::VisibilityType::Protected:
4511 return cxstring::createRef("protected");
4512 }
4513 llvm_unreachable("unknown visibility type");
4514 }
4515
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004516 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004517}
4518
4519CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4520 unsigned pieceIndex,
4521 unsigned options) {
4522 if (clang_Cursor_isNull(C))
4523 return clang_getNullRange();
4524
4525 ASTContext &Ctx = getCursorContext(C);
4526
4527 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004528 const Stmt *S = getCursorStmt(C);
4529 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 if (pieceIndex > 0)
4531 return clang_getNullRange();
4532 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4533 }
4534
4535 return clang_getNullRange();
4536 }
4537
4538 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004539 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4541 if (pieceIndex >= ME->getNumSelectorLocs())
4542 return clang_getNullRange();
4543 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4544 }
4545 }
4546
4547 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4548 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004549 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4551 if (pieceIndex >= MD->getNumSelectorLocs())
4552 return clang_getNullRange();
4553 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4554 }
4555 }
4556
4557 if (C.kind == CXCursor_ObjCCategoryDecl ||
4558 C.kind == CXCursor_ObjCCategoryImplDecl) {
4559 if (pieceIndex > 0)
4560 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004561 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004562 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4563 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004564 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4566 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4567 }
4568
4569 if (C.kind == CXCursor_ModuleImportDecl) {
4570 if (pieceIndex > 0)
4571 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004572 if (const ImportDecl *ImportD =
4573 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4575 if (!Locs.empty())
4576 return cxloc::translateSourceRange(Ctx,
4577 SourceRange(Locs.front(), Locs.back()));
4578 }
4579 return clang_getNullRange();
4580 }
4581
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004582 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004583 C.kind == CXCursor_ConversionFunction ||
4584 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004585 if (pieceIndex > 0)
4586 return clang_getNullRange();
4587 if (const FunctionDecl *FD =
4588 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4589 DeclarationNameInfo FunctionName = FD->getNameInfo();
4590 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4591 }
4592 return clang_getNullRange();
4593 }
4594
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 // FIXME: A CXCursor_InclusionDirective should give the location of the
4596 // filename, but we don't keep track of this.
4597
4598 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4599 // but we don't keep track of this.
4600
4601 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4602 // but we don't keep track of this.
4603
4604 // Default handling, give the location of the cursor.
4605
4606 if (pieceIndex > 0)
4607 return clang_getNullRange();
4608
4609 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4610 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4611 return cxloc::translateSourceRange(Ctx, Loc);
4612}
4613
Eli Bendersky44a206f2014-07-31 18:04:56 +00004614CXString clang_Cursor_getMangling(CXCursor C) {
4615 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4616 return cxstring::createEmpty();
4617
Eli Bendersky44a206f2014-07-31 18:04:56 +00004618 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004619 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004620 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4621 return cxstring::createEmpty();
4622
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004623 ASTContext &Ctx = D->getASTContext();
4624 index::CodegenNameGenerator CGNameGen(Ctx);
4625 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004626}
4627
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004628CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4629 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4630 return nullptr;
4631
4632 const Decl *D = getCursorDecl(C);
4633 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4634 return nullptr;
4635
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004636 ASTContext &Ctx = D->getASTContext();
4637 index::CodegenNameGenerator CGNameGen(Ctx);
4638 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004639 return cxstring::createSet(Manglings);
4640}
4641
Dave Lee1a532c92017-09-22 16:58:57 +00004642CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4643 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4644 return nullptr;
4645
4646 const Decl *D = getCursorDecl(C);
4647 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4648 return nullptr;
4649
4650 ASTContext &Ctx = D->getASTContext();
4651 index::CodegenNameGenerator CGNameGen(Ctx);
4652 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4653 return cxstring::createSet(Manglings);
4654}
4655
Guy Benyei11169dd2012-12-18 14:30:41 +00004656CXString clang_getCursorDisplayName(CXCursor C) {
4657 if (!clang_isDeclaration(C.kind))
4658 return clang_getCursorSpelling(C);
4659
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004660 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004662 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004663
4664 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004665 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 D = FunTmpl->getTemplatedDecl();
4667
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004668 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 SmallString<64> Str;
4670 llvm::raw_svector_ostream OS(Str);
4671 OS << *Function;
4672 if (Function->getPrimaryTemplate())
4673 OS << "<>";
4674 OS << "(";
4675 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4676 if (I)
4677 OS << ", ";
4678 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4679 }
4680
4681 if (Function->isVariadic()) {
4682 if (Function->getNumParams())
4683 OS << ", ";
4684 OS << "...";
4685 }
4686 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004687 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 }
4689
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004690 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 SmallString<64> Str;
4692 llvm::raw_svector_ostream OS(Str);
4693 OS << *ClassTemplate;
4694 OS << "<";
4695 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4696 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4697 if (I)
4698 OS << ", ";
4699
4700 NamedDecl *Param = Params->getParam(I);
4701 if (Param->getIdentifier()) {
4702 OS << Param->getIdentifier()->getName();
4703 continue;
4704 }
4705
4706 // There is no parameter name, which makes this tricky. Try to come up
4707 // with something useful that isn't too long.
4708 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4709 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4710 else if (NonTypeTemplateParmDecl *NTTP
4711 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4712 OS << NTTP->getType().getAsString(Policy);
4713 else
4714 OS << "template<...> class";
4715 }
4716
4717 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004718 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 }
4720
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004721 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004722 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4723 // If the type was explicitly written, use that.
4724 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004725 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004726
Benjamin Kramer9170e912013-02-22 15:46:01 +00004727 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 llvm::raw_svector_ostream OS(Str);
4729 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004730 TemplateSpecializationType::PrintTemplateArgumentList(
4731 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004732 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 }
4734
4735 return clang_getCursorSpelling(C);
4736}
4737
4738CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4739 switch (Kind) {
4740 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004741 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004743 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004745 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004747 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004749 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004751 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004753 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004755 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004756 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004757 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004759 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004761 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004762 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004763 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004765 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004767 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004768 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004769 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004770 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004771 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004773 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004775 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004777 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004779 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004781 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004783 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004785 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004786 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004787 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004789 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004791 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004793 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004795 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004796 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004797 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004798 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004799 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004801 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004803 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004805 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004806 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004807 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004808 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004809 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004811 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004813 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004814 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004815 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004817 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004818 case CXCursor_OMPArraySectionExpr:
4819 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004821 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004823 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004824 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004825 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004826 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004827 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004829 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004830 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004831 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004833 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004835 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004837 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004838 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004839 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004840 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004841 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004843 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004845 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004847 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004848 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004849 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004851 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004853 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004855 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004856 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004857 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004859 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004861 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004862 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004863 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004864 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004865 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004866 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004867 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004869 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004870 case CXCursor_ObjCAvailabilityCheckExpr:
4871 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004872 case CXCursor_ObjCSelfExpr:
4873 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004875 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004877 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004879 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004881 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004883 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004884 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004885 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004886 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004887 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004888 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004889 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004891 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004893 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004895 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004896 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004897 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004899 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004901 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004902 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004903 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004904 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004905 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004907 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004909 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004910 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004911 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004913 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004914 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004915 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004916 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004917 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004919 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004921 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004923 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004924 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004925 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004926 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004927 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004929 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004931 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004932 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004933 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004935 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004937 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004939 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004941 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004943 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004944 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004945 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004946 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004947 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004948 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004949 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004950 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004951 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004952 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004953 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004955 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004956 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004957 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004958 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004959 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004960 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004961 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004962 case CXCursor_SEHLeaveStmt:
4963 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004965 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004967 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004969 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004970 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004971 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004972 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004973 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004975 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004977 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004979 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004980 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004981 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004982 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004983 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004985 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004987 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004989 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004991 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004992 case CXCursor_PackedAttr:
4993 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004994 case CXCursor_PureAttr:
4995 return cxstring::createRef("attribute(pure)");
4996 case CXCursor_ConstAttr:
4997 return cxstring::createRef("attribute(const)");
4998 case CXCursor_NoDuplicateAttr:
4999 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005000 case CXCursor_CUDAConstantAttr:
5001 return cxstring::createRef("attribute(constant)");
5002 case CXCursor_CUDADeviceAttr:
5003 return cxstring::createRef("attribute(device)");
5004 case CXCursor_CUDAGlobalAttr:
5005 return cxstring::createRef("attribute(global)");
5006 case CXCursor_CUDAHostAttr:
5007 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005008 case CXCursor_CUDASharedAttr:
5009 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005010 case CXCursor_VisibilityAttr:
5011 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005012 case CXCursor_DLLExport:
5013 return cxstring::createRef("attribute(dllexport)");
5014 case CXCursor_DLLImport:
5015 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005017 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005019 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005021 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005023 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005025 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005027 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005029 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005031 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005033 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005035 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005037 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005039 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005041 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005043 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005045 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005047 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005049 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005051 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005053 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005055 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005057 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005061 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005064 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005065 return cxstring::createRef("OMPParallelDirective");
5066 case CXCursor_OMPSimdDirective:
5067 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005068 case CXCursor_OMPForDirective:
5069 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005070 case CXCursor_OMPForSimdDirective:
5071 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005072 case CXCursor_OMPSectionsDirective:
5073 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005074 case CXCursor_OMPSectionDirective:
5075 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005076 case CXCursor_OMPSingleDirective:
5077 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005078 case CXCursor_OMPMasterDirective:
5079 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005080 case CXCursor_OMPCriticalDirective:
5081 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005082 case CXCursor_OMPParallelForDirective:
5083 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005084 case CXCursor_OMPParallelForSimdDirective:
5085 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005086 case CXCursor_OMPParallelSectionsDirective:
5087 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005088 case CXCursor_OMPTaskDirective:
5089 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005090 case CXCursor_OMPTaskyieldDirective:
5091 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005092 case CXCursor_OMPBarrierDirective:
5093 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005094 case CXCursor_OMPTaskwaitDirective:
5095 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005096 case CXCursor_OMPTaskgroupDirective:
5097 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005098 case CXCursor_OMPFlushDirective:
5099 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005100 case CXCursor_OMPOrderedDirective:
5101 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005102 case CXCursor_OMPAtomicDirective:
5103 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005104 case CXCursor_OMPTargetDirective:
5105 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005106 case CXCursor_OMPTargetDataDirective:
5107 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005108 case CXCursor_OMPTargetEnterDataDirective:
5109 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005110 case CXCursor_OMPTargetExitDataDirective:
5111 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005112 case CXCursor_OMPTargetParallelDirective:
5113 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005114 case CXCursor_OMPTargetParallelForDirective:
5115 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005116 case CXCursor_OMPTargetUpdateDirective:
5117 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005118 case CXCursor_OMPTeamsDirective:
5119 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005120 case CXCursor_OMPCancellationPointDirective:
5121 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005122 case CXCursor_OMPCancelDirective:
5123 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005124 case CXCursor_OMPTaskLoopDirective:
5125 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005126 case CXCursor_OMPTaskLoopSimdDirective:
5127 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005128 case CXCursor_OMPDistributeDirective:
5129 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005130 case CXCursor_OMPDistributeParallelForDirective:
5131 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005132 case CXCursor_OMPDistributeParallelForSimdDirective:
5133 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005134 case CXCursor_OMPDistributeSimdDirective:
5135 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005136 case CXCursor_OMPTargetParallelForSimdDirective:
5137 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005138 case CXCursor_OMPTargetSimdDirective:
5139 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005140 case CXCursor_OMPTeamsDistributeDirective:
5141 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005142 case CXCursor_OMPTeamsDistributeSimdDirective:
5143 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005144 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5145 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005146 case CXCursor_OMPTeamsDistributeParallelForDirective:
5147 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005148 case CXCursor_OMPTargetTeamsDirective:
5149 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005150 case CXCursor_OMPTargetTeamsDistributeDirective:
5151 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005152 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5153 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005154 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5155 return cxstring::createRef(
5156 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005157 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5158 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005159 case CXCursor_OverloadCandidate:
5160 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005161 case CXCursor_TypeAliasTemplateDecl:
5162 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005163 case CXCursor_StaticAssert:
5164 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005165 case CXCursor_FriendDecl:
5166 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 }
5168
5169 llvm_unreachable("Unhandled CXCursorKind");
5170}
5171
5172struct GetCursorData {
5173 SourceLocation TokenBeginLoc;
5174 bool PointsAtMacroArgExpansion;
5175 bool VisitedObjCPropertyImplDecl;
5176 SourceLocation VisitedDeclaratorDeclStartLoc;
5177 CXCursor &BestCursor;
5178
5179 GetCursorData(SourceManager &SM,
5180 SourceLocation tokenBegin, CXCursor &outputCursor)
5181 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5182 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5183 VisitedObjCPropertyImplDecl = false;
5184 }
5185};
5186
5187static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5188 CXCursor parent,
5189 CXClientData client_data) {
5190 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5191 CXCursor *BestCursor = &Data->BestCursor;
5192
5193 // If we point inside a macro argument we should provide info of what the
5194 // token is so use the actual cursor, don't replace it with a macro expansion
5195 // cursor.
5196 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5197 return CXChildVisit_Recurse;
5198
5199 if (clang_isDeclaration(cursor.kind)) {
5200 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005201 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5203 if (MD->isImplicit())
5204 return CXChildVisit_Break;
5205
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005206 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5208 // Check that when we have multiple @class references in the same line,
5209 // that later ones do not override the previous ones.
5210 // If we have:
5211 // @class Foo, Bar;
5212 // source ranges for both start at '@', so 'Bar' will end up overriding
5213 // 'Foo' even though the cursor location was at 'Foo'.
5214 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5215 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005216 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5218 if (PrevID != ID &&
5219 !PrevID->isThisDeclarationADefinition() &&
5220 !ID->isThisDeclarationADefinition())
5221 return CXChildVisit_Break;
5222 }
5223
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005224 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5226 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5227 // Check that when we have multiple declarators in the same line,
5228 // that later ones do not override the previous ones.
5229 // If we have:
5230 // int Foo, Bar;
5231 // source ranges for both start at 'int', so 'Bar' will end up overriding
5232 // 'Foo' even though the cursor location was at 'Foo'.
5233 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5234 return CXChildVisit_Break;
5235 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5236
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005237 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5239 (void)PropImp;
5240 // Check that when we have multiple @synthesize in the same line,
5241 // that later ones do not override the previous ones.
5242 // If we have:
5243 // @synthesize Foo, Bar;
5244 // source ranges for both start at '@', so 'Bar' will end up overriding
5245 // 'Foo' even though the cursor location was at 'Foo'.
5246 if (Data->VisitedObjCPropertyImplDecl)
5247 return CXChildVisit_Break;
5248 Data->VisitedObjCPropertyImplDecl = true;
5249 }
5250 }
5251
5252 if (clang_isExpression(cursor.kind) &&
5253 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005254 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 // Avoid having the cursor of an expression replace the declaration cursor
5256 // when the expression source range overlaps the declaration range.
5257 // This can happen for C++ constructor expressions whose range generally
5258 // include the variable declaration, e.g.:
5259 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5260 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5261 D->getLocation() == Data->TokenBeginLoc)
5262 return CXChildVisit_Break;
5263 }
5264 }
5265
5266 // If our current best cursor is the construction of a temporary object,
5267 // don't replace that cursor with a type reference, because we want
5268 // clang_getCursor() to point at the constructor.
5269 if (clang_isExpression(BestCursor->kind) &&
5270 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5271 cursor.kind == CXCursor_TypeRef) {
5272 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5273 // as having the actual point on the type reference.
5274 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5275 return CXChildVisit_Recurse;
5276 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005277
5278 // If we already have an Objective-C superclass reference, don't
5279 // update it further.
5280 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5281 return CXChildVisit_Break;
5282
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 *BestCursor = cursor;
5284 return CXChildVisit_Recurse;
5285}
5286
5287CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005288 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005289 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005291 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005292
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005293 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5295
5296 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5297 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5298
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005299 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 CXFile SearchFile;
5301 unsigned SearchLine, SearchColumn;
5302 CXFile ResultFile;
5303 unsigned ResultLine, ResultColumn;
5304 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5305 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5306 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005307
5308 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5309 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005310 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005311 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 SearchFileName = clang_getFileName(SearchFile);
5313 ResultFileName = clang_getFileName(ResultFile);
5314 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5315 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005316 *Log << llvm::format("(%s:%d:%d) = %s",
5317 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5318 clang_getCString(KindSpelling))
5319 << llvm::format("(%s:%d:%d):%s%s",
5320 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5321 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 clang_disposeString(SearchFileName);
5323 clang_disposeString(ResultFileName);
5324 clang_disposeString(KindSpelling);
5325 clang_disposeString(USR);
5326
5327 CXCursor Definition = clang_getCursorDefinition(Result);
5328 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5329 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5330 CXString DefinitionKindSpelling
5331 = clang_getCursorKindSpelling(Definition.kind);
5332 CXFile DefinitionFile;
5333 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005334 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005335 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005337 *Log << llvm::format(" -> %s(%s:%d:%d)",
5338 clang_getCString(DefinitionKindSpelling),
5339 clang_getCString(DefinitionFileName),
5340 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 clang_disposeString(DefinitionFileName);
5342 clang_disposeString(DefinitionKindSpelling);
5343 }
5344 }
5345
5346 return Result;
5347}
5348
5349CXCursor clang_getNullCursor(void) {
5350 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5351}
5352
5353unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005354 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5355 // can't set consistently. For example, when visiting a DeclStmt we will set
5356 // it but we don't set it on the result of clang_getCursorDefinition for
5357 // a reference of the same declaration.
5358 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5359 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5360 // to provide that kind of info.
5361 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005362 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005363 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005364 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005365
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 return X == Y;
5367}
5368
5369unsigned clang_hashCursor(CXCursor C) {
5370 unsigned Index = 0;
5371 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5372 Index = 1;
5373
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005374 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 std::make_pair(C.kind, C.data[Index]));
5376}
5377
5378unsigned clang_isInvalid(enum CXCursorKind K) {
5379 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5380}
5381
5382unsigned clang_isDeclaration(enum CXCursorKind K) {
5383 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5384 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5385}
5386
5387unsigned clang_isReference(enum CXCursorKind K) {
5388 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5389}
5390
5391unsigned clang_isExpression(enum CXCursorKind K) {
5392 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5393}
5394
5395unsigned clang_isStatement(enum CXCursorKind K) {
5396 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5397}
5398
5399unsigned clang_isAttribute(enum CXCursorKind K) {
5400 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5401}
5402
5403unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5404 return K == CXCursor_TranslationUnit;
5405}
5406
5407unsigned clang_isPreprocessing(enum CXCursorKind K) {
5408 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5409}
5410
5411unsigned clang_isUnexposed(enum CXCursorKind K) {
5412 switch (K) {
5413 case CXCursor_UnexposedDecl:
5414 case CXCursor_UnexposedExpr:
5415 case CXCursor_UnexposedStmt:
5416 case CXCursor_UnexposedAttr:
5417 return true;
5418 default:
5419 return false;
5420 }
5421}
5422
5423CXCursorKind clang_getCursorKind(CXCursor C) {
5424 return C.kind;
5425}
5426
5427CXSourceLocation clang_getCursorLocation(CXCursor C) {
5428 if (clang_isReference(C.kind)) {
5429 switch (C.kind) {
5430 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005431 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005432 = getCursorObjCSuperClassRef(C);
5433 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5434 }
5435
5436 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005437 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 = getCursorObjCProtocolRef(C);
5439 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5440 }
5441
5442 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005443 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 = getCursorObjCClassRef(C);
5445 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5446 }
5447
5448 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005449 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5451 }
5452
5453 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005454 std::pair<const TemplateDecl *, SourceLocation> P =
5455 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5457 }
5458
5459 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005460 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005461 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5462 }
5463
5464 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005465 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005466 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5467 }
5468
5469 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005470 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5472 }
5473
5474 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005475 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005476 if (!BaseSpec)
5477 return clang_getNullLocation();
5478
5479 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5480 return cxloc::translateSourceLocation(getCursorContext(C),
5481 TSInfo->getTypeLoc().getBeginLoc());
5482
5483 return cxloc::translateSourceLocation(getCursorContext(C),
5484 BaseSpec->getLocStart());
5485 }
5486
5487 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005488 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005489 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5490 }
5491
5492 case CXCursor_OverloadedDeclRef:
5493 return cxloc::translateSourceLocation(getCursorContext(C),
5494 getCursorOverloadedDeclRef(C).second);
5495
5496 default:
5497 // FIXME: Need a way to enumerate all non-reference cases.
5498 llvm_unreachable("Missed a reference kind");
5499 }
5500 }
5501
5502 if (clang_isExpression(C.kind))
5503 return cxloc::translateSourceLocation(getCursorContext(C),
5504 getLocationFromExpr(getCursorExpr(C)));
5505
5506 if (clang_isStatement(C.kind))
5507 return cxloc::translateSourceLocation(getCursorContext(C),
5508 getCursorStmt(C)->getLocStart());
5509
5510 if (C.kind == CXCursor_PreprocessingDirective) {
5511 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5512 return cxloc::translateSourceLocation(getCursorContext(C), L);
5513 }
5514
5515 if (C.kind == CXCursor_MacroExpansion) {
5516 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005517 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 return cxloc::translateSourceLocation(getCursorContext(C), L);
5519 }
5520
5521 if (C.kind == CXCursor_MacroDefinition) {
5522 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5523 return cxloc::translateSourceLocation(getCursorContext(C), L);
5524 }
5525
5526 if (C.kind == CXCursor_InclusionDirective) {
5527 SourceLocation L
5528 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5529 return cxloc::translateSourceLocation(getCursorContext(C), L);
5530 }
5531
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005532 if (clang_isAttribute(C.kind)) {
5533 SourceLocation L
5534 = cxcursor::getCursorAttr(C)->getLocation();
5535 return cxloc::translateSourceLocation(getCursorContext(C), L);
5536 }
5537
Guy Benyei11169dd2012-12-18 14:30:41 +00005538 if (!clang_isDeclaration(C.kind))
5539 return clang_getNullLocation();
5540
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005541 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 if (!D)
5543 return clang_getNullLocation();
5544
5545 SourceLocation Loc = D->getLocation();
5546 // FIXME: Multiple variables declared in a single declaration
5547 // currently lack the information needed to correctly determine their
5548 // ranges when accounting for the type-specifier. We use context
5549 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5550 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005551 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005552 if (!cxcursor::isFirstInDeclGroup(C))
5553 Loc = VD->getLocation();
5554 }
5555
5556 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005557 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005558 Loc = MD->getSelectorStartLoc();
5559
5560 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5561}
5562
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005563} // end extern "C"
5564
Guy Benyei11169dd2012-12-18 14:30:41 +00005565CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5566 assert(TU);
5567
5568 // Guard against an invalid SourceLocation, or we may assert in one
5569 // of the following calls.
5570 if (SLoc.isInvalid())
5571 return clang_getNullCursor();
5572
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005573 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005574
5575 // Translate the given source location to make it point at the beginning of
5576 // the token under the cursor.
5577 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5578 CXXUnit->getASTContext().getLangOpts());
5579
5580 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5581 if (SLoc.isValid()) {
5582 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5583 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5584 /*VisitPreprocessorLast=*/true,
5585 /*VisitIncludedEntities=*/false,
5586 SourceLocation(SLoc));
5587 CursorVis.visitFileRegion();
5588 }
5589
5590 return Result;
5591}
5592
5593static SourceRange getRawCursorExtent(CXCursor C) {
5594 if (clang_isReference(C.kind)) {
5595 switch (C.kind) {
5596 case CXCursor_ObjCSuperClassRef:
5597 return getCursorObjCSuperClassRef(C).second;
5598
5599 case CXCursor_ObjCProtocolRef:
5600 return getCursorObjCProtocolRef(C).second;
5601
5602 case CXCursor_ObjCClassRef:
5603 return getCursorObjCClassRef(C).second;
5604
5605 case CXCursor_TypeRef:
5606 return getCursorTypeRef(C).second;
5607
5608 case CXCursor_TemplateRef:
5609 return getCursorTemplateRef(C).second;
5610
5611 case CXCursor_NamespaceRef:
5612 return getCursorNamespaceRef(C).second;
5613
5614 case CXCursor_MemberRef:
5615 return getCursorMemberRef(C).second;
5616
5617 case CXCursor_CXXBaseSpecifier:
5618 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5619
5620 case CXCursor_LabelRef:
5621 return getCursorLabelRef(C).second;
5622
5623 case CXCursor_OverloadedDeclRef:
5624 return getCursorOverloadedDeclRef(C).second;
5625
5626 case CXCursor_VariableRef:
5627 return getCursorVariableRef(C).second;
5628
5629 default:
5630 // FIXME: Need a way to enumerate all non-reference cases.
5631 llvm_unreachable("Missed a reference kind");
5632 }
5633 }
5634
5635 if (clang_isExpression(C.kind))
5636 return getCursorExpr(C)->getSourceRange();
5637
5638 if (clang_isStatement(C.kind))
5639 return getCursorStmt(C)->getSourceRange();
5640
5641 if (clang_isAttribute(C.kind))
5642 return getCursorAttr(C)->getRange();
5643
5644 if (C.kind == CXCursor_PreprocessingDirective)
5645 return cxcursor::getCursorPreprocessingDirective(C);
5646
5647 if (C.kind == CXCursor_MacroExpansion) {
5648 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005649 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005650 return TU->mapRangeFromPreamble(Range);
5651 }
5652
5653 if (C.kind == CXCursor_MacroDefinition) {
5654 ASTUnit *TU = getCursorASTUnit(C);
5655 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5656 return TU->mapRangeFromPreamble(Range);
5657 }
5658
5659 if (C.kind == CXCursor_InclusionDirective) {
5660 ASTUnit *TU = getCursorASTUnit(C);
5661 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5662 return TU->mapRangeFromPreamble(Range);
5663 }
5664
5665 if (C.kind == CXCursor_TranslationUnit) {
5666 ASTUnit *TU = getCursorASTUnit(C);
5667 FileID MainID = TU->getSourceManager().getMainFileID();
5668 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5669 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5670 return SourceRange(Start, End);
5671 }
5672
5673 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005674 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 if (!D)
5676 return SourceRange();
5677
5678 SourceRange R = D->getSourceRange();
5679 // FIXME: Multiple variables declared in a single declaration
5680 // currently lack the information needed to correctly determine their
5681 // ranges when accounting for the type-specifier. We use context
5682 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5683 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005684 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005685 if (!cxcursor::isFirstInDeclGroup(C))
5686 R.setBegin(VD->getLocation());
5687 }
5688 return R;
5689 }
5690 return SourceRange();
5691}
5692
5693/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5694/// the decl-specifier-seq for declarations.
5695static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5696 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005697 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005698 if (!D)
5699 return SourceRange();
5700
5701 SourceRange R = D->getSourceRange();
5702
5703 // Adjust the start of the location for declarations preceded by
5704 // declaration specifiers.
5705 SourceLocation StartLoc;
5706 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5707 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5708 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005709 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005710 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5711 StartLoc = TI->getTypeLoc().getLocStart();
5712 }
5713
5714 if (StartLoc.isValid() && R.getBegin().isValid() &&
5715 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5716 R.setBegin(StartLoc);
5717
5718 // FIXME: Multiple variables declared in a single declaration
5719 // currently lack the information needed to correctly determine their
5720 // ranges when accounting for the type-specifier. We use context
5721 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5722 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005723 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005724 if (!cxcursor::isFirstInDeclGroup(C))
5725 R.setBegin(VD->getLocation());
5726 }
5727
5728 return R;
5729 }
5730
5731 return getRawCursorExtent(C);
5732}
5733
Guy Benyei11169dd2012-12-18 14:30:41 +00005734CXSourceRange clang_getCursorExtent(CXCursor C) {
5735 SourceRange R = getRawCursorExtent(C);
5736 if (R.isInvalid())
5737 return clang_getNullRange();
5738
5739 return cxloc::translateSourceRange(getCursorContext(C), R);
5740}
5741
5742CXCursor clang_getCursorReferenced(CXCursor C) {
5743 if (clang_isInvalid(C.kind))
5744 return clang_getNullCursor();
5745
5746 CXTranslationUnit tu = getCursorTU(C);
5747 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005748 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005749 if (!D)
5750 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005751 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005752 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005753 if (const ObjCPropertyImplDecl *PropImpl =
5754 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005755 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5756 return MakeCXCursor(Property, tu);
5757
5758 return C;
5759 }
5760
5761 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005762 const Expr *E = getCursorExpr(C);
5763 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 if (D) {
5765 CXCursor declCursor = MakeCXCursor(D, tu);
5766 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5767 declCursor);
5768 return declCursor;
5769 }
5770
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005771 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005772 return MakeCursorOverloadedDeclRef(Ovl, tu);
5773
5774 return clang_getNullCursor();
5775 }
5776
5777 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005778 const Stmt *S = getCursorStmt(C);
5779 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005780 if (LabelDecl *label = Goto->getLabel())
5781 if (LabelStmt *labelS = label->getStmt())
5782 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5783
5784 return clang_getNullCursor();
5785 }
Richard Smith66a81862015-05-04 02:25:31 +00005786
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005788 if (const MacroDefinitionRecord *Def =
5789 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005790 return MakeMacroDefinitionCursor(Def, tu);
5791 }
5792
5793 if (!clang_isReference(C.kind))
5794 return clang_getNullCursor();
5795
5796 switch (C.kind) {
5797 case CXCursor_ObjCSuperClassRef:
5798 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5799
5800 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005801 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5802 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005803 return MakeCXCursor(Def, tu);
5804
5805 return MakeCXCursor(Prot, tu);
5806 }
5807
5808 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005809 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5810 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 return MakeCXCursor(Def, tu);
5812
5813 return MakeCXCursor(Class, tu);
5814 }
5815
5816 case CXCursor_TypeRef:
5817 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5818
5819 case CXCursor_TemplateRef:
5820 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5821
5822 case CXCursor_NamespaceRef:
5823 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5824
5825 case CXCursor_MemberRef:
5826 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5827
5828 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005829 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005830 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5831 tu ));
5832 }
5833
5834 case CXCursor_LabelRef:
5835 // FIXME: We end up faking the "parent" declaration here because we
5836 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005837 return MakeCXCursor(getCursorLabelRef(C).first,
5838 cxtu::getASTUnit(tu)->getASTContext()
5839 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005840 tu);
5841
5842 case CXCursor_OverloadedDeclRef:
5843 return C;
5844
5845 case CXCursor_VariableRef:
5846 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5847
5848 default:
5849 // We would prefer to enumerate all non-reference cursor kinds here.
5850 llvm_unreachable("Unhandled reference cursor kind");
5851 }
5852}
5853
5854CXCursor clang_getCursorDefinition(CXCursor C) {
5855 if (clang_isInvalid(C.kind))
5856 return clang_getNullCursor();
5857
5858 CXTranslationUnit TU = getCursorTU(C);
5859
5860 bool WasReference = false;
5861 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5862 C = clang_getCursorReferenced(C);
5863 WasReference = true;
5864 }
5865
5866 if (C.kind == CXCursor_MacroExpansion)
5867 return clang_getCursorReferenced(C);
5868
5869 if (!clang_isDeclaration(C.kind))
5870 return clang_getNullCursor();
5871
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005872 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 if (!D)
5874 return clang_getNullCursor();
5875
5876 switch (D->getKind()) {
5877 // Declaration kinds that don't really separate the notions of
5878 // declaration and definition.
5879 case Decl::Namespace:
5880 case Decl::Typedef:
5881 case Decl::TypeAlias:
5882 case Decl::TypeAliasTemplate:
5883 case Decl::TemplateTypeParm:
5884 case Decl::EnumConstant:
5885 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005886 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005887 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005888 case Decl::IndirectField:
5889 case Decl::ObjCIvar:
5890 case Decl::ObjCAtDefsField:
5891 case Decl::ImplicitParam:
5892 case Decl::ParmVar:
5893 case Decl::NonTypeTemplateParm:
5894 case Decl::TemplateTemplateParm:
5895 case Decl::ObjCCategoryImpl:
5896 case Decl::ObjCImplementation:
5897 case Decl::AccessSpec:
5898 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005899 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005900 case Decl::ObjCPropertyImpl:
5901 case Decl::FileScopeAsm:
5902 case Decl::StaticAssert:
5903 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005904 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005905 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005906 case Decl::Label: // FIXME: Is this right??
5907 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00005908 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00005909 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005910 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005911 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005912 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005913 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005914 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005915 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005916 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005917 return C;
5918
5919 // Declaration kinds that don't make any sense here, but are
5920 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005921 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005922 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005923 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005924 break;
5925
5926 // Declaration kinds for which the definition is not resolvable.
5927 case Decl::UnresolvedUsingTypename:
5928 case Decl::UnresolvedUsingValue:
5929 break;
5930
5931 case Decl::UsingDirective:
5932 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5933 TU);
5934
5935 case Decl::NamespaceAlias:
5936 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5937
5938 case Decl::Enum:
5939 case Decl::Record:
5940 case Decl::CXXRecord:
5941 case Decl::ClassTemplateSpecialization:
5942 case Decl::ClassTemplatePartialSpecialization:
5943 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5944 return MakeCXCursor(Def, TU);
5945 return clang_getNullCursor();
5946
5947 case Decl::Function:
5948 case Decl::CXXMethod:
5949 case Decl::CXXConstructor:
5950 case Decl::CXXDestructor:
5951 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005952 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005953 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005954 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005955 return clang_getNullCursor();
5956 }
5957
Larisse Voufo39a1e502013-08-06 01:03:05 +00005958 case Decl::Var:
5959 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005960 case Decl::VarTemplatePartialSpecialization:
5961 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005962 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005963 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005964 return MakeCXCursor(Def, TU);
5965 return clang_getNullCursor();
5966 }
5967
5968 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005969 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5971 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5972 return clang_getNullCursor();
5973 }
5974
5975 case Decl::ClassTemplate: {
5976 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5977 ->getDefinition())
5978 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5979 TU);
5980 return clang_getNullCursor();
5981 }
5982
Larisse Voufo39a1e502013-08-06 01:03:05 +00005983 case Decl::VarTemplate: {
5984 if (VarDecl *Def =
5985 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5986 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5987 return clang_getNullCursor();
5988 }
5989
Guy Benyei11169dd2012-12-18 14:30:41 +00005990 case Decl::Using:
5991 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5992 D->getLocation(), TU);
5993
5994 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005995 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005996 return clang_getCursorDefinition(
5997 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5998 TU));
5999
6000 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006001 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006002 if (Method->isThisDeclarationADefinition())
6003 return C;
6004
6005 // Dig out the method definition in the associated
6006 // @implementation, if we have it.
6007 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006008 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006009 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6010 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6011 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6012 Method->isInstanceMethod()))
6013 if (Def->isThisDeclarationADefinition())
6014 return MakeCXCursor(Def, TU);
6015
6016 return clang_getNullCursor();
6017 }
6018
6019 case Decl::ObjCCategory:
6020 if (ObjCCategoryImplDecl *Impl
6021 = cast<ObjCCategoryDecl>(D)->getImplementation())
6022 return MakeCXCursor(Impl, TU);
6023 return clang_getNullCursor();
6024
6025 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006026 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006027 return MakeCXCursor(Def, TU);
6028 return clang_getNullCursor();
6029
6030 case Decl::ObjCInterface: {
6031 // There are two notions of a "definition" for an Objective-C
6032 // class: the interface and its implementation. When we resolved a
6033 // reference to an Objective-C class, produce the @interface as
6034 // the definition; when we were provided with the interface,
6035 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006036 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006038 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 return MakeCXCursor(Def, TU);
6040 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6041 return MakeCXCursor(Impl, TU);
6042 return clang_getNullCursor();
6043 }
6044
6045 case Decl::ObjCProperty:
6046 // FIXME: We don't really know where to find the
6047 // ObjCPropertyImplDecls that implement this property.
6048 return clang_getNullCursor();
6049
6050 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006051 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006052 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006053 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006054 return MakeCXCursor(Def, TU);
6055
6056 return clang_getNullCursor();
6057
6058 case Decl::Friend:
6059 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6060 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6061 return clang_getNullCursor();
6062
6063 case Decl::FriendTemplate:
6064 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6065 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6066 return clang_getNullCursor();
6067 }
6068
6069 return clang_getNullCursor();
6070}
6071
6072unsigned clang_isCursorDefinition(CXCursor C) {
6073 if (!clang_isDeclaration(C.kind))
6074 return 0;
6075
6076 return clang_getCursorDefinition(C) == C;
6077}
6078
6079CXCursor clang_getCanonicalCursor(CXCursor C) {
6080 if (!clang_isDeclaration(C.kind))
6081 return C;
6082
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006083 if (const Decl *D = getCursorDecl(C)) {
6084 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006085 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6086 return MakeCXCursor(CatD, getCursorTU(C));
6087
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006088 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6089 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006090 return MakeCXCursor(IFD, getCursorTU(C));
6091
6092 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6093 }
6094
6095 return C;
6096}
6097
6098int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6099 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6100}
6101
6102unsigned clang_getNumOverloadedDecls(CXCursor C) {
6103 if (C.kind != CXCursor_OverloadedDeclRef)
6104 return 0;
6105
6106 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006107 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006108 return E->getNumDecls();
6109
6110 if (OverloadedTemplateStorage *S
6111 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6112 return S->size();
6113
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006114 const Decl *D = Storage.get<const Decl *>();
6115 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006116 return Using->shadow_size();
6117
6118 return 0;
6119}
6120
6121CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6122 if (cursor.kind != CXCursor_OverloadedDeclRef)
6123 return clang_getNullCursor();
6124
6125 if (index >= clang_getNumOverloadedDecls(cursor))
6126 return clang_getNullCursor();
6127
6128 CXTranslationUnit TU = getCursorTU(cursor);
6129 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006130 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006131 return MakeCXCursor(E->decls_begin()[index], TU);
6132
6133 if (OverloadedTemplateStorage *S
6134 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6135 return MakeCXCursor(S->begin()[index], TU);
6136
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006137 const Decl *D = Storage.get<const Decl *>();
6138 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006139 // FIXME: This is, unfortunately, linear time.
6140 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6141 std::advance(Pos, index);
6142 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6143 }
6144
6145 return clang_getNullCursor();
6146}
6147
6148void clang_getDefinitionSpellingAndExtent(CXCursor C,
6149 const char **startBuf,
6150 const char **endBuf,
6151 unsigned *startLine,
6152 unsigned *startColumn,
6153 unsigned *endLine,
6154 unsigned *endColumn) {
6155 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006156 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6158
6159 SourceManager &SM = FD->getASTContext().getSourceManager();
6160 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6161 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6162 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6163 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6164 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6165 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6166}
6167
6168
6169CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6170 unsigned PieceIndex) {
6171 RefNamePieces Pieces;
6172
6173 switch (C.kind) {
6174 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006175 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006176 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6177 E->getQualifierLoc().getSourceRange());
6178 break;
6179
6180 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006181 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6182 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6183 Pieces =
6184 buildPieces(NameFlags, false, E->getNameInfo(),
6185 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6186 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006187 break;
6188
6189 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006190 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006191 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006192 const Expr *Callee = OCE->getCallee();
6193 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006194 Callee = ICE->getSubExpr();
6195
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006196 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006197 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6198 DRE->getQualifierLoc().getSourceRange());
6199 }
6200 break;
6201
6202 default:
6203 break;
6204 }
6205
6206 if (Pieces.empty()) {
6207 if (PieceIndex == 0)
6208 return clang_getCursorExtent(C);
6209 } else if (PieceIndex < Pieces.size()) {
6210 SourceRange R = Pieces[PieceIndex];
6211 if (R.isValid())
6212 return cxloc::translateSourceRange(getCursorContext(C), R);
6213 }
6214
6215 return clang_getNullRange();
6216}
6217
6218void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006219 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6220 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006221}
6222
6223void clang_executeOnThread(void (*fn)(void*), void *user_data,
6224 unsigned stack_size) {
6225 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6226}
6227
Guy Benyei11169dd2012-12-18 14:30:41 +00006228//===----------------------------------------------------------------------===//
6229// Token-based Operations.
6230//===----------------------------------------------------------------------===//
6231
6232/* CXToken layout:
6233 * int_data[0]: a CXTokenKind
6234 * int_data[1]: starting token location
6235 * int_data[2]: token length
6236 * int_data[3]: reserved
6237 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6238 * otherwise unused.
6239 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006240CXTokenKind clang_getTokenKind(CXToken CXTok) {
6241 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6242}
6243
6244CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6245 switch (clang_getTokenKind(CXTok)) {
6246 case CXToken_Identifier:
6247 case CXToken_Keyword:
6248 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006249 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006250 ->getNameStart());
6251
6252 case CXToken_Literal: {
6253 // We have stashed the starting pointer in the ptr_data field. Use it.
6254 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006255 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006256 }
6257
6258 case CXToken_Punctuation:
6259 case CXToken_Comment:
6260 break;
6261 }
6262
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006263 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006264 LOG_BAD_TU(TU);
6265 return cxstring::createEmpty();
6266 }
6267
Guy Benyei11169dd2012-12-18 14:30:41 +00006268 // We have to find the starting buffer pointer the hard way, by
6269 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006270 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006272 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006273
6274 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6275 std::pair<FileID, unsigned> LocInfo
6276 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6277 bool Invalid = false;
6278 StringRef Buffer
6279 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6280 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006281 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006282
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006283 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006284}
6285
6286CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006287 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006288 LOG_BAD_TU(TU);
6289 return clang_getNullLocation();
6290 }
6291
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006292 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006293 if (!CXXUnit)
6294 return clang_getNullLocation();
6295
6296 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6297 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6298}
6299
6300CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006301 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006302 LOG_BAD_TU(TU);
6303 return clang_getNullRange();
6304 }
6305
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006306 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 if (!CXXUnit)
6308 return clang_getNullRange();
6309
6310 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6311 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6312}
6313
6314static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6315 SmallVectorImpl<CXToken> &CXTokens) {
6316 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6317 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006318 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006320 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006321
6322 // Cannot tokenize across files.
6323 if (BeginLocInfo.first != EndLocInfo.first)
6324 return;
6325
6326 // Create a lexer
6327 bool Invalid = false;
6328 StringRef Buffer
6329 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6330 if (Invalid)
6331 return;
6332
6333 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6334 CXXUnit->getASTContext().getLangOpts(),
6335 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6336 Lex.SetCommentRetentionState(true);
6337
6338 // Lex tokens until we hit the end of the range.
6339 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6340 Token Tok;
6341 bool previousWasAt = false;
6342 do {
6343 // Lex the next token
6344 Lex.LexFromRawLexer(Tok);
6345 if (Tok.is(tok::eof))
6346 break;
6347
6348 // Initialize the CXToken.
6349 CXToken CXTok;
6350
6351 // - Common fields
6352 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6353 CXTok.int_data[2] = Tok.getLength();
6354 CXTok.int_data[3] = 0;
6355
6356 // - Kind-specific fields
6357 if (Tok.isLiteral()) {
6358 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006359 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006360 } else if (Tok.is(tok::raw_identifier)) {
6361 // Lookup the identifier to determine whether we have a keyword.
6362 IdentifierInfo *II
6363 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6364
6365 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6366 CXTok.int_data[0] = CXToken_Keyword;
6367 }
6368 else {
6369 CXTok.int_data[0] = Tok.is(tok::identifier)
6370 ? CXToken_Identifier
6371 : CXToken_Keyword;
6372 }
6373 CXTok.ptr_data = II;
6374 } else if (Tok.is(tok::comment)) {
6375 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006376 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 } else {
6378 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006379 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 }
6381 CXTokens.push_back(CXTok);
6382 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006383 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006384}
6385
6386void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6387 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006388 LOG_FUNC_SECTION {
6389 *Log << TU << ' ' << Range;
6390 }
6391
Guy Benyei11169dd2012-12-18 14:30:41 +00006392 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006393 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 if (NumTokens)
6395 *NumTokens = 0;
6396
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006397 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006398 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006399 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006400 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006401
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006402 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 if (!CXXUnit || !Tokens || !NumTokens)
6404 return;
6405
6406 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6407
6408 SourceRange R = cxloc::translateCXSourceRange(Range);
6409 if (R.isInvalid())
6410 return;
6411
6412 SmallVector<CXToken, 32> CXTokens;
6413 getTokens(CXXUnit, R, CXTokens);
6414
6415 if (CXTokens.empty())
6416 return;
6417
6418 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6419 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6420 *NumTokens = CXTokens.size();
6421}
6422
6423void clang_disposeTokens(CXTranslationUnit TU,
6424 CXToken *Tokens, unsigned NumTokens) {
6425 free(Tokens);
6426}
6427
Guy Benyei11169dd2012-12-18 14:30:41 +00006428//===----------------------------------------------------------------------===//
6429// Token annotation APIs.
6430//===----------------------------------------------------------------------===//
6431
Guy Benyei11169dd2012-12-18 14:30:41 +00006432static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6433 CXCursor parent,
6434 CXClientData client_data);
6435static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6436 CXClientData client_data);
6437
6438namespace {
6439class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006440 CXToken *Tokens;
6441 CXCursor *Cursors;
6442 unsigned NumTokens;
6443 unsigned TokIdx;
6444 unsigned PreprocessingTokIdx;
6445 CursorVisitor AnnotateVis;
6446 SourceManager &SrcMgr;
6447 bool HasContextSensitiveKeywords;
6448
6449 struct PostChildrenInfo {
6450 CXCursor Cursor;
6451 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006452 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006453 unsigned BeforeChildrenTokenIdx;
6454 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006455 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006456
6457 CXToken &getTok(unsigned Idx) {
6458 assert(Idx < NumTokens);
6459 return Tokens[Idx];
6460 }
6461 const CXToken &getTok(unsigned Idx) const {
6462 assert(Idx < NumTokens);
6463 return Tokens[Idx];
6464 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 bool MoreTokens() const { return TokIdx < NumTokens; }
6466 unsigned NextToken() const { return TokIdx; }
6467 void AdvanceToken() { ++TokIdx; }
6468 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006469 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006470 }
6471 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006472 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006473 }
6474 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006475 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006476 }
6477
6478 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006479 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 SourceRange);
6481
6482public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006483 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006484 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006485 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006486 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006487 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 AnnotateTokensVisitor, this,
6489 /*VisitPreprocessorLast=*/true,
6490 /*VisitIncludedEntities=*/false,
6491 RegionOfInterest,
6492 /*VisitDeclsOnly=*/false,
6493 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006494 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006495 HasContextSensitiveKeywords(false) { }
6496
6497 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6498 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6499 bool postVisitChildren(CXCursor cursor);
6500 void AnnotateTokens();
6501
6502 /// \brief Determine whether the annotator saw any cursors that have
6503 /// context-sensitive keywords.
6504 bool hasContextSensitiveKeywords() const {
6505 return HasContextSensitiveKeywords;
6506 }
6507
6508 ~AnnotateTokensWorker() {
6509 assert(PostChildrenInfos.empty());
6510 }
6511};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006512}
Guy Benyei11169dd2012-12-18 14:30:41 +00006513
6514void AnnotateTokensWorker::AnnotateTokens() {
6515 // Walk the AST within the region of interest, annotating tokens
6516 // along the way.
6517 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006518}
Guy Benyei11169dd2012-12-18 14:30:41 +00006519
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006520static inline void updateCursorAnnotation(CXCursor &Cursor,
6521 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006522 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006524 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006525}
6526
6527/// \brief It annotates and advances tokens with a cursor until the comparison
6528//// between the cursor location and the source range is the same as
6529/// \arg compResult.
6530///
6531/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6532/// Pass RangeOverlap to annotate tokens inside a range.
6533void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6534 RangeComparisonResult compResult,
6535 SourceRange range) {
6536 while (MoreTokens()) {
6537 const unsigned I = NextToken();
6538 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006539 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6540 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006541
6542 SourceLocation TokLoc = GetTokenLoc(I);
6543 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006544 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006545 AdvanceToken();
6546 continue;
6547 }
6548 break;
6549 }
6550}
6551
6552/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006553/// \returns true if it advanced beyond all macro tokens, false otherwise.
6554bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006555 CXCursor updateC,
6556 RangeComparisonResult compResult,
6557 SourceRange range) {
6558 assert(MoreTokens());
6559 assert(isFunctionMacroToken(NextToken()) &&
6560 "Should be called only for macro arg tokens");
6561
6562 // This works differently than annotateAndAdvanceTokens; because expanded
6563 // macro arguments can have arbitrary translation-unit source order, we do not
6564 // advance the token index one by one until a token fails the range test.
6565 // We only advance once past all of the macro arg tokens if all of them
6566 // pass the range test. If one of them fails we keep the token index pointing
6567 // at the start of the macro arg tokens so that the failing token will be
6568 // annotated by a subsequent annotation try.
6569
6570 bool atLeastOneCompFail = false;
6571
6572 unsigned I = NextToken();
6573 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6574 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6575 if (TokLoc.isFileID())
6576 continue; // not macro arg token, it's parens or comma.
6577 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6578 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6579 Cursors[I] = updateC;
6580 } else
6581 atLeastOneCompFail = true;
6582 }
6583
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006584 if (atLeastOneCompFail)
6585 return false;
6586
6587 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6588 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006589}
6590
6591enum CXChildVisitResult
6592AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006593 SourceRange cursorRange = getRawCursorExtent(cursor);
6594 if (cursorRange.isInvalid())
6595 return CXChildVisit_Recurse;
6596
6597 if (!HasContextSensitiveKeywords) {
6598 // Objective-C properties can have context-sensitive keywords.
6599 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006600 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6602 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6603 }
6604 // Objective-C methods can have context-sensitive keywords.
6605 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6606 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006607 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006608 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6609 if (Method->getObjCDeclQualifier())
6610 HasContextSensitiveKeywords = true;
6611 else {
David Majnemer59f77922016-06-24 04:05:48 +00006612 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006613 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 HasContextSensitiveKeywords = true;
6615 break;
6616 }
6617 }
6618 }
6619 }
6620 }
6621 // C++ methods can have context-sensitive keywords.
6622 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006623 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6625 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6626 HasContextSensitiveKeywords = true;
6627 }
6628 }
6629 // C++ classes can have context-sensitive keywords.
6630 else if (cursor.kind == CXCursor_StructDecl ||
6631 cursor.kind == CXCursor_ClassDecl ||
6632 cursor.kind == CXCursor_ClassTemplate ||
6633 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006634 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 if (D->hasAttr<FinalAttr>())
6636 HasContextSensitiveKeywords = true;
6637 }
6638 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006639
6640 // Don't override a property annotation with its getter/setter method.
6641 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6642 parent.kind == CXCursor_ObjCPropertyDecl)
6643 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006644
6645 if (clang_isPreprocessing(cursor.kind)) {
6646 // Items in the preprocessing record are kept separate from items in
6647 // declarations, so we keep a separate token index.
6648 unsigned SavedTokIdx = TokIdx;
6649 TokIdx = PreprocessingTokIdx;
6650
6651 // Skip tokens up until we catch up to the beginning of the preprocessing
6652 // entry.
6653 while (MoreTokens()) {
6654 const unsigned I = NextToken();
6655 SourceLocation TokLoc = GetTokenLoc(I);
6656 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6657 case RangeBefore:
6658 AdvanceToken();
6659 continue;
6660 case RangeAfter:
6661 case RangeOverlap:
6662 break;
6663 }
6664 break;
6665 }
6666
6667 // Look at all of the tokens within this range.
6668 while (MoreTokens()) {
6669 const unsigned I = NextToken();
6670 SourceLocation TokLoc = GetTokenLoc(I);
6671 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6672 case RangeBefore:
6673 llvm_unreachable("Infeasible");
6674 case RangeAfter:
6675 break;
6676 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006677 // For macro expansions, just note where the beginning of the macro
6678 // expansion occurs.
6679 if (cursor.kind == CXCursor_MacroExpansion) {
6680 if (TokLoc == cursorRange.getBegin())
6681 Cursors[I] = cursor;
6682 AdvanceToken();
6683 break;
6684 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006685 // We may have already annotated macro names inside macro definitions.
6686 if (Cursors[I].kind != CXCursor_MacroExpansion)
6687 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006688 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006689 continue;
6690 }
6691 break;
6692 }
6693
6694 // Save the preprocessing token index; restore the non-preprocessing
6695 // token index.
6696 PreprocessingTokIdx = TokIdx;
6697 TokIdx = SavedTokIdx;
6698 return CXChildVisit_Recurse;
6699 }
6700
6701 if (cursorRange.isInvalid())
6702 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006703
6704 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 const enum CXCursorKind K = clang_getCursorKind(parent);
6707 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006708 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6709 // Attributes are annotated out-of-order, skip tokens until we reach it.
6710 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006711 ? clang_getNullCursor() : parent;
6712
6713 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6714
6715 // Avoid having the cursor of an expression "overwrite" the annotation of the
6716 // variable declaration that it belongs to.
6717 // This can happen for C++ constructor expressions whose range generally
6718 // include the variable declaration, e.g.:
6719 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006720 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006721 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006722 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006723 const unsigned I = NextToken();
6724 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6725 E->getLocStart() == D->getLocation() &&
6726 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006727 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 AdvanceToken();
6729 }
6730 }
6731 }
6732
6733 // Before recursing into the children keep some state that we are going
6734 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6735 // extra work after the child nodes are visited.
6736 // Note that we don't call VisitChildren here to avoid traversing statements
6737 // code-recursively which can blow the stack.
6738
6739 PostChildrenInfo Info;
6740 Info.Cursor = cursor;
6741 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006742 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006743 Info.BeforeChildrenTokenIdx = NextToken();
6744 PostChildrenInfos.push_back(Info);
6745
6746 return CXChildVisit_Recurse;
6747}
6748
6749bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6750 if (PostChildrenInfos.empty())
6751 return false;
6752 const PostChildrenInfo &Info = PostChildrenInfos.back();
6753 if (!clang_equalCursors(Info.Cursor, cursor))
6754 return false;
6755
6756 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6757 const unsigned AfterChildren = NextToken();
6758 SourceRange cursorRange = Info.CursorRange;
6759
6760 // Scan the tokens that are at the end of the cursor, but are not captured
6761 // but the child cursors.
6762 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6763
6764 // Scan the tokens that are at the beginning of the cursor, but are not
6765 // capture by the child cursors.
6766 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6767 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6768 break;
6769
6770 Cursors[I] = cursor;
6771 }
6772
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006773 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6774 // encountered the attribute cursor.
6775 if (clang_isAttribute(cursor.kind))
6776 TokIdx = Info.BeforeReachingCursorIdx;
6777
Guy Benyei11169dd2012-12-18 14:30:41 +00006778 PostChildrenInfos.pop_back();
6779 return false;
6780}
6781
6782static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6783 CXCursor parent,
6784 CXClientData client_data) {
6785 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6786}
6787
6788static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6789 CXClientData client_data) {
6790 return static_cast<AnnotateTokensWorker*>(client_data)->
6791 postVisitChildren(cursor);
6792}
6793
6794namespace {
6795
6796/// \brief Uses the macro expansions in the preprocessing record to find
6797/// and mark tokens that are macro arguments. This info is used by the
6798/// AnnotateTokensWorker.
6799class MarkMacroArgTokensVisitor {
6800 SourceManager &SM;
6801 CXToken *Tokens;
6802 unsigned NumTokens;
6803 unsigned CurIdx;
6804
6805public:
6806 MarkMacroArgTokensVisitor(SourceManager &SM,
6807 CXToken *tokens, unsigned numTokens)
6808 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6809
6810 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6811 if (cursor.kind != CXCursor_MacroExpansion)
6812 return CXChildVisit_Continue;
6813
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006814 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 if (macroRange.getBegin() == macroRange.getEnd())
6816 return CXChildVisit_Continue; // it's not a function macro.
6817
6818 for (; CurIdx < NumTokens; ++CurIdx) {
6819 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6820 macroRange.getBegin()))
6821 break;
6822 }
6823
6824 if (CurIdx == NumTokens)
6825 return CXChildVisit_Break;
6826
6827 for (; CurIdx < NumTokens; ++CurIdx) {
6828 SourceLocation tokLoc = getTokenLoc(CurIdx);
6829 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6830 break;
6831
6832 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6833 }
6834
6835 if (CurIdx == NumTokens)
6836 return CXChildVisit_Break;
6837
6838 return CXChildVisit_Continue;
6839 }
6840
6841private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006842 CXToken &getTok(unsigned Idx) {
6843 assert(Idx < NumTokens);
6844 return Tokens[Idx];
6845 }
6846 const CXToken &getTok(unsigned Idx) const {
6847 assert(Idx < NumTokens);
6848 return Tokens[Idx];
6849 }
6850
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006852 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 }
6854
6855 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6856 // The third field is reserved and currently not used. Use it here
6857 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006858 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006859 }
6860};
6861
6862} // end anonymous namespace
6863
6864static CXChildVisitResult
6865MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6866 CXClientData client_data) {
6867 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6868 parent);
6869}
6870
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006871/// \brief Used by \c annotatePreprocessorTokens.
6872/// \returns true if lexing was finished, false otherwise.
6873static bool lexNext(Lexer &Lex, Token &Tok,
6874 unsigned &NextIdx, unsigned NumTokens) {
6875 if (NextIdx >= NumTokens)
6876 return true;
6877
6878 ++NextIdx;
6879 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006880 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006881}
6882
Guy Benyei11169dd2012-12-18 14:30:41 +00006883static void annotatePreprocessorTokens(CXTranslationUnit TU,
6884 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006885 CXCursor *Cursors,
6886 CXToken *Tokens,
6887 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006888 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006889
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006890 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6892 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006893 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006894 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006895 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006896
6897 if (BeginLocInfo.first != EndLocInfo.first)
6898 return;
6899
6900 StringRef Buffer;
6901 bool Invalid = false;
6902 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6903 if (Buffer.empty() || Invalid)
6904 return;
6905
6906 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6907 CXXUnit->getASTContext().getLangOpts(),
6908 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6909 Buffer.end());
6910 Lex.SetCommentRetentionState(true);
6911
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006912 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006913 // Lex tokens in raw mode until we hit the end of the range, to avoid
6914 // entering #includes or expanding macros.
6915 while (true) {
6916 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006917 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6918 break;
6919 unsigned TokIdx = NextIdx-1;
6920 assert(Tok.getLocation() ==
6921 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006922
6923 reprocess:
6924 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006925 // We have found a preprocessing directive. Annotate the tokens
6926 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 //
6928 // FIXME: Some simple tests here could identify macro definitions and
6929 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006930
6931 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006932 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6933 break;
6934
Craig Topper69186e72014-06-08 08:38:04 +00006935 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006936 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006937 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6938 break;
6939
6940 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006941 IdentifierInfo &II =
6942 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006943 SourceLocation MappedTokLoc =
6944 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6945 MI = getMacroInfo(II, MappedTokLoc, TU);
6946 }
6947 }
6948
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006949 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006951 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6952 finished = true;
6953 break;
6954 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006955 // If we are in a macro definition, check if the token was ever a
6956 // macro name and annotate it if that's the case.
6957 if (MI) {
6958 SourceLocation SaveLoc = Tok.getLocation();
6959 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006960 MacroDefinitionRecord *MacroDef =
6961 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006962 Tok.setLocation(SaveLoc);
6963 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006964 Cursors[NextIdx - 1] =
6965 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006966 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006967 } while (!Tok.isAtStartOfLine());
6968
6969 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6970 assert(TokIdx <= LastIdx);
6971 SourceLocation EndLoc =
6972 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6973 CXCursor Cursor =
6974 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6975
6976 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006977 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006978
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006979 if (finished)
6980 break;
6981 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006982 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 }
6984}
6985
6986// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006987static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6988 CXToken *Tokens, unsigned NumTokens,
6989 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006990 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006991 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6992 setThreadBackgroundPriority();
6993
6994 // Determine the region of interest, which contains all of the tokens.
6995 SourceRange RegionOfInterest;
6996 RegionOfInterest.setBegin(
6997 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6998 RegionOfInterest.setEnd(
6999 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7000 Tokens[NumTokens-1])));
7001
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 // Relex the tokens within the source range to look for preprocessing
7003 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007004 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007005
7006 // If begin location points inside a macro argument, set it to the expansion
7007 // location so we can have the full context when annotating semantically.
7008 {
7009 SourceManager &SM = CXXUnit->getSourceManager();
7010 SourceLocation Loc =
7011 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7012 if (Loc.isMacroID())
7013 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7014 }
7015
Guy Benyei11169dd2012-12-18 14:30:41 +00007016 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7017 // Search and mark tokens that are macro argument expansions.
7018 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7019 Tokens, NumTokens);
7020 CursorVisitor MacroArgMarker(TU,
7021 MarkMacroArgTokensVisitorDelegate, &Visitor,
7022 /*VisitPreprocessorLast=*/true,
7023 /*VisitIncludedEntities=*/false,
7024 RegionOfInterest);
7025 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7026 }
7027
7028 // Annotate all of the source locations in the region of interest that map to
7029 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007030 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007031
7032 // FIXME: We use a ridiculous stack size here because the data-recursion
7033 // algorithm uses a large stack frame than the non-data recursive version,
7034 // and AnnotationTokensWorker currently transforms the data-recursion
7035 // algorithm back into a traditional recursion by explicitly calling
7036 // VisitChildren(). We will need to remove this explicit recursive call.
7037 W.AnnotateTokens();
7038
7039 // If we ran into any entities that involve context-sensitive keywords,
7040 // take another pass through the tokens to mark them as such.
7041 if (W.hasContextSensitiveKeywords()) {
7042 for (unsigned I = 0; I != NumTokens; ++I) {
7043 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7044 continue;
7045
7046 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7047 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007048 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007049 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7050 if (Property->getPropertyAttributesAsWritten() != 0 &&
7051 llvm::StringSwitch<bool>(II->getName())
7052 .Case("readonly", true)
7053 .Case("assign", true)
7054 .Case("unsafe_unretained", true)
7055 .Case("readwrite", true)
7056 .Case("retain", true)
7057 .Case("copy", true)
7058 .Case("nonatomic", true)
7059 .Case("atomic", true)
7060 .Case("getter", true)
7061 .Case("setter", true)
7062 .Case("strong", true)
7063 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007064 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007065 .Default(false))
7066 Tokens[I].int_data[0] = CXToken_Keyword;
7067 }
7068 continue;
7069 }
7070
7071 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7072 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7073 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7074 if (llvm::StringSwitch<bool>(II->getName())
7075 .Case("in", true)
7076 .Case("out", true)
7077 .Case("inout", true)
7078 .Case("oneway", true)
7079 .Case("bycopy", true)
7080 .Case("byref", true)
7081 .Default(false))
7082 Tokens[I].int_data[0] = CXToken_Keyword;
7083 continue;
7084 }
7085
7086 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7087 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7088 Tokens[I].int_data[0] = CXToken_Keyword;
7089 continue;
7090 }
7091 }
7092 }
7093}
7094
Guy Benyei11169dd2012-12-18 14:30:41 +00007095void clang_annotateTokens(CXTranslationUnit TU,
7096 CXToken *Tokens, unsigned NumTokens,
7097 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007098 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007099 LOG_BAD_TU(TU);
7100 return;
7101 }
7102 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007103 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007105 }
7106
7107 LOG_FUNC_SECTION {
7108 *Log << TU << ' ';
7109 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7110 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7111 *Log << clang_getRange(bloc, eloc);
7112 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007113
7114 // Any token we don't specifically annotate will have a NULL cursor.
7115 CXCursor C = clang_getNullCursor();
7116 for (unsigned I = 0; I != NumTokens; ++I)
7117 Cursors[I] = C;
7118
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007119 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007120 if (!CXXUnit)
7121 return;
7122
7123 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007124
7125 auto AnnotateTokensImpl = [=]() {
7126 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7127 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007128 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007129 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7131 }
7132}
7133
Guy Benyei11169dd2012-12-18 14:30:41 +00007134//===----------------------------------------------------------------------===//
7135// Operations for querying linkage of a cursor.
7136//===----------------------------------------------------------------------===//
7137
Guy Benyei11169dd2012-12-18 14:30:41 +00007138CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7139 if (!clang_isDeclaration(cursor.kind))
7140 return CXLinkage_Invalid;
7141
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007142 const Decl *D = cxcursor::getCursorDecl(cursor);
7143 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007144 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007145 case NoLinkage:
7146 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007147 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007148 case InternalLinkage: return CXLinkage_Internal;
7149 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007150 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007151 case ExternalLinkage: return CXLinkage_External;
7152 };
7153
7154 return CXLinkage_Invalid;
7155}
Guy Benyei11169dd2012-12-18 14:30:41 +00007156
7157//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007158// Operations for querying visibility of a cursor.
7159//===----------------------------------------------------------------------===//
7160
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007161CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7162 if (!clang_isDeclaration(cursor.kind))
7163 return CXVisibility_Invalid;
7164
7165 const Decl *D = cxcursor::getCursorDecl(cursor);
7166 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7167 switch (ND->getVisibility()) {
7168 case HiddenVisibility: return CXVisibility_Hidden;
7169 case ProtectedVisibility: return CXVisibility_Protected;
7170 case DefaultVisibility: return CXVisibility_Default;
7171 };
7172
7173 return CXVisibility_Invalid;
7174}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007175
7176//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007177// Operations for querying language of a cursor.
7178//===----------------------------------------------------------------------===//
7179
7180static CXLanguageKind getDeclLanguage(const Decl *D) {
7181 if (!D)
7182 return CXLanguage_C;
7183
7184 switch (D->getKind()) {
7185 default:
7186 break;
7187 case Decl::ImplicitParam:
7188 case Decl::ObjCAtDefsField:
7189 case Decl::ObjCCategory:
7190 case Decl::ObjCCategoryImpl:
7191 case Decl::ObjCCompatibleAlias:
7192 case Decl::ObjCImplementation:
7193 case Decl::ObjCInterface:
7194 case Decl::ObjCIvar:
7195 case Decl::ObjCMethod:
7196 case Decl::ObjCProperty:
7197 case Decl::ObjCPropertyImpl:
7198 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007199 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 return CXLanguage_ObjC;
7201 case Decl::CXXConstructor:
7202 case Decl::CXXConversion:
7203 case Decl::CXXDestructor:
7204 case Decl::CXXMethod:
7205 case Decl::CXXRecord:
7206 case Decl::ClassTemplate:
7207 case Decl::ClassTemplatePartialSpecialization:
7208 case Decl::ClassTemplateSpecialization:
7209 case Decl::Friend:
7210 case Decl::FriendTemplate:
7211 case Decl::FunctionTemplate:
7212 case Decl::LinkageSpec:
7213 case Decl::Namespace:
7214 case Decl::NamespaceAlias:
7215 case Decl::NonTypeTemplateParm:
7216 case Decl::StaticAssert:
7217 case Decl::TemplateTemplateParm:
7218 case Decl::TemplateTypeParm:
7219 case Decl::UnresolvedUsingTypename:
7220 case Decl::UnresolvedUsingValue:
7221 case Decl::Using:
7222 case Decl::UsingDirective:
7223 case Decl::UsingShadow:
7224 return CXLanguage_CPlusPlus;
7225 }
7226
7227 return CXLanguage_C;
7228}
7229
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007230static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7231 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007232 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007233
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007234 switch (D->getAvailability()) {
7235 case AR_Available:
7236 case AR_NotYetIntroduced:
7237 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007238 return getCursorAvailabilityForDecl(
7239 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007240 return CXAvailability_Available;
7241
7242 case AR_Deprecated:
7243 return CXAvailability_Deprecated;
7244
7245 case AR_Unavailable:
7246 return CXAvailability_NotAvailable;
7247 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007248
7249 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007250}
7251
Guy Benyei11169dd2012-12-18 14:30:41 +00007252enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7253 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007254 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7255 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007256
7257 return CXAvailability_Available;
7258}
7259
7260static CXVersion convertVersion(VersionTuple In) {
7261 CXVersion Out = { -1, -1, -1 };
7262 if (In.empty())
7263 return Out;
7264
7265 Out.Major = In.getMajor();
7266
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007267 Optional<unsigned> Minor = In.getMinor();
7268 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007269 Out.Minor = *Minor;
7270 else
7271 return Out;
7272
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007273 Optional<unsigned> Subminor = In.getSubminor();
7274 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007275 Out.Subminor = *Subminor;
7276
7277 return Out;
7278}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007279
Alex Lorenz1345ea22017-06-12 19:06:30 +00007280static void getCursorPlatformAvailabilityForDecl(
7281 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7282 int *always_unavailable, CXString *unavailable_message,
7283 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007284 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007285 for (auto A : D->attrs()) {
7286 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007287 HadAvailAttr = true;
7288 if (always_deprecated)
7289 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007290 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007291 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007292 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007293 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007294 continue;
7295 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007296
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007297 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007298 HadAvailAttr = true;
7299 if (always_unavailable)
7300 *always_unavailable = 1;
7301 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007302 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007303 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7304 }
7305 continue;
7306 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007307
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007308 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007309 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007310 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007311 }
7312 }
7313
7314 if (!HadAvailAttr)
7315 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7316 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007317 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7318 deprecated_message, always_unavailable, unavailable_message,
7319 AvailabilityAttrs);
7320
7321 if (AvailabilityAttrs.empty())
7322 return;
7323
7324 std::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7325 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
Reid Klecknere6cde142017-08-04 21:52:25 +00007326 return LHS->getPlatform()->getName() <
7327 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007328 });
7329 ASTContext &Ctx = D->getASTContext();
7330 auto It = std::unique(
7331 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7332 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7333 if (LHS->getPlatform() != RHS->getPlatform())
7334 return false;
7335
7336 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7337 LHS->getDeprecated() == RHS->getDeprecated() &&
7338 LHS->getObsoleted() == RHS->getObsoleted() &&
7339 LHS->getMessage() == RHS->getMessage() &&
7340 LHS->getReplacement() == RHS->getReplacement())
7341 return true;
7342
7343 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7344 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7345 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7346 return false;
7347
7348 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7349 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7350
7351 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7352 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7353 if (LHS->getMessage().empty())
7354 LHS->setMessage(Ctx, RHS->getMessage());
7355 if (LHS->getReplacement().empty())
7356 LHS->setReplacement(Ctx, RHS->getReplacement());
7357 }
7358
7359 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7360 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7361 if (LHS->getMessage().empty())
7362 LHS->setMessage(Ctx, RHS->getMessage());
7363 if (LHS->getReplacement().empty())
7364 LHS->setReplacement(Ctx, RHS->getReplacement());
7365 }
7366
7367 return true;
7368 });
7369 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007370}
7371
Alex Lorenz1345ea22017-06-12 19:06:30 +00007372int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007373 CXString *deprecated_message,
7374 int *always_unavailable,
7375 CXString *unavailable_message,
7376 CXPlatformAvailability *availability,
7377 int availability_size) {
7378 if (always_deprecated)
7379 *always_deprecated = 0;
7380 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007381 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007382 if (always_unavailable)
7383 *always_unavailable = 0;
7384 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007385 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007386
Guy Benyei11169dd2012-12-18 14:30:41 +00007387 if (!clang_isDeclaration(cursor.kind))
7388 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007389
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007390 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007391 if (!D)
7392 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007393
Alex Lorenz1345ea22017-06-12 19:06:30 +00007394 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7395 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7396 always_unavailable, unavailable_message,
7397 AvailabilityAttrs);
7398 for (const auto &Avail :
7399 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7400 .take_front(availability_size))) {
7401 availability[Avail.index()].Platform =
7402 cxstring::createDup(Avail.value()->getPlatform()->getName());
7403 availability[Avail.index()].Introduced =
7404 convertVersion(Avail.value()->getIntroduced());
7405 availability[Avail.index()].Deprecated =
7406 convertVersion(Avail.value()->getDeprecated());
7407 availability[Avail.index()].Obsoleted =
7408 convertVersion(Avail.value()->getObsoleted());
7409 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7410 availability[Avail.index()].Message =
7411 cxstring::createDup(Avail.value()->getMessage());
7412 }
7413
7414 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007415}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007416
Guy Benyei11169dd2012-12-18 14:30:41 +00007417void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7418 clang_disposeString(availability->Platform);
7419 clang_disposeString(availability->Message);
7420}
7421
7422CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7423 if (clang_isDeclaration(cursor.kind))
7424 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7425
7426 return CXLanguage_Invalid;
7427}
7428
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007429CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7430 const Decl *D = cxcursor::getCursorDecl(cursor);
7431 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7432 switch (VD->getTLSKind()) {
7433 case VarDecl::TLS_None:
7434 return CXTLS_None;
7435 case VarDecl::TLS_Dynamic:
7436 return CXTLS_Dynamic;
7437 case VarDecl::TLS_Static:
7438 return CXTLS_Static;
7439 }
7440 }
7441
7442 return CXTLS_None;
7443}
7444
Guy Benyei11169dd2012-12-18 14:30:41 +00007445 /// \brief If the given cursor is the "templated" declaration
7446 /// descibing a class or function template, return the class or
7447 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007448static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007449 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007450 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007451
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007452 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7454 return FunTmpl;
7455
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007456 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7458 return ClassTmpl;
7459
7460 return D;
7461}
7462
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007463
7464enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7465 StorageClass sc = SC_None;
7466 const Decl *D = getCursorDecl(C);
7467 if (D) {
7468 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7469 sc = FD->getStorageClass();
7470 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7471 sc = VD->getStorageClass();
7472 } else {
7473 return CX_SC_Invalid;
7474 }
7475 } else {
7476 return CX_SC_Invalid;
7477 }
7478 switch (sc) {
7479 case SC_None:
7480 return CX_SC_None;
7481 case SC_Extern:
7482 return CX_SC_Extern;
7483 case SC_Static:
7484 return CX_SC_Static;
7485 case SC_PrivateExtern:
7486 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007487 case SC_Auto:
7488 return CX_SC_Auto;
7489 case SC_Register:
7490 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007491 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007492 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007493}
7494
Guy Benyei11169dd2012-12-18 14:30:41 +00007495CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7496 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007497 if (const Decl *D = getCursorDecl(cursor)) {
7498 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007499 if (!DC)
7500 return clang_getNullCursor();
7501
7502 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7503 getCursorTU(cursor));
7504 }
7505 }
7506
7507 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007508 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007509 return MakeCXCursor(D, getCursorTU(cursor));
7510 }
7511
7512 return clang_getNullCursor();
7513}
7514
7515CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7516 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007517 if (const Decl *D = getCursorDecl(cursor)) {
7518 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007519 if (!DC)
7520 return clang_getNullCursor();
7521
7522 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7523 getCursorTU(cursor));
7524 }
7525 }
7526
7527 // FIXME: Note that we can't easily compute the lexical context of a
7528 // statement or expression, so we return nothing.
7529 return clang_getNullCursor();
7530}
7531
7532CXFile clang_getIncludedFile(CXCursor cursor) {
7533 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007534 return nullptr;
7535
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007536 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007537 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007538}
7539
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007540unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7541 if (C.kind != CXCursor_ObjCPropertyDecl)
7542 return CXObjCPropertyAttr_noattr;
7543
7544 unsigned Result = CXObjCPropertyAttr_noattr;
7545 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7546 ObjCPropertyDecl::PropertyAttributeKind Attr =
7547 PD->getPropertyAttributesAsWritten();
7548
7549#define SET_CXOBJCPROP_ATTR(A) \
7550 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7551 Result |= CXObjCPropertyAttr_##A
7552 SET_CXOBJCPROP_ATTR(readonly);
7553 SET_CXOBJCPROP_ATTR(getter);
7554 SET_CXOBJCPROP_ATTR(assign);
7555 SET_CXOBJCPROP_ATTR(readwrite);
7556 SET_CXOBJCPROP_ATTR(retain);
7557 SET_CXOBJCPROP_ATTR(copy);
7558 SET_CXOBJCPROP_ATTR(nonatomic);
7559 SET_CXOBJCPROP_ATTR(setter);
7560 SET_CXOBJCPROP_ATTR(atomic);
7561 SET_CXOBJCPROP_ATTR(weak);
7562 SET_CXOBJCPROP_ATTR(strong);
7563 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007564 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007565#undef SET_CXOBJCPROP_ATTR
7566
7567 return Result;
7568}
7569
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007570unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7571 if (!clang_isDeclaration(C.kind))
7572 return CXObjCDeclQualifier_None;
7573
7574 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7575 const Decl *D = getCursorDecl(C);
7576 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7577 QT = MD->getObjCDeclQualifier();
7578 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7579 QT = PD->getObjCDeclQualifier();
7580 if (QT == Decl::OBJC_TQ_None)
7581 return CXObjCDeclQualifier_None;
7582
7583 unsigned Result = CXObjCDeclQualifier_None;
7584 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7585 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7586 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7587 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7588 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7589 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7590
7591 return Result;
7592}
7593
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007594unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7595 if (!clang_isDeclaration(C.kind))
7596 return 0;
7597
7598 const Decl *D = getCursorDecl(C);
7599 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7600 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7601 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7602 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7603
7604 return 0;
7605}
7606
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007607unsigned clang_Cursor_isVariadic(CXCursor C) {
7608 if (!clang_isDeclaration(C.kind))
7609 return 0;
7610
7611 const Decl *D = getCursorDecl(C);
7612 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7613 return FD->isVariadic();
7614 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7615 return MD->isVariadic();
7616
7617 return 0;
7618}
7619
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007620unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7621 CXString *language, CXString *definedIn,
7622 unsigned *isGenerated) {
7623 if (!clang_isDeclaration(C.kind))
7624 return 0;
7625
7626 const Decl *D = getCursorDecl(C);
7627
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00007628 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007629 if (language)
7630 *language = cxstring::createDup(attr->getLanguage());
7631 if (definedIn)
7632 *definedIn = cxstring::createDup(attr->getDefinedIn());
7633 if (isGenerated)
7634 *isGenerated = attr->getGeneratedDeclaration();
7635 return 1;
7636 }
7637 return 0;
7638}
7639
Guy Benyei11169dd2012-12-18 14:30:41 +00007640CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7641 if (!clang_isDeclaration(C.kind))
7642 return clang_getNullRange();
7643
7644 const Decl *D = getCursorDecl(C);
7645 ASTContext &Context = getCursorContext(C);
7646 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7647 if (!RC)
7648 return clang_getNullRange();
7649
7650 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7651}
7652
7653CXString clang_Cursor_getRawCommentText(CXCursor C) {
7654 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007655 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007656
7657 const Decl *D = getCursorDecl(C);
7658 ASTContext &Context = getCursorContext(C);
7659 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7660 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7661 StringRef();
7662
7663 // Don't duplicate the string because RawText points directly into source
7664 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007665 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007666}
7667
7668CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7669 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007670 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007671
7672 const Decl *D = getCursorDecl(C);
7673 const ASTContext &Context = getCursorContext(C);
7674 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7675
7676 if (RC) {
7677 StringRef BriefText = RC->getBriefText(Context);
7678
7679 // Don't duplicate the string because RawComment ensures that this memory
7680 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007681 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007682 }
7683
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007684 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007685}
7686
Guy Benyei11169dd2012-12-18 14:30:41 +00007687CXModule clang_Cursor_getModule(CXCursor C) {
7688 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007689 if (const ImportDecl *ImportD =
7690 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007691 return ImportD->getImportedModule();
7692 }
7693
Craig Topper69186e72014-06-08 08:38:04 +00007694 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007695}
7696
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007697CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7698 if (isNotUsableTU(TU)) {
7699 LOG_BAD_TU(TU);
7700 return nullptr;
7701 }
7702 if (!File)
7703 return nullptr;
7704 FileEntry *FE = static_cast<FileEntry *>(File);
7705
7706 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7707 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7708 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7709
Richard Smithfeb54b62014-10-23 02:01:19 +00007710 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007711}
7712
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007713CXFile clang_Module_getASTFile(CXModule CXMod) {
7714 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007715 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007716 Module *Mod = static_cast<Module*>(CXMod);
7717 return const_cast<FileEntry *>(Mod->getASTFile());
7718}
7719
Guy Benyei11169dd2012-12-18 14:30:41 +00007720CXModule clang_Module_getParent(CXModule CXMod) {
7721 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007722 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007723 Module *Mod = static_cast<Module*>(CXMod);
7724 return Mod->Parent;
7725}
7726
7727CXString clang_Module_getName(CXModule CXMod) {
7728 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007729 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007730 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007731 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007732}
7733
7734CXString clang_Module_getFullName(CXModule CXMod) {
7735 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007736 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007737 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007738 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007739}
7740
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007741int clang_Module_isSystem(CXModule CXMod) {
7742 if (!CXMod)
7743 return 0;
7744 Module *Mod = static_cast<Module*>(CXMod);
7745 return Mod->IsSystem;
7746}
7747
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007748unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7749 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007750 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007751 LOG_BAD_TU(TU);
7752 return 0;
7753 }
7754 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 return 0;
7756 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007757 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7758 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7759 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007760}
7761
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007762CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7763 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007764 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007765 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007766 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007767 }
7768 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007769 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007770 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007771 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007772
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007773 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7774 if (Index < TopHeaders.size())
7775 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007776
Craig Topper69186e72014-06-08 08:38:04 +00007777 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007778}
7779
Guy Benyei11169dd2012-12-18 14:30:41 +00007780//===----------------------------------------------------------------------===//
7781// C++ AST instrospection.
7782//===----------------------------------------------------------------------===//
7783
Jonathan Coe29565352016-04-27 12:48:25 +00007784unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7785 if (!clang_isDeclaration(C.kind))
7786 return 0;
7787
7788 const Decl *D = cxcursor::getCursorDecl(C);
7789 const CXXConstructorDecl *Constructor =
7790 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7791 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7792}
7793
7794unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7795 if (!clang_isDeclaration(C.kind))
7796 return 0;
7797
7798 const Decl *D = cxcursor::getCursorDecl(C);
7799 const CXXConstructorDecl *Constructor =
7800 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7801 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7802}
7803
7804unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7805 if (!clang_isDeclaration(C.kind))
7806 return 0;
7807
7808 const Decl *D = cxcursor::getCursorDecl(C);
7809 const CXXConstructorDecl *Constructor =
7810 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7811 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7812}
7813
7814unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7815 if (!clang_isDeclaration(C.kind))
7816 return 0;
7817
7818 const Decl *D = cxcursor::getCursorDecl(C);
7819 const CXXConstructorDecl *Constructor =
7820 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7821 // Passing 'false' excludes constructors marked 'explicit'.
7822 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7823}
7824
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007825unsigned clang_CXXField_isMutable(CXCursor C) {
7826 if (!clang_isDeclaration(C.kind))
7827 return 0;
7828
7829 if (const auto D = cxcursor::getCursorDecl(C))
7830 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7831 return FD->isMutable() ? 1 : 0;
7832 return 0;
7833}
7834
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007835unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7836 if (!clang_isDeclaration(C.kind))
7837 return 0;
7838
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007839 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007840 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007841 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007842 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7843}
7844
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007845unsigned clang_CXXMethod_isConst(CXCursor C) {
7846 if (!clang_isDeclaration(C.kind))
7847 return 0;
7848
7849 const Decl *D = cxcursor::getCursorDecl(C);
7850 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007851 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007852 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7853}
7854
Jonathan Coe29565352016-04-27 12:48:25 +00007855unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7856 if (!clang_isDeclaration(C.kind))
7857 return 0;
7858
7859 const Decl *D = cxcursor::getCursorDecl(C);
7860 const CXXMethodDecl *Method =
7861 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7862 return (Method && Method->isDefaulted()) ? 1 : 0;
7863}
7864
Guy Benyei11169dd2012-12-18 14:30:41 +00007865unsigned clang_CXXMethod_isStatic(CXCursor C) {
7866 if (!clang_isDeclaration(C.kind))
7867 return 0;
7868
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007869 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007870 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007871 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007872 return (Method && Method->isStatic()) ? 1 : 0;
7873}
7874
7875unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7876 if (!clang_isDeclaration(C.kind))
7877 return 0;
7878
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007879 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007880 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007881 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 return (Method && Method->isVirtual()) ? 1 : 0;
7883}
Guy Benyei11169dd2012-12-18 14:30:41 +00007884
Alex Lorenzff7f42e2017-07-12 11:35:11 +00007885unsigned clang_EnumDecl_isScoped(CXCursor C) {
7886 if (!clang_isDeclaration(C.kind))
7887 return 0;
7888
7889 const Decl *D = cxcursor::getCursorDecl(C);
7890 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
7891 return (Enum && Enum->isScoped()) ? 1 : 0;
7892}
7893
Guy Benyei11169dd2012-12-18 14:30:41 +00007894//===----------------------------------------------------------------------===//
7895// Attribute introspection.
7896//===----------------------------------------------------------------------===//
7897
Guy Benyei11169dd2012-12-18 14:30:41 +00007898CXType clang_getIBOutletCollectionType(CXCursor C) {
7899 if (C.kind != CXCursor_IBOutletCollectionAttr)
7900 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7901
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007902 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007903 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7904
7905 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7906}
Guy Benyei11169dd2012-12-18 14:30:41 +00007907
7908//===----------------------------------------------------------------------===//
7909// Inspecting memory usage.
7910//===----------------------------------------------------------------------===//
7911
7912typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7913
7914static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7915 enum CXTUResourceUsageKind k,
7916 unsigned long amount) {
7917 CXTUResourceUsageEntry entry = { k, amount };
7918 entries.push_back(entry);
7919}
7920
Guy Benyei11169dd2012-12-18 14:30:41 +00007921const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7922 const char *str = "";
7923 switch (kind) {
7924 case CXTUResourceUsage_AST:
7925 str = "ASTContext: expressions, declarations, and types";
7926 break;
7927 case CXTUResourceUsage_Identifiers:
7928 str = "ASTContext: identifiers";
7929 break;
7930 case CXTUResourceUsage_Selectors:
7931 str = "ASTContext: selectors";
7932 break;
7933 case CXTUResourceUsage_GlobalCompletionResults:
7934 str = "Code completion: cached global results";
7935 break;
7936 case CXTUResourceUsage_SourceManagerContentCache:
7937 str = "SourceManager: content cache allocator";
7938 break;
7939 case CXTUResourceUsage_AST_SideTables:
7940 str = "ASTContext: side tables";
7941 break;
7942 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7943 str = "SourceManager: malloc'ed memory buffers";
7944 break;
7945 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7946 str = "SourceManager: mmap'ed memory buffers";
7947 break;
7948 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7949 str = "ExternalASTSource: malloc'ed memory buffers";
7950 break;
7951 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7952 str = "ExternalASTSource: mmap'ed memory buffers";
7953 break;
7954 case CXTUResourceUsage_Preprocessor:
7955 str = "Preprocessor: malloc'ed memory";
7956 break;
7957 case CXTUResourceUsage_PreprocessingRecord:
7958 str = "Preprocessor: PreprocessingRecord";
7959 break;
7960 case CXTUResourceUsage_SourceManager_DataStructures:
7961 str = "SourceManager: data structures and tables";
7962 break;
7963 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7964 str = "Preprocessor: header search tables";
7965 break;
7966 }
7967 return str;
7968}
7969
7970CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007971 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007972 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007973 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 return usage;
7975 }
7976
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007977 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007978 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007979 ASTContext &astContext = astUnit->getASTContext();
7980
7981 // How much memory is used by AST nodes and types?
7982 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7983 (unsigned long) astContext.getASTAllocatedMemory());
7984
7985 // How much memory is used by identifiers?
7986 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7987 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7988
7989 // How much memory is used for selectors?
7990 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7991 (unsigned long) astContext.Selectors.getTotalMemory());
7992
7993 // How much memory is used by ASTContext's side tables?
7994 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7995 (unsigned long) astContext.getSideTableAllocatedMemory());
7996
7997 // How much memory is used for caching global code completion results?
7998 unsigned long completionBytes = 0;
7999 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008000 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 completionBytes = completionAllocator->getTotalMemory();
8002 }
8003 createCXTUResourceUsageEntry(*entries,
8004 CXTUResourceUsage_GlobalCompletionResults,
8005 completionBytes);
8006
8007 // How much memory is being used by SourceManager's content cache?
8008 createCXTUResourceUsageEntry(*entries,
8009 CXTUResourceUsage_SourceManagerContentCache,
8010 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8011
8012 // How much memory is being used by the MemoryBuffer's in SourceManager?
8013 const SourceManager::MemoryBufferSizes &srcBufs =
8014 astUnit->getSourceManager().getMemoryBufferSizes();
8015
8016 createCXTUResourceUsageEntry(*entries,
8017 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8018 (unsigned long) srcBufs.malloc_bytes);
8019 createCXTUResourceUsageEntry(*entries,
8020 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8021 (unsigned long) srcBufs.mmap_bytes);
8022 createCXTUResourceUsageEntry(*entries,
8023 CXTUResourceUsage_SourceManager_DataStructures,
8024 (unsigned long) astContext.getSourceManager()
8025 .getDataStructureSizes());
8026
8027 // How much memory is being used by the ExternalASTSource?
8028 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8029 const ExternalASTSource::MemoryBufferSizes &sizes =
8030 esrc->getMemoryBufferSizes();
8031
8032 createCXTUResourceUsageEntry(*entries,
8033 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8034 (unsigned long) sizes.malloc_bytes);
8035 createCXTUResourceUsageEntry(*entries,
8036 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8037 (unsigned long) sizes.mmap_bytes);
8038 }
8039
8040 // How much memory is being used by the Preprocessor?
8041 Preprocessor &pp = astUnit->getPreprocessor();
8042 createCXTUResourceUsageEntry(*entries,
8043 CXTUResourceUsage_Preprocessor,
8044 pp.getTotalMemory());
8045
8046 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8047 createCXTUResourceUsageEntry(*entries,
8048 CXTUResourceUsage_PreprocessingRecord,
8049 pRec->getTotalMemory());
8050 }
8051
8052 createCXTUResourceUsageEntry(*entries,
8053 CXTUResourceUsage_Preprocessor_HeaderSearch,
8054 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008055
Guy Benyei11169dd2012-12-18 14:30:41 +00008056 CXTUResourceUsage usage = { (void*) entries.get(),
8057 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008058 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008059 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008060 return usage;
8061}
8062
8063void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8064 if (usage.data)
8065 delete (MemUsageEntries*) usage.data;
8066}
8067
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008068CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8069 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008070 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008071 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008072
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008073 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008074 LOG_BAD_TU(TU);
8075 return skipped;
8076 }
8077
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008078 if (!file)
8079 return skipped;
8080
8081 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8082 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8083 if (!ppRec)
8084 return skipped;
8085
8086 ASTContext &Ctx = astUnit->getASTContext();
8087 SourceManager &sm = Ctx.getSourceManager();
8088 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8089 FileID wantedFileID = sm.translateFile(fileEntry);
8090
8091 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8092 std::vector<SourceRange> wantedRanges;
8093 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8094 i != ei; ++i) {
8095 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8096 wantedRanges.push_back(*i);
8097 }
8098
8099 skipped->count = wantedRanges.size();
8100 skipped->ranges = new CXSourceRange[skipped->count];
8101 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8102 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8103
8104 return skipped;
8105}
8106
Cameron Desrochersd8091282016-08-18 15:43:55 +00008107CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8108 CXSourceRangeList *skipped = new CXSourceRangeList;
8109 skipped->count = 0;
8110 skipped->ranges = nullptr;
8111
8112 if (isNotUsableTU(TU)) {
8113 LOG_BAD_TU(TU);
8114 return skipped;
8115 }
8116
8117 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8118 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8119 if (!ppRec)
8120 return skipped;
8121
8122 ASTContext &Ctx = astUnit->getASTContext();
8123
8124 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8125
8126 skipped->count = SkippedRanges.size();
8127 skipped->ranges = new CXSourceRange[skipped->count];
8128 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8129 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8130
8131 return skipped;
8132}
8133
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008134void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8135 if (ranges) {
8136 delete[] ranges->ranges;
8137 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008138 }
8139}
8140
Guy Benyei11169dd2012-12-18 14:30:41 +00008141void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8142 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8143 for (unsigned I = 0; I != Usage.numEntries; ++I)
8144 fprintf(stderr, " %s: %lu\n",
8145 clang_getTUResourceUsageName(Usage.entries[I].kind),
8146 Usage.entries[I].amount);
8147
8148 clang_disposeCXTUResourceUsage(Usage);
8149}
8150
8151//===----------------------------------------------------------------------===//
8152// Misc. utility functions.
8153//===----------------------------------------------------------------------===//
8154
8155/// Default to using an 8 MB stack size on "safety" threads.
8156static unsigned SafetyStackThreadSize = 8 << 20;
8157
8158namespace clang {
8159
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008160bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 unsigned Size) {
8162 if (!Size)
8163 Size = GetSafetyThreadStackSize();
8164 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008165 return CRC.RunSafelyOnThread(Fn, Size);
8166 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008167}
8168
8169unsigned GetSafetyThreadStackSize() {
8170 return SafetyStackThreadSize;
8171}
8172
8173void SetSafetyThreadStackSize(unsigned Value) {
8174 SafetyStackThreadSize = Value;
8175}
8176
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008177}
Guy Benyei11169dd2012-12-18 14:30:41 +00008178
8179void clang::setThreadBackgroundPriority() {
8180 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8181 return;
8182
Alp Toker1a86ad22014-07-06 06:24:00 +00008183#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008184 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8185#endif
8186}
8187
8188void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8189 if (!Unit)
8190 return;
8191
8192 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8193 DEnd = Unit->stored_diag_end();
8194 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008195 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008196 CXString Msg = clang_formatDiagnostic(&Diag,
8197 clang_defaultDiagnosticDisplayOptions());
8198 fprintf(stderr, "%s\n", clang_getCString(Msg));
8199 clang_disposeString(Msg);
8200 }
8201#ifdef LLVM_ON_WIN32
8202 // On Windows, force a flush, since there may be multiple copies of
8203 // stderr and stdout in the file system, all with different buffers
8204 // but writing to the same device.
8205 fflush(stderr);
8206#endif
8207}
8208
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008209MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8210 SourceLocation MacroDefLoc,
8211 CXTranslationUnit TU){
8212 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008213 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008214 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008215 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008216
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008217 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008218 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008219 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008220 if (MD) {
8221 for (MacroDirective::DefInfo
8222 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8223 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8224 return Def.getMacroInfo();
8225 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008226 }
8227
Craig Topper69186e72014-06-08 08:38:04 +00008228 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008229}
8230
Richard Smith66a81862015-05-04 02:25:31 +00008231const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008232 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008233 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008234 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008235 const IdentifierInfo *II = MacroDef->getName();
8236 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008237 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008238
8239 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8240}
8241
Richard Smith66a81862015-05-04 02:25:31 +00008242MacroDefinitionRecord *
8243cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8244 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008245 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008246 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008247 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008248 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008249
8250 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008251 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008252 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8253 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008254 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008255
8256 // Check that the token is inside the definition and not its argument list.
8257 SourceManager &SM = Unit->getSourceManager();
8258 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008259 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008260 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008261 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008262
8263 Preprocessor &PP = Unit->getPreprocessor();
8264 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8265 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008266 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008267
Alp Toker2d57cea2014-05-17 04:53:25 +00008268 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008269 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008270 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008271
8272 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008273 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008274 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008275
Richard Smith20e883e2015-04-29 23:20:19 +00008276 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008277 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008278 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008279
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008280 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008281}
8282
Richard Smith66a81862015-05-04 02:25:31 +00008283MacroDefinitionRecord *
8284cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8285 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008286 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008287 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008288
8289 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008290 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008291 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008292 Preprocessor &PP = Unit->getPreprocessor();
8293 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008294 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008295 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8296 Token Tok;
8297 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008298 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008299
8300 return checkForMacroInMacroDefinition(MI, Tok, TU);
8301}
8302
Guy Benyei11169dd2012-12-18 14:30:41 +00008303CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008304 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008305}
8306
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008307Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8308 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008309 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008310 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008311 if (Unit->isMainFileAST())
8312 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008313 return *this;
8314 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008315 } else {
8316 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008317 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008318 return *this;
8319}
8320
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008321Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8322 *this << FE->getName();
8323 return *this;
8324}
8325
8326Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8327 CXString cursorName = clang_getCursorDisplayName(cursor);
8328 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8329 clang_disposeString(cursorName);
8330 return *this;
8331}
8332
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008333Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8334 CXFile File;
8335 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008336 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008337 CXString FileName = clang_getFileName(File);
8338 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8339 clang_disposeString(FileName);
8340 return *this;
8341}
8342
8343Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8344 CXSourceLocation BLoc = clang_getRangeStart(range);
8345 CXSourceLocation ELoc = clang_getRangeEnd(range);
8346
8347 CXFile BFile;
8348 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008349 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008350
8351 CXFile EFile;
8352 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008353 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008354
8355 CXString BFileName = clang_getFileName(BFile);
8356 if (BFile == EFile) {
8357 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8358 BLine, BColumn, ELine, EColumn);
8359 } else {
8360 CXString EFileName = clang_getFileName(EFile);
8361 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8362 BLine, BColumn)
8363 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8364 ELine, EColumn);
8365 clang_disposeString(EFileName);
8366 }
8367 clang_disposeString(BFileName);
8368 return *this;
8369}
8370
8371Logger &cxindex::Logger::operator<<(CXString Str) {
8372 *this << clang_getCString(Str);
8373 return *this;
8374}
8375
8376Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8377 LogOS << Fmt;
8378 return *this;
8379}
8380
Chandler Carruth37ad2582014-06-27 15:14:39 +00008381static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8382
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008383cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008384 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008385
8386 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8387
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008388 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008389 OS << "[libclang:" << Name << ':';
8390
Alp Toker1a86ad22014-07-06 06:24:00 +00008391#ifdef USE_DARWIN_THREADS
8392 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008393 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8394 OS << tid << ':';
8395#endif
8396
8397 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8398 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008399 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008400
8401 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008402 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008403 OS << "--------------------------------------------------\n";
8404 }
8405}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008406
8407#ifdef CLANG_TOOL_EXTRA_BUILD
8408// This anchor is used to force the linker to link the clang-tidy plugin.
8409extern volatile int ClangTidyPluginAnchorSource;
8410static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8411 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008412
8413// This anchor is used to force the linker to link the clang-include-fixer
8414// plugin.
8415extern volatile int ClangIncludeFixerPluginAnchorSource;
8416static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8417 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008418#endif