blob: 3921c055b83841e068e269bcee2323c61ed7b5d9 [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)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001745DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001746DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1747DEFAULT_TYPELOC_IMPL(Vector, Type)
1748DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1749DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1750DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1751DEFAULT_TYPELOC_IMPL(Record, TagType)
1752DEFAULT_TYPELOC_IMPL(Enum, TagType)
1753DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1754DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1755DEFAULT_TYPELOC_IMPL(Auto, Type)
1756
1757bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1758 // Visit the nested-name-specifier, if present.
1759 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1760 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1761 return true;
1762
1763 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001764 for (const auto &I : D->bases()) {
1765 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001766 return true;
1767 }
1768 }
1769
1770 return VisitTagDecl(D);
1771}
1772
1773bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001774 for (const auto *I : D->attrs())
1775 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001776 return true;
1777
1778 return false;
1779}
1780
1781//===----------------------------------------------------------------------===//
1782// Data-recursive visitor methods.
1783//===----------------------------------------------------------------------===//
1784
1785namespace {
1786#define DEF_JOB(NAME, DATA, KIND)\
1787class NAME : public VisitorJob {\
1788public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001789 NAME(const DATA *d, CXCursor parent) : \
1790 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001792 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001793};
1794
1795DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1796DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1797DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1798DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001799DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1800DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1801DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1802#undef DEF_JOB
1803
James Y Knight04ec5bf2015-12-24 02:59:37 +00001804class ExplicitTemplateArgsVisit : public VisitorJob {
1805public:
1806 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1807 const TemplateArgumentLoc *End, CXCursor parent)
1808 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1809 End) {}
1810 static bool classof(const VisitorJob *VJ) {
1811 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1812 }
1813 const TemplateArgumentLoc *begin() const {
1814 return static_cast<const TemplateArgumentLoc *>(data[0]);
1815 }
1816 const TemplateArgumentLoc *end() {
1817 return static_cast<const TemplateArgumentLoc *>(data[1]);
1818 }
1819};
Guy Benyei11169dd2012-12-18 14:30:41 +00001820class DeclVisit : public VisitorJob {
1821public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001822 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001824 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001825 static bool classof(const VisitorJob *VJ) {
1826 return VJ->getKind() == DeclVisitKind;
1827 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001828 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001829 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001830};
1831class TypeLocVisit : public VisitorJob {
1832public:
1833 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1834 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1835 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1836
1837 static bool classof(const VisitorJob *VJ) {
1838 return VJ->getKind() == TypeLocVisitKind;
1839 }
1840
1841 TypeLoc get() const {
1842 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001843 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001844 }
1845};
1846
1847class LabelRefVisit : public VisitorJob {
1848public:
1849 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1850 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1851 labelLoc.getPtrEncoding()) {}
1852
1853 static bool classof(const VisitorJob *VJ) {
1854 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1855 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001856 const LabelDecl *get() const {
1857 return static_cast<const LabelDecl *>(data[0]);
1858 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001859 SourceLocation getLoc() const {
1860 return SourceLocation::getFromPtrEncoding(data[1]); }
1861};
1862
1863class NestedNameSpecifierLocVisit : public VisitorJob {
1864public:
1865 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1866 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1867 Qualifier.getNestedNameSpecifier(),
1868 Qualifier.getOpaqueData()) { }
1869
1870 static bool classof(const VisitorJob *VJ) {
1871 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1872 }
1873
1874 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001875 return NestedNameSpecifierLoc(
1876 const_cast<NestedNameSpecifier *>(
1877 static_cast<const NestedNameSpecifier *>(data[0])),
1878 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 }
1880};
1881
1882class DeclarationNameInfoVisit : public VisitorJob {
1883public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001884 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001885 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 static bool classof(const VisitorJob *VJ) {
1887 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1888 }
1889 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001890 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 switch (S->getStmtClass()) {
1892 default:
1893 llvm_unreachable("Unhandled Stmt");
1894 case clang::Stmt::MSDependentExistsStmtClass:
1895 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1896 case Stmt::CXXDependentScopeMemberExprClass:
1897 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1898 case Stmt::DependentScopeDeclRefExprClass:
1899 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001900 case Stmt::OMPCriticalDirectiveClass:
1901 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 }
1903 }
1904};
1905class MemberRefVisit : public VisitorJob {
1906public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001907 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1909 L.getPtrEncoding()) {}
1910 static bool classof(const VisitorJob *VJ) {
1911 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1912 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001913 const FieldDecl *get() const {
1914 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 }
1916 SourceLocation getLoc() const {
1917 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1918 }
1919};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001920class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001921 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001922 VisitorWorkList &WL;
1923 CXCursor Parent;
1924public:
1925 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1926 : WL(wl), Parent(parent) {}
1927
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001928 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1929 void VisitBlockExpr(const BlockExpr *B);
1930 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1931 void VisitCompoundStmt(const CompoundStmt *S);
1932 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1933 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1934 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1935 void VisitCXXNewExpr(const CXXNewExpr *E);
1936 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1937 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1938 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1939 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1940 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1941 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1942 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1943 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001944 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001945 void VisitDeclRefExpr(const DeclRefExpr *D);
1946 void VisitDeclStmt(const DeclStmt *S);
1947 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1948 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1949 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1950 void VisitForStmt(const ForStmt *FS);
1951 void VisitGotoStmt(const GotoStmt *GS);
1952 void VisitIfStmt(const IfStmt *If);
1953 void VisitInitListExpr(const InitListExpr *IE);
1954 void VisitMemberExpr(const MemberExpr *M);
1955 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1956 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1957 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1958 void VisitOverloadExpr(const OverloadExpr *E);
1959 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1960 void VisitStmt(const Stmt *S);
1961 void VisitSwitchStmt(const SwitchStmt *S);
1962 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001963 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1964 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1965 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1966 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1967 void VisitVAArgExpr(const VAArgExpr *E);
1968 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1969 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1970 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1971 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001972 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001973 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001974 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001975 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001976 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001977 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001978 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001979 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001980 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001981 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001982 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001983 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001984 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001985 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001986 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001987 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001988 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001989 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001990 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001991 void
1992 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001993 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00001994 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001995 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00001996 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001997 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00001998 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00001999 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002000 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002001 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002002 void
2003 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002004 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002005 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002006 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002007 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002008 void VisitOMPDistributeParallelForDirective(
2009 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002010 void VisitOMPDistributeParallelForSimdDirective(
2011 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002012 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002013 void VisitOMPTargetParallelForSimdDirective(
2014 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002015 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002016 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002017 void VisitOMPTeamsDistributeSimdDirective(
2018 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002019 void VisitOMPTeamsDistributeParallelForSimdDirective(
2020 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002021 void VisitOMPTeamsDistributeParallelForDirective(
2022 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002023 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002024 void VisitOMPTargetTeamsDistributeDirective(
2025 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002026 void VisitOMPTargetTeamsDistributeParallelForDirective(
2027 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002028 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2029 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002030 void VisitOMPTargetTeamsDistributeSimdDirective(
2031 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002032
Guy Benyei11169dd2012-12-18 14:30:41 +00002033private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002034 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002035 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002036 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2037 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002038 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2039 void AddStmt(const Stmt *S);
2040 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002041 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002042 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002043 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002044};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002045} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002046
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002047void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002048 // 'S' should always be non-null, since it comes from the
2049 // statement we are visiting.
2050 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2051}
2052
2053void
2054EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2055 if (Qualifier)
2056 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2057}
2058
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002059void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002060 if (S)
2061 WL.push_back(StmtVisit(S, Parent));
2062}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002063void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002064 if (D)
2065 WL.push_back(DeclVisit(D, Parent, isFirst));
2066}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002067void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2068 unsigned NumTemplateArgs) {
2069 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002070}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002071void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 if (D)
2073 WL.push_back(MemberRefVisit(D, L, Parent));
2074}
2075void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2076 if (TI)
2077 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2078 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002079void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002081 for (const Stmt *SubStmt : S->children()) {
2082 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002083 }
2084 if (size == WL.size())
2085 return;
2086 // Now reverse the entries we just added. This will match the DFS
2087 // ordering performed by the worklist.
2088 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2089 std::reverse(I, E);
2090}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002091namespace {
2092class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2093 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002094 /// \brief Process clauses with list of variables.
2095 template <typename T>
2096 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002097public:
2098 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2099#define OPENMP_CLAUSE(Name, Class) \
2100 void Visit##Class(const Class *C);
2101#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002102 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002103 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002104};
2105
Alexey Bataev3392d762016-02-16 11:18:12 +00002106void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2107 const OMPClauseWithPreInit *C) {
2108 Visitor->AddStmt(C->getPreInitStmt());
2109}
2110
Alexey Bataev005248a2016-02-25 05:25:57 +00002111void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2112 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002113 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002114 Visitor->AddStmt(C->getPostUpdateExpr());
2115}
2116
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002117void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002118 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002119 Visitor->AddStmt(C->getCondition());
2120}
2121
Alexey Bataev3778b602014-07-17 07:32:53 +00002122void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2123 Visitor->AddStmt(C->getCondition());
2124}
2125
Alexey Bataev568a8332014-03-06 06:15:19 +00002126void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002127 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002128 Visitor->AddStmt(C->getNumThreads());
2129}
2130
Alexey Bataev62c87d22014-03-21 04:51:18 +00002131void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2132 Visitor->AddStmt(C->getSafelen());
2133}
2134
Alexey Bataev66b15b52015-08-21 11:14:16 +00002135void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2136 Visitor->AddStmt(C->getSimdlen());
2137}
2138
Alexander Musman8bd31e62014-05-27 15:12:19 +00002139void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2140 Visitor->AddStmt(C->getNumForLoops());
2141}
2142
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002143void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002144
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002145void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2146
Alexey Bataev56dafe82014-06-20 07:16:17 +00002147void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002148 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002149 Visitor->AddStmt(C->getChunkSize());
2150}
2151
Alexey Bataev10e775f2015-07-30 11:36:16 +00002152void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2153 Visitor->AddStmt(C->getNumForLoops());
2154}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002155
Alexey Bataev236070f2014-06-20 11:19:47 +00002156void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2157
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002158void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2159
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002160void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2161
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002162void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2163
Alexey Bataevdea47612014-07-23 07:46:59 +00002164void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2165
Alexey Bataev67a4f222014-07-23 10:25:33 +00002166void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2167
Alexey Bataev459dec02014-07-24 06:46:57 +00002168void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2169
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002170void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2171
Alexey Bataev346265e2015-09-25 10:37:12 +00002172void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2173
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002174void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2175
Alexey Bataevb825de12015-12-07 10:51:44 +00002176void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2177
Michael Wonge710d542015-08-07 16:16:36 +00002178void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2179 Visitor->AddStmt(C->getDevice());
2180}
2181
Kelvin Li099bb8c2015-11-24 20:50:12 +00002182void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002183 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002184 Visitor->AddStmt(C->getNumTeams());
2185}
2186
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002187void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002188 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002189 Visitor->AddStmt(C->getThreadLimit());
2190}
2191
Alexey Bataeva0569352015-12-01 10:17:31 +00002192void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2193 Visitor->AddStmt(C->getPriority());
2194}
2195
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002196void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2197 Visitor->AddStmt(C->getGrainsize());
2198}
2199
Alexey Bataev382967a2015-12-08 12:06:20 +00002200void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2201 Visitor->AddStmt(C->getNumTasks());
2202}
2203
Alexey Bataev28c75412015-12-15 08:19:24 +00002204void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2205 Visitor->AddStmt(C->getHint());
2206}
2207
Alexey Bataev756c1962013-09-24 03:17:45 +00002208template<typename T>
2209void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002210 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002211 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002212 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002213}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002214
2215void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002216 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002217 for (const auto *E : C->private_copies()) {
2218 Visitor->AddStmt(E);
2219 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002220}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002221void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2222 const OMPFirstprivateClause *C) {
2223 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002224 VisitOMPClauseWithPreInit(C);
2225 for (const auto *E : C->private_copies()) {
2226 Visitor->AddStmt(E);
2227 }
2228 for (const auto *E : C->inits()) {
2229 Visitor->AddStmt(E);
2230 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002231}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002232void OMPClauseEnqueue::VisitOMPLastprivateClause(
2233 const OMPLastprivateClause *C) {
2234 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002235 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002236 for (auto *E : C->private_copies()) {
2237 Visitor->AddStmt(E);
2238 }
2239 for (auto *E : C->source_exprs()) {
2240 Visitor->AddStmt(E);
2241 }
2242 for (auto *E : C->destination_exprs()) {
2243 Visitor->AddStmt(E);
2244 }
2245 for (auto *E : C->assignment_ops()) {
2246 Visitor->AddStmt(E);
2247 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002248}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002249void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002250 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002251}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002252void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2253 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002254 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002255 for (auto *E : C->privates()) {
2256 Visitor->AddStmt(E);
2257 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002258 for (auto *E : C->lhs_exprs()) {
2259 Visitor->AddStmt(E);
2260 }
2261 for (auto *E : C->rhs_exprs()) {
2262 Visitor->AddStmt(E);
2263 }
2264 for (auto *E : C->reduction_ops()) {
2265 Visitor->AddStmt(E);
2266 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002267}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002268void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2269 const OMPTaskReductionClause *C) {
2270 VisitOMPClauseList(C);
2271 VisitOMPClauseWithPostUpdate(C);
2272 for (auto *E : C->privates()) {
2273 Visitor->AddStmt(E);
2274 }
2275 for (auto *E : C->lhs_exprs()) {
2276 Visitor->AddStmt(E);
2277 }
2278 for (auto *E : C->rhs_exprs()) {
2279 Visitor->AddStmt(E);
2280 }
2281 for (auto *E : C->reduction_ops()) {
2282 Visitor->AddStmt(E);
2283 }
2284}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002285void OMPClauseEnqueue::VisitOMPInReductionClause(
2286 const OMPInReductionClause *C) {
2287 VisitOMPClauseList(C);
2288 VisitOMPClauseWithPostUpdate(C);
2289 for (auto *E : C->privates()) {
2290 Visitor->AddStmt(E);
2291 }
2292 for (auto *E : C->lhs_exprs()) {
2293 Visitor->AddStmt(E);
2294 }
2295 for (auto *E : C->rhs_exprs()) {
2296 Visitor->AddStmt(E);
2297 }
2298 for (auto *E : C->reduction_ops()) {
2299 Visitor->AddStmt(E);
2300 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002301 for (auto *E : C->taskgroup_descriptors())
2302 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002303}
Alexander Musman8dba6642014-04-22 13:09:42 +00002304void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2305 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002306 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002307 for (const auto *E : C->privates()) {
2308 Visitor->AddStmt(E);
2309 }
Alexander Musman3276a272015-03-21 10:12:56 +00002310 for (const auto *E : C->inits()) {
2311 Visitor->AddStmt(E);
2312 }
2313 for (const auto *E : C->updates()) {
2314 Visitor->AddStmt(E);
2315 }
2316 for (const auto *E : C->finals()) {
2317 Visitor->AddStmt(E);
2318 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002319 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002320 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002321}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002322void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2323 VisitOMPClauseList(C);
2324 Visitor->AddStmt(C->getAlignment());
2325}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002326void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2327 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002328 for (auto *E : C->source_exprs()) {
2329 Visitor->AddStmt(E);
2330 }
2331 for (auto *E : C->destination_exprs()) {
2332 Visitor->AddStmt(E);
2333 }
2334 for (auto *E : C->assignment_ops()) {
2335 Visitor->AddStmt(E);
2336 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002337}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002338void
2339OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2340 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002341 for (auto *E : C->source_exprs()) {
2342 Visitor->AddStmt(E);
2343 }
2344 for (auto *E : C->destination_exprs()) {
2345 Visitor->AddStmt(E);
2346 }
2347 for (auto *E : C->assignment_ops()) {
2348 Visitor->AddStmt(E);
2349 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002350}
Alexey Bataev6125da92014-07-21 11:26:11 +00002351void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2352 VisitOMPClauseList(C);
2353}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002354void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2355 VisitOMPClauseList(C);
2356}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002357void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2358 VisitOMPClauseList(C);
2359}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002360void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2361 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002362 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002363 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002364}
Alexey Bataev3392d762016-02-16 11:18:12 +00002365void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2366 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002367void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2368 VisitOMPClauseList(C);
2369}
Samuel Antaoec172c62016-05-26 17:49:04 +00002370void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2371 VisitOMPClauseList(C);
2372}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002373void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2374 VisitOMPClauseList(C);
2375}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002376void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2377 VisitOMPClauseList(C);
2378}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002379}
Alexey Bataev756c1962013-09-24 03:17:45 +00002380
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002381void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2382 unsigned size = WL.size();
2383 OMPClauseEnqueue Visitor(this);
2384 Visitor.Visit(S);
2385 if (size == WL.size())
2386 return;
2387 // Now reverse the entries we just added. This will match the DFS
2388 // ordering performed by the worklist.
2389 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2390 std::reverse(I, E);
2391}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002392void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2394}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002395void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 AddDecl(B->getBlockDecl());
2397}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002398void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 EnqueueChildren(E);
2400 AddTypeLoc(E->getTypeSourceInfo());
2401}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002402void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002403 for (auto &I : llvm::reverse(S->body()))
2404 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002405}
2406void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002407VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 AddStmt(S->getSubStmt());
2409 AddDeclarationNameInfo(S);
2410 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2411 AddNestedNameSpecifierLoc(QualifierLoc);
2412}
2413
2414void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002415VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002416 if (E->hasExplicitTemplateArgs())
2417 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 AddDeclarationNameInfo(E);
2419 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2420 AddNestedNameSpecifierLoc(QualifierLoc);
2421 if (!E->isImplicitAccess())
2422 AddStmt(E->getBase());
2423}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002424void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 // Enqueue the initializer , if any.
2426 AddStmt(E->getInitializer());
2427 // Enqueue the array size, if any.
2428 AddStmt(E->getArraySize());
2429 // Enqueue the allocated type.
2430 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2431 // Enqueue the placement arguments.
2432 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2433 AddStmt(E->getPlacementArg(I-1));
2434}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002435void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2437 AddStmt(CE->getArg(I-1));
2438 AddStmt(CE->getCallee());
2439 AddStmt(CE->getArg(0));
2440}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002441void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2442 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 // Visit the name of the type being destroyed.
2444 AddTypeLoc(E->getDestroyedTypeInfo());
2445 // Visit the scope type that looks disturbingly like the nested-name-specifier
2446 // but isn't.
2447 AddTypeLoc(E->getScopeTypeInfo());
2448 // Visit the nested-name-specifier.
2449 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2450 AddNestedNameSpecifierLoc(QualifierLoc);
2451 // Visit base expression.
2452 AddStmt(E->getBase());
2453}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002454void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2455 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 AddTypeLoc(E->getTypeSourceInfo());
2457}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002458void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2459 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 EnqueueChildren(E);
2461 AddTypeLoc(E->getTypeSourceInfo());
2462}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002463void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 EnqueueChildren(E);
2465 if (E->isTypeOperand())
2466 AddTypeLoc(E->getTypeOperandSourceInfo());
2467}
2468
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002469void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2470 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 EnqueueChildren(E);
2472 AddTypeLoc(E->getTypeSourceInfo());
2473}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002474void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 EnqueueChildren(E);
2476 if (E->isTypeOperand())
2477 AddTypeLoc(E->getTypeOperandSourceInfo());
2478}
2479
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002480void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 EnqueueChildren(S);
2482 AddDecl(S->getExceptionDecl());
2483}
2484
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002485void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002486 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002487 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002488 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002489}
2490
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002491void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002492 if (DR->hasExplicitTemplateArgs())
2493 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 WL.push_back(DeclRefExprParts(DR, Parent));
2495}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002496void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2497 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002498 if (E->hasExplicitTemplateArgs())
2499 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 AddDeclarationNameInfo(E);
2501 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2502}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002503void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 unsigned size = WL.size();
2505 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002506 for (const auto *D : S->decls()) {
2507 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 isFirst = false;
2509 }
2510 if (size == WL.size())
2511 return;
2512 // Now reverse the entries we just added. This will match the DFS
2513 // ordering performed by the worklist.
2514 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2515 std::reverse(I, E);
2516}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002517void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002519 for (const DesignatedInitExpr::Designator &D :
2520 llvm::reverse(E->designators())) {
2521 if (D.isFieldDesignator()) {
2522 if (FieldDecl *Field = D.getField())
2523 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 continue;
2525 }
David Majnemerf7e36092016-06-23 00:15:04 +00002526 if (D.isArrayDesignator()) {
2527 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 continue;
2529 }
David Majnemerf7e36092016-06-23 00:15:04 +00002530 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2531 AddStmt(E->getArrayRangeEnd(D));
2532 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 }
2534}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002535void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 EnqueueChildren(E);
2537 AddTypeLoc(E->getTypeInfoAsWritten());
2538}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002539void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 AddStmt(FS->getBody());
2541 AddStmt(FS->getInc());
2542 AddStmt(FS->getCond());
2543 AddDecl(FS->getConditionVariable());
2544 AddStmt(FS->getInit());
2545}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002546void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2548}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002549void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 AddStmt(If->getElse());
2551 AddStmt(If->getThen());
2552 AddStmt(If->getCond());
2553 AddDecl(If->getConditionVariable());
2554}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002555void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 // We care about the syntactic form of the initializer list, only.
2557 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2558 IE = Syntactic;
2559 EnqueueChildren(IE);
2560}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002561void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 WL.push_back(MemberExprParts(M, Parent));
2563
2564 // If the base of the member access expression is an implicit 'this', don't
2565 // visit it.
2566 // FIXME: If we ever want to show these implicit accesses, this will be
2567 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002568 if (M->isImplicitAccess())
2569 return;
2570
2571 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2572 // real field that that we are interested in.
2573 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2574 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2575 if (FD->isAnonymousStructOrUnion()) {
2576 AddStmt(SubME->getBase());
2577 return;
2578 }
2579 }
2580 }
2581
2582 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002583}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002584void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 AddTypeLoc(E->getEncodedTypeSourceInfo());
2586}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002587void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 EnqueueChildren(M);
2589 AddTypeLoc(M->getClassReceiverTypeInfo());
2590}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002591void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 // Visit the components of the offsetof expression.
2593 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 const OffsetOfNode &Node = E->getComponent(I-1);
2595 switch (Node.getKind()) {
2596 case OffsetOfNode::Array:
2597 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2598 break;
2599 case OffsetOfNode::Field:
2600 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2601 break;
2602 case OffsetOfNode::Identifier:
2603 case OffsetOfNode::Base:
2604 continue;
2605 }
2606 }
2607 // Visit the type into which we're computing the offset.
2608 AddTypeLoc(E->getTypeSourceInfo());
2609}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002610void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002611 if (E->hasExplicitTemplateArgs())
2612 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 WL.push_back(OverloadExprParts(E, Parent));
2614}
2615void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002616 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 EnqueueChildren(E);
2618 if (E->isArgumentType())
2619 AddTypeLoc(E->getArgumentTypeInfo());
2620}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002621void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 EnqueueChildren(S);
2623}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002624void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 AddStmt(S->getBody());
2626 AddStmt(S->getCond());
2627 AddDecl(S->getConditionVariable());
2628}
2629
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002630void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 AddStmt(W->getBody());
2632 AddStmt(W->getCond());
2633 AddDecl(W->getConditionVariable());
2634}
2635
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002636void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 for (unsigned I = E->getNumArgs(); I > 0; --I)
2638 AddTypeLoc(E->getArg(I-1));
2639}
2640
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002641void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 AddTypeLoc(E->getQueriedTypeSourceInfo());
2643}
2644
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002645void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 EnqueueChildren(E);
2647}
2648
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002649void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 VisitOverloadExpr(U);
2651 if (!U->isImplicitAccess())
2652 AddStmt(U->getBase());
2653}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002654void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 AddStmt(E->getSubExpr());
2656 AddTypeLoc(E->getWrittenTypeInfo());
2657}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002658void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 WL.push_back(SizeOfPackExprParts(E, Parent));
2660}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002661void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 // If the opaque value has a source expression, just transparently
2663 // visit that. This is useful for (e.g.) pseudo-object expressions.
2664 if (Expr *SourceExpr = E->getSourceExpr())
2665 return Visit(SourceExpr);
2666}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002667void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 AddStmt(E->getBody());
2669 WL.push_back(LambdaExprParts(E, Parent));
2670}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002671void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 // Treat the expression like its syntactic form.
2673 Visit(E->getSyntacticForm());
2674}
2675
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002676void EnqueueVisitor::VisitOMPExecutableDirective(
2677 const OMPExecutableDirective *D) {
2678 EnqueueChildren(D);
2679 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2680 E = D->clauses().end();
2681 I != E; ++I)
2682 EnqueueChildren(*I);
2683}
2684
Alexander Musman3aaab662014-08-19 11:27:13 +00002685void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2686 VisitOMPExecutableDirective(D);
2687}
2688
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002689void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2690 VisitOMPExecutableDirective(D);
2691}
2692
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002693void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002694 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002695}
2696
Alexey Bataevf29276e2014-06-18 04:14:57 +00002697void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002698 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002699}
2700
Alexander Musmanf82886e2014-09-18 05:12:34 +00002701void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2702 VisitOMPLoopDirective(D);
2703}
2704
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002705void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2706 VisitOMPExecutableDirective(D);
2707}
2708
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002709void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2710 VisitOMPExecutableDirective(D);
2711}
2712
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002713void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2714 VisitOMPExecutableDirective(D);
2715}
2716
Alexander Musman80c22892014-07-17 08:54:58 +00002717void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2718 VisitOMPExecutableDirective(D);
2719}
2720
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002721void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2722 VisitOMPExecutableDirective(D);
2723 AddDeclarationNameInfo(D);
2724}
2725
Alexey Bataev4acb8592014-07-07 13:01:15 +00002726void
2727EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002728 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002729}
2730
Alexander Musmane4e893b2014-09-23 09:33:00 +00002731void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2732 const OMPParallelForSimdDirective *D) {
2733 VisitOMPLoopDirective(D);
2734}
2735
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002736void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2737 const OMPParallelSectionsDirective *D) {
2738 VisitOMPExecutableDirective(D);
2739}
2740
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002741void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2742 VisitOMPExecutableDirective(D);
2743}
2744
Alexey Bataev68446b72014-07-18 07:47:19 +00002745void
2746EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2747 VisitOMPExecutableDirective(D);
2748}
2749
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002750void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2751 VisitOMPExecutableDirective(D);
2752}
2753
Alexey Bataev2df347a2014-07-18 10:17:07 +00002754void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2755 VisitOMPExecutableDirective(D);
2756}
2757
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002758void EnqueueVisitor::VisitOMPTaskgroupDirective(
2759 const OMPTaskgroupDirective *D) {
2760 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002761 if (const Expr *E = D->getReductionRef())
2762 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002763}
2764
Alexey Bataev6125da92014-07-21 11:26:11 +00002765void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2766 VisitOMPExecutableDirective(D);
2767}
2768
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002769void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2770 VisitOMPExecutableDirective(D);
2771}
2772
Alexey Bataev0162e452014-07-22 10:10:35 +00002773void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2774 VisitOMPExecutableDirective(D);
2775}
2776
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002777void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2778 VisitOMPExecutableDirective(D);
2779}
2780
Michael Wong65f367f2015-07-21 13:44:28 +00002781void EnqueueVisitor::VisitOMPTargetDataDirective(const
2782 OMPTargetDataDirective *D) {
2783 VisitOMPExecutableDirective(D);
2784}
2785
Samuel Antaodf67fc42016-01-19 19:15:56 +00002786void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2787 const OMPTargetEnterDataDirective *D) {
2788 VisitOMPExecutableDirective(D);
2789}
2790
Samuel Antao72590762016-01-19 20:04:50 +00002791void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2792 const OMPTargetExitDataDirective *D) {
2793 VisitOMPExecutableDirective(D);
2794}
2795
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002796void EnqueueVisitor::VisitOMPTargetParallelDirective(
2797 const OMPTargetParallelDirective *D) {
2798 VisitOMPExecutableDirective(D);
2799}
2800
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002801void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2802 const OMPTargetParallelForDirective *D) {
2803 VisitOMPLoopDirective(D);
2804}
2805
Alexey Bataev13314bf2014-10-09 04:18:56 +00002806void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2807 VisitOMPExecutableDirective(D);
2808}
2809
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002810void EnqueueVisitor::VisitOMPCancellationPointDirective(
2811 const OMPCancellationPointDirective *D) {
2812 VisitOMPExecutableDirective(D);
2813}
2814
Alexey Bataev80909872015-07-02 11:25:17 +00002815void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2816 VisitOMPExecutableDirective(D);
2817}
2818
Alexey Bataev49f6e782015-12-01 04:18:41 +00002819void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2820 VisitOMPLoopDirective(D);
2821}
2822
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002823void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2824 const OMPTaskLoopSimdDirective *D) {
2825 VisitOMPLoopDirective(D);
2826}
2827
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002828void EnqueueVisitor::VisitOMPDistributeDirective(
2829 const OMPDistributeDirective *D) {
2830 VisitOMPLoopDirective(D);
2831}
2832
Carlo Bertolli9925f152016-06-27 14:55:37 +00002833void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2834 const OMPDistributeParallelForDirective *D) {
2835 VisitOMPLoopDirective(D);
2836}
2837
Kelvin Li4a39add2016-07-05 05:00:15 +00002838void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2839 const OMPDistributeParallelForSimdDirective *D) {
2840 VisitOMPLoopDirective(D);
2841}
2842
Kelvin Li787f3fc2016-07-06 04:45:38 +00002843void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2844 const OMPDistributeSimdDirective *D) {
2845 VisitOMPLoopDirective(D);
2846}
2847
Kelvin Lia579b912016-07-14 02:54:56 +00002848void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2849 const OMPTargetParallelForSimdDirective *D) {
2850 VisitOMPLoopDirective(D);
2851}
2852
Kelvin Li986330c2016-07-20 22:57:10 +00002853void EnqueueVisitor::VisitOMPTargetSimdDirective(
2854 const OMPTargetSimdDirective *D) {
2855 VisitOMPLoopDirective(D);
2856}
2857
Kelvin Li02532872016-08-05 14:37:37 +00002858void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2859 const OMPTeamsDistributeDirective *D) {
2860 VisitOMPLoopDirective(D);
2861}
2862
Kelvin Li4e325f72016-10-25 12:50:55 +00002863void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2864 const OMPTeamsDistributeSimdDirective *D) {
2865 VisitOMPLoopDirective(D);
2866}
2867
Kelvin Li579e41c2016-11-30 23:51:03 +00002868void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2869 const OMPTeamsDistributeParallelForSimdDirective *D) {
2870 VisitOMPLoopDirective(D);
2871}
2872
Kelvin Li7ade93f2016-12-09 03:24:30 +00002873void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2874 const OMPTeamsDistributeParallelForDirective *D) {
2875 VisitOMPLoopDirective(D);
2876}
2877
Kelvin Libf594a52016-12-17 05:48:59 +00002878void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2879 const OMPTargetTeamsDirective *D) {
2880 VisitOMPExecutableDirective(D);
2881}
2882
Kelvin Li83c451e2016-12-25 04:52:54 +00002883void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2884 const OMPTargetTeamsDistributeDirective *D) {
2885 VisitOMPLoopDirective(D);
2886}
2887
Kelvin Li80e8f562016-12-29 22:16:30 +00002888void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2889 const OMPTargetTeamsDistributeParallelForDirective *D) {
2890 VisitOMPLoopDirective(D);
2891}
2892
Kelvin Li1851df52017-01-03 05:23:48 +00002893void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2894 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2895 VisitOMPLoopDirective(D);
2896}
2897
Kelvin Lida681182017-01-10 18:08:18 +00002898void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2899 const OMPTargetTeamsDistributeSimdDirective *D) {
2900 VisitOMPLoopDirective(D);
2901}
2902
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002903void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2905}
2906
2907bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2908 if (RegionOfInterest.isValid()) {
2909 SourceRange Range = getRawCursorExtent(C);
2910 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2911 return false;
2912 }
2913 return true;
2914}
2915
2916bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2917 while (!WL.empty()) {
2918 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002919 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002920
2921 // Set the Parent field, then back to its old value once we're done.
2922 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2923
2924 switch (LI.getKind()) {
2925 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002926 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 if (!D)
2928 continue;
2929
2930 // For now, perform default visitation for Decls.
2931 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2932 cast<DeclVisit>(&LI)->isFirst())))
2933 return true;
2934
2935 continue;
2936 }
2937 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002938 for (const TemplateArgumentLoc &Arg :
2939 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2940 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 return true;
2942 }
2943 continue;
2944 }
2945 case VisitorJob::TypeLocVisitKind: {
2946 // Perform default visitation for TypeLocs.
2947 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2948 return true;
2949 continue;
2950 }
2951 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002952 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 if (LabelStmt *stmt = LS->getStmt()) {
2954 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2955 TU))) {
2956 return true;
2957 }
2958 }
2959 continue;
2960 }
2961
2962 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2963 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2964 if (VisitNestedNameSpecifierLoc(V->get()))
2965 return true;
2966 continue;
2967 }
2968
2969 case VisitorJob::DeclarationNameInfoVisitKind: {
2970 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2971 ->get()))
2972 return true;
2973 continue;
2974 }
2975 case VisitorJob::MemberRefVisitKind: {
2976 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2977 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2978 return true;
2979 continue;
2980 }
2981 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002982 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 if (!S)
2984 continue;
2985
2986 // Update the current cursor.
2987 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2988 if (!IsInRegionOfInterest(Cursor))
2989 continue;
2990 switch (Visitor(Cursor, Parent, ClientData)) {
2991 case CXChildVisit_Break: return true;
2992 case CXChildVisit_Continue: break;
2993 case CXChildVisit_Recurse:
2994 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00002995 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 EnqueueWorkList(WL, S);
2997 break;
2998 }
2999 continue;
3000 }
3001 case VisitorJob::MemberExprPartsKind: {
3002 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003003 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003004
3005 // Visit the nested-name-specifier
3006 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3007 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3008 return true;
3009
3010 // Visit the declaration name.
3011 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3012 return true;
3013
3014 // Visit the explicitly-specified template arguments, if any.
3015 if (M->hasExplicitTemplateArgs()) {
3016 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3017 *ArgEnd = Arg + M->getNumTemplateArgs();
3018 Arg != ArgEnd; ++Arg) {
3019 if (VisitTemplateArgumentLoc(*Arg))
3020 return true;
3021 }
3022 }
3023 continue;
3024 }
3025 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003026 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 // Visit nested-name-specifier, if present.
3028 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3029 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3030 return true;
3031 // Visit declaration name.
3032 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3033 return true;
3034 continue;
3035 }
3036 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003037 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 // Visit the nested-name-specifier.
3039 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3040 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3041 return true;
3042 // Visit the declaration name.
3043 if (VisitDeclarationNameInfo(O->getNameInfo()))
3044 return true;
3045 // Visit the overloaded declaration reference.
3046 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3047 return true;
3048 continue;
3049 }
3050 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003051 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 NamedDecl *Pack = E->getPack();
3053 if (isa<TemplateTypeParmDecl>(Pack)) {
3054 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3055 E->getPackLoc(), TU)))
3056 return true;
3057
3058 continue;
3059 }
3060
3061 if (isa<TemplateTemplateParmDecl>(Pack)) {
3062 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3063 E->getPackLoc(), TU)))
3064 return true;
3065
3066 continue;
3067 }
3068
3069 // Non-type template parameter packs and function parameter packs are
3070 // treated like DeclRefExpr cursors.
3071 continue;
3072 }
3073
3074 case VisitorJob::LambdaExprPartsKind: {
3075 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003076 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3078 CEnd = E->explicit_capture_end();
3079 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003080 // FIXME: Lambda init-captures.
3081 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003083
Guy Benyei11169dd2012-12-18 14:30:41 +00003084 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3085 C->getLocation(),
3086 TU)))
3087 return true;
3088 }
3089
3090 // Visit parameters and return type, if present.
3091 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3092 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3093 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3094 // Visit the whole type.
3095 if (Visit(TL))
3096 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003097 } else if (FunctionProtoTypeLoc Proto =
3098 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 if (E->hasExplicitParameters()) {
3100 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003101 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3102 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 return true;
3104 } else {
3105 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003106 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 return true;
3108 }
3109 }
3110 }
3111 break;
3112 }
3113
3114 case VisitorJob::PostChildrenVisitKind:
3115 if (PostChildrenVisitor(Parent, ClientData))
3116 return true;
3117 break;
3118 }
3119 }
3120 return false;
3121}
3122
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003123bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003124 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 if (!WorkListFreeList.empty()) {
3126 WL = WorkListFreeList.back();
3127 WL->clear();
3128 WorkListFreeList.pop_back();
3129 }
3130 else {
3131 WL = new VisitorWorkList();
3132 WorkListCache.push_back(WL);
3133 }
3134 EnqueueWorkList(*WL, S);
3135 bool result = RunVisitorWorkList(*WL);
3136 WorkListFreeList.push_back(WL);
3137 return result;
3138}
3139
3140namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003141typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003142RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3143 const DeclarationNameInfo &NI, SourceRange QLoc,
3144 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3146 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3147 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3148
3149 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3150
3151 RefNamePieces Pieces;
3152
3153 if (WantQualifier && QLoc.isValid())
3154 Pieces.push_back(QLoc);
3155
3156 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3157 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003158
3159 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3160 Pieces.push_back(*TemplateArgsLoc);
3161
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 if (Kind == DeclarationName::CXXOperatorName) {
3163 Pieces.push_back(SourceLocation::getFromRawEncoding(
3164 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3165 Pieces.push_back(SourceLocation::getFromRawEncoding(
3166 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3167 }
3168
3169 if (WantSinglePiece) {
3170 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3171 Pieces.clear();
3172 Pieces.push_back(R);
3173 }
3174
3175 return Pieces;
3176}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003177}
Guy Benyei11169dd2012-12-18 14:30:41 +00003178
3179//===----------------------------------------------------------------------===//
3180// Misc. API hooks.
3181//===----------------------------------------------------------------------===//
3182
Chad Rosier05c71aa2013-03-27 18:28:23 +00003183static void fatal_error_handler(void *user_data, const std::string& reason,
3184 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003185 // Write the result out to stderr avoiding errs() because raw_ostreams can
3186 // call report_fatal_error.
3187 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3188 ::abort();
3189}
3190
Chandler Carruth66660742014-06-27 16:37:27 +00003191namespace {
3192struct RegisterFatalErrorHandler {
3193 RegisterFatalErrorHandler() {
3194 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3195 }
3196};
3197}
3198
3199static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3200
Guy Benyei11169dd2012-12-18 14:30:41 +00003201CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3202 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 // We use crash recovery to make some of our APIs more reliable, implicitly
3204 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003205 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3206 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003207
Chandler Carruth66660742014-06-27 16:37:27 +00003208 // Look through the managed static to trigger construction of the managed
3209 // static which registers our fatal error handler. This ensures it is only
3210 // registered once.
3211 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003212
Adrian Prantlbc068582015-07-08 01:00:30 +00003213 // Initialize targets for clang module support.
3214 llvm::InitializeAllTargets();
3215 llvm::InitializeAllTargetMCs();
3216 llvm::InitializeAllAsmPrinters();
3217 llvm::InitializeAllAsmParsers();
3218
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003219 CIndexer *CIdxr = new CIndexer();
3220
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 if (excludeDeclarationsFromPCH)
3222 CIdxr->setOnlyLocalDecls();
3223 if (displayDiagnostics)
3224 CIdxr->setDisplayDiagnostics();
3225
3226 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3227 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3228 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3229 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3230 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3231 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3232
3233 return CIdxr;
3234}
3235
3236void clang_disposeIndex(CXIndex CIdx) {
3237 if (CIdx)
3238 delete static_cast<CIndexer *>(CIdx);
3239}
3240
3241void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3242 if (CIdx)
3243 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3244}
3245
3246unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3247 if (CIdx)
3248 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3249 return 0;
3250}
3251
3252void clang_toggleCrashRecovery(unsigned isEnabled) {
3253 if (isEnabled)
3254 llvm::CrashRecoveryContext::Enable();
3255 else
3256 llvm::CrashRecoveryContext::Disable();
3257}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003258
Guy Benyei11169dd2012-12-18 14:30:41 +00003259CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3260 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003261 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003262 enum CXErrorCode Result =
3263 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003264 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003265 assert((TU && Result == CXError_Success) ||
3266 (!TU && Result != CXError_Success));
3267 return TU;
3268}
3269
3270enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3271 const char *ast_filename,
3272 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003273 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003274 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003275
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003276 if (!CIdx || !ast_filename || !out_TU)
3277 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003278
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003279 LOG_FUNC_SECTION {
3280 *Log << ast_filename;
3281 }
3282
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3284 FileSystemOptions FileSystemOpts;
3285
Justin Bognerd512c1e2014-10-15 00:33:06 +00003286 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3287 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003288 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003289 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3290 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003291 FileSystemOpts, /*UseDebugInfo=*/false,
3292 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003293 /*CaptureDiagnostics=*/true,
3294 /*AllowPCHWithCompilerErrors=*/true,
3295 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003296 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003297 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003298}
3299
3300unsigned clang_defaultEditingTranslationUnitOptions() {
3301 return CXTranslationUnit_PrecompiledPreamble |
3302 CXTranslationUnit_CacheCompletionResults;
3303}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003304
Guy Benyei11169dd2012-12-18 14:30:41 +00003305CXTranslationUnit
3306clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3307 const char *source_filename,
3308 int num_command_line_args,
3309 const char * const *command_line_args,
3310 unsigned num_unsaved_files,
3311 struct CXUnsavedFile *unsaved_files) {
3312 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3313 return clang_parseTranslationUnit(CIdx, source_filename,
3314 command_line_args, num_command_line_args,
3315 unsaved_files, num_unsaved_files,
3316 Options);
3317}
3318
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003319static CXErrorCode
3320clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3321 const char *const *command_line_args,
3322 int num_command_line_args,
3323 ArrayRef<CXUnsavedFile> unsaved_files,
3324 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003325 // Set up the initial return values.
3326 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003327 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003328
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003329 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003330 if (!CIdx || !out_TU)
3331 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003332
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3334
3335 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3336 setThreadBackgroundPriority();
3337
3338 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003339 bool CreatePreambleOnFirstParse =
3340 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003341 // FIXME: Add a flag for modules.
3342 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003343 = (options & (CXTranslationUnit_Incomplete |
3344 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003345 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 = options & CXTranslationUnit_CacheCompletionResults;
3347 bool IncludeBriefCommentsInCodeCompletion
3348 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3349 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003350 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003351 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3352
3353 // Configure the diagnostics.
3354 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003355 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003356
Manuel Klimek016c0242016-03-01 10:56:19 +00003357 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003358 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003359
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 // Recover resources if we crash before exiting this function.
3361 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3362 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003363 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003364
Ahmed Charlesb8984322014-03-07 20:03:18 +00003365 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3366 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003367
3368 // Recover resources if we crash before exiting this function.
3369 llvm::CrashRecoveryContextCleanupRegistrar<
3370 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3371
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003372 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003373 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003374 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003375 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 }
3377
Ahmed Charlesb8984322014-03-07 20:03:18 +00003378 std::unique_ptr<std::vector<const char *>> Args(
3379 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003380
3381 // Recover resources if we crash before exiting this method.
3382 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3383 ArgsCleanup(Args.get());
3384
3385 // Since the Clang C library is primarily used by batch tools dealing with
3386 // (often very broken) source code, where spell-checking can have a
3387 // significant negative impact on performance (particularly when
3388 // precompiled headers are involved), we disable it by default.
3389 // Only do this if we haven't found a spell-checking-related argument.
3390 bool FoundSpellCheckingArgument = false;
3391 for (int I = 0; I != num_command_line_args; ++I) {
3392 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3393 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3394 FoundSpellCheckingArgument = true;
3395 break;
3396 }
3397 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 Args->insert(Args->end(), command_line_args,
3399 command_line_args + num_command_line_args);
3400
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003401 if (!FoundSpellCheckingArgument)
3402 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3403
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 // The 'source_filename' argument is optional. If the caller does not
3405 // specify it then it is assumed that the source file is specified
3406 // in the actual argument list.
3407 // Put the source file after command_line_args otherwise if '-x' flag is
3408 // present it will be unused.
3409 if (source_filename)
3410 Args->push_back(source_filename);
3411
3412 // Do we need the detailed preprocessing record?
3413 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3414 Args->push_back("-Xclang");
3415 Args->push_back("-detailed-preprocessing-record");
3416 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003417
3418 // Suppress any editor placeholder diagnostics.
3419 Args->push_back("-fallow-editor-placeholders");
3420
Guy Benyei11169dd2012-12-18 14:30:41 +00003421 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003422 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003423 // Unless the user specified that they want the preamble on the first parse
3424 // set it up to be created on the first reparse. This makes the first parse
3425 // faster, trading for a slower (first) reparse.
3426 unsigned PrecompilePreambleAfterNParses =
3427 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003428 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003429 Args->data(), Args->data() + Args->size(),
3430 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003431 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3432 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003433 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3434 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003435 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003436 /*UserFilesAreVolatile=*/true, ForSerialization,
3437 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3438 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003439
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003440 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003441 if (!Unit && !ErrUnit)
3442 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003443
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 if (NumErrors != Diags->getClient()->getNumErrors()) {
3445 // Make sure to check that 'Unit' is non-NULL.
3446 if (CXXIdx->getDisplayDiagnostics())
3447 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3448 }
3449
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003450 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3451 return CXError_ASTReadError;
3452
David Blaikieea4395e2017-01-06 19:49:01 +00003453 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003454 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003455}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003456
3457CXTranslationUnit
3458clang_parseTranslationUnit(CXIndex CIdx,
3459 const char *source_filename,
3460 const char *const *command_line_args,
3461 int num_command_line_args,
3462 struct CXUnsavedFile *unsaved_files,
3463 unsigned num_unsaved_files,
3464 unsigned options) {
3465 CXTranslationUnit TU;
3466 enum CXErrorCode Result = clang_parseTranslationUnit2(
3467 CIdx, source_filename, command_line_args, num_command_line_args,
3468 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003469 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003470 assert((TU && Result == CXError_Success) ||
3471 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003472 return TU;
3473}
3474
3475enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003476 CXIndex CIdx, const char *source_filename,
3477 const char *const *command_line_args, int num_command_line_args,
3478 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3479 unsigned options, CXTranslationUnit *out_TU) {
3480 SmallVector<const char *, 4> Args;
3481 Args.push_back("clang");
3482 Args.append(command_line_args, command_line_args + num_command_line_args);
3483 return clang_parseTranslationUnit2FullArgv(
3484 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3485 num_unsaved_files, options, out_TU);
3486}
3487
3488enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3489 CXIndex CIdx, const char *source_filename,
3490 const char *const *command_line_args, int num_command_line_args,
3491 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3492 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003493 LOG_FUNC_SECTION {
3494 *Log << source_filename << ": ";
3495 for (int i = 0; i != num_command_line_args; ++i)
3496 *Log << command_line_args[i] << " ";
3497 }
3498
Alp Toker9d85b182014-07-07 01:23:14 +00003499 if (num_unsaved_files && !unsaved_files)
3500 return CXError_InvalidArguments;
3501
Alp Toker5c532982014-07-07 22:42:03 +00003502 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003503 auto ParseTranslationUnitImpl = [=, &result] {
3504 result = clang_parseTranslationUnit_Impl(
3505 CIdx, source_filename, command_line_args, num_command_line_args,
3506 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3507 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003508
3509 if (getenv("LIBCLANG_NOTHREADS")) {
3510 ParseTranslationUnitImpl();
3511 return result;
3512 }
3513
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 llvm::CrashRecoveryContext CRC;
3515
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003516 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3518 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3519 fprintf(stderr, " 'command_line_args' : [");
3520 for (int i = 0; i != num_command_line_args; ++i) {
3521 if (i)
3522 fprintf(stderr, ", ");
3523 fprintf(stderr, "'%s'", command_line_args[i]);
3524 }
3525 fprintf(stderr, "],\n");
3526 fprintf(stderr, " 'unsaved_files' : [");
3527 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3528 if (i)
3529 fprintf(stderr, ", ");
3530 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3531 unsaved_files[i].Length);
3532 }
3533 fprintf(stderr, "],\n");
3534 fprintf(stderr, " 'options' : %d,\n", options);
3535 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003536
3537 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003539 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003540 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003541 }
Alp Toker5c532982014-07-07 22:42:03 +00003542
3543 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003544}
3545
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003546CXString clang_Type_getObjCEncoding(CXType CT) {
3547 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3548 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3549 std::string encoding;
3550 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3551 encoding);
3552
3553 return cxstring::createDup(encoding);
3554}
3555
3556static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3557 if (C.kind == CXCursor_MacroDefinition) {
3558 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3559 return MDR->getName();
3560 } else if (C.kind == CXCursor_MacroExpansion) {
3561 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3562 return ME.getName();
3563 }
3564 return nullptr;
3565}
3566
3567unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3568 const IdentifierInfo *II = getMacroIdentifier(C);
3569 if (!II) {
3570 return false;
3571 }
3572 ASTUnit *ASTU = getCursorASTUnit(C);
3573 Preprocessor &PP = ASTU->getPreprocessor();
3574 if (const MacroInfo *MI = PP.getMacroInfo(II))
3575 return MI->isFunctionLike();
3576 return false;
3577}
3578
3579unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3580 const IdentifierInfo *II = getMacroIdentifier(C);
3581 if (!II) {
3582 return false;
3583 }
3584 ASTUnit *ASTU = getCursorASTUnit(C);
3585 Preprocessor &PP = ASTU->getPreprocessor();
3586 if (const MacroInfo *MI = PP.getMacroInfo(II))
3587 return MI->isBuiltinMacro();
3588 return false;
3589}
3590
3591unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3592 const Decl *D = getCursorDecl(C);
3593 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3594 if (!FD) {
3595 return false;
3596 }
3597 return FD->isInlined();
3598}
3599
3600static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3601 if (callExpr->getNumArgs() != 1) {
3602 return nullptr;
3603 }
3604
3605 StringLiteral *S = nullptr;
3606 auto *arg = callExpr->getArg(0);
3607 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3608 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3609 auto *subExpr = I->getSubExprAsWritten();
3610
3611 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3612 return nullptr;
3613 }
3614
3615 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3616 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3617 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3618 } else {
3619 return nullptr;
3620 }
3621 return S;
3622}
3623
David Blaikie59272572016-04-13 18:23:33 +00003624struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003625 CXEvalResultKind EvalType;
3626 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003627 unsigned long long unsignedVal;
3628 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003629 double floatVal;
3630 char *stringVal;
3631 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003632 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003633 ~ExprEvalResult() {
3634 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3635 EvalType != CXEval_Int) {
3636 delete EvalData.stringVal;
3637 }
3638 }
3639};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003640
3641void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003642 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003643}
3644
3645CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3646 if (!E) {
3647 return CXEval_UnExposed;
3648 }
3649 return ((ExprEvalResult *)E)->EvalType;
3650}
3651
3652int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003653 return clang_EvalResult_getAsLongLong(E);
3654}
3655
3656long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003657 if (!E) {
3658 return 0;
3659 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003660 ExprEvalResult *Result = (ExprEvalResult*)E;
3661 if (Result->IsUnsignedInt)
3662 return Result->EvalData.unsignedVal;
3663 return Result->EvalData.intVal;
3664}
3665
3666unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3667 return ((ExprEvalResult *)E)->IsUnsignedInt;
3668}
3669
3670unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3671 if (!E) {
3672 return 0;
3673 }
3674
3675 ExprEvalResult *Result = (ExprEvalResult*)E;
3676 if (Result->IsUnsignedInt)
3677 return Result->EvalData.unsignedVal;
3678 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003679}
3680
3681double clang_EvalResult_getAsDouble(CXEvalResult E) {
3682 if (!E) {
3683 return 0;
3684 }
3685 return ((ExprEvalResult *)E)->EvalData.floatVal;
3686}
3687
3688const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3689 if (!E) {
3690 return nullptr;
3691 }
3692 return ((ExprEvalResult *)E)->EvalData.stringVal;
3693}
3694
3695static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3696 Expr::EvalResult ER;
3697 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003698 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003699 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003700
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003701 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003702 if (!expr->EvaluateAsRValue(ER, ctx))
3703 return nullptr;
3704
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003705 QualType rettype;
3706 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003707 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003708 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003709 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003710
David Blaikiebbc00882016-04-13 18:36:19 +00003711 if (ER.Val.isInt()) {
3712 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003713
3714 auto& val = ER.Val.getInt();
3715 if (val.isUnsigned()) {
3716 result->IsUnsignedInt = true;
3717 result->EvalData.unsignedVal = val.getZExtValue();
3718 } else {
3719 result->EvalData.intVal = val.getExtValue();
3720 }
3721
David Blaikiebbc00882016-04-13 18:36:19 +00003722 return result.release();
3723 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003724
David Blaikiebbc00882016-04-13 18:36:19 +00003725 if (ER.Val.isFloat()) {
3726 llvm::SmallVector<char, 100> Buffer;
3727 ER.Val.getFloat().toString(Buffer);
3728 std::string floatStr(Buffer.data(), Buffer.size());
3729 result->EvalType = CXEval_Float;
3730 bool ignored;
3731 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003732 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003733 llvm::APFloat::rmNearestTiesToEven, &ignored);
3734 result->EvalData.floatVal = apFloat.convertToDouble();
3735 return result.release();
3736 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003737
David Blaikiebbc00882016-04-13 18:36:19 +00003738 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3739 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3740 auto *subExpr = I->getSubExprAsWritten();
3741 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3742 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003743 const StringLiteral *StrE = nullptr;
3744 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003745 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003746
3747 if (ObjCExpr) {
3748 StrE = ObjCExpr->getString();
3749 result->EvalType = CXEval_ObjCStrLiteral;
3750 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003751 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003752 result->EvalType = CXEval_StrLiteral;
3753 }
3754
3755 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003756 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003757 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3758 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003759 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003760 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003761 }
3762 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3763 expr->getStmtClass() == Stmt::StringLiteralClass) {
3764 const StringLiteral *StrE = nullptr;
3765 const ObjCStringLiteral *ObjCExpr;
3766 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003767
David Blaikiebbc00882016-04-13 18:36:19 +00003768 if (ObjCExpr) {
3769 StrE = ObjCExpr->getString();
3770 result->EvalType = CXEval_ObjCStrLiteral;
3771 } else {
3772 StrE = cast<StringLiteral>(expr);
3773 result->EvalType = CXEval_StrLiteral;
3774 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003775
David Blaikiebbc00882016-04-13 18:36:19 +00003776 std::string strRef(StrE->getString().str());
3777 result->EvalData.stringVal = new char[strRef.size() + 1];
3778 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3779 result->EvalData.stringVal[strRef.size()] = '\0';
3780 return result.release();
3781 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003782
David Blaikiebbc00882016-04-13 18:36:19 +00003783 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3784 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003785
David Blaikiebbc00882016-04-13 18:36:19 +00003786 rettype = CC->getType();
3787 if (rettype.getAsString() == "CFStringRef" &&
3788 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003789
David Blaikiebbc00882016-04-13 18:36:19 +00003790 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3791 StringLiteral *S = getCFSTR_value(callExpr);
3792 if (S) {
3793 std::string strLiteral(S->getString().str());
3794 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003795
David Blaikiebbc00882016-04-13 18:36:19 +00003796 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3797 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3798 strLiteral.size());
3799 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003800 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003801 }
3802 }
3803
David Blaikiebbc00882016-04-13 18:36:19 +00003804 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3805 callExpr = static_cast<CallExpr *>(expr);
3806 rettype = callExpr->getCallReturnType(ctx);
3807
3808 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3809 return nullptr;
3810
3811 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3812 if (callExpr->getNumArgs() == 1 &&
3813 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3814 return nullptr;
3815 } else if (rettype.getAsString() == "CFStringRef") {
3816
3817 StringLiteral *S = getCFSTR_value(callExpr);
3818 if (S) {
3819 std::string strLiteral(S->getString().str());
3820 result->EvalType = CXEval_CFStr;
3821 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3822 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3823 strLiteral.size());
3824 result->EvalData.stringVal[strLiteral.size()] = '\0';
3825 return result.release();
3826 }
3827 }
3828 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3829 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3830 ValueDecl *V = D->getDecl();
3831 if (V->getKind() == Decl::Function) {
3832 std::string strName = V->getNameAsString();
3833 result->EvalType = CXEval_Other;
3834 result->EvalData.stringVal = new char[strName.size() + 1];
3835 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3836 result->EvalData.stringVal[strName.size()] = '\0';
3837 return result.release();
3838 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003839 }
3840
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003841 return nullptr;
3842}
3843
3844CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3845 const Decl *D = getCursorDecl(C);
3846 if (D) {
3847 const Expr *expr = nullptr;
3848 if (auto *Var = dyn_cast<VarDecl>(D)) {
3849 expr = Var->getInit();
3850 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3851 expr = Field->getInClassInitializer();
3852 }
3853 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003854 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3855 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003856 return nullptr;
3857 }
3858
3859 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3860 if (compoundStmt) {
3861 Expr *expr = nullptr;
3862 for (auto *bodyIterator : compoundStmt->body()) {
3863 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3864 break;
3865 }
3866 }
3867 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003868 return const_cast<CXEvalResult>(
3869 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003870 }
3871 return nullptr;
3872}
3873
3874unsigned clang_Cursor_hasAttrs(CXCursor C) {
3875 const Decl *D = getCursorDecl(C);
3876 if (!D) {
3877 return 0;
3878 }
3879
3880 if (D->hasAttrs()) {
3881 return 1;
3882 }
3883
3884 return 0;
3885}
Guy Benyei11169dd2012-12-18 14:30:41 +00003886unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3887 return CXSaveTranslationUnit_None;
3888}
3889
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003890static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3891 const char *FileName,
3892 unsigned options) {
3893 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3895 setThreadBackgroundPriority();
3896
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003897 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3898 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003899}
3900
3901int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3902 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003903 LOG_FUNC_SECTION {
3904 *Log << TU << ' ' << FileName;
3905 }
3906
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003907 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003908 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003909 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003910 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003911
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003912 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003913 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3914 if (!CXXUnit->hasSema())
3915 return CXSaveError_InvalidTU;
3916
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003917 CXSaveError result;
3918 auto SaveTranslationUnitImpl = [=, &result]() {
3919 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3920 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003921
3922 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3923 getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003924 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003925
3926 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3927 PrintLibclangResourceUsage(TU);
3928
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003929 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 }
3931
3932 // We have an AST that has invalid nodes due to compiler errors.
3933 // Use a crash recovery thread for protection.
3934
3935 llvm::CrashRecoveryContext CRC;
3936
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003937 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003938 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3939 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3940 fprintf(stderr, " 'options' : %d,\n", options);
3941 fprintf(stderr, "}\n");
3942
3943 return CXSaveError_Unknown;
3944
3945 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3946 PrintLibclangResourceUsage(TU);
3947 }
3948
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003949 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003950}
3951
3952void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3953 if (CTUnit) {
3954 // If the translation unit has been marked as unsafe to free, just discard
3955 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003956 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3957 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003958 return;
3959
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003960 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003961 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3963 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003964 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 delete CTUnit;
3966 }
3967}
3968
Erik Verbruggen346066b2017-05-30 14:25:54 +00003969unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
3970 if (CTUnit) {
3971 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3972
3973 if (Unit && Unit->isUnsafeToFree())
3974 return false;
3975
3976 Unit->ResetForParse();
3977 return true;
3978 }
3979
3980 return false;
3981}
3982
Guy Benyei11169dd2012-12-18 14:30:41 +00003983unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3984 return CXReparse_None;
3985}
3986
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003987static CXErrorCode
3988clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3989 ArrayRef<CXUnsavedFile> unsaved_files,
3990 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003991 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003992 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003993 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003994 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003995 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003996
3997 // Reset the associated diagnostics.
3998 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00003999 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004000
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004001 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4003 setThreadBackgroundPriority();
4004
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004005 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004007
4008 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4009 new std::vector<ASTUnit::RemappedFile>());
4010
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 // Recover resources if we crash before exiting this function.
4012 llvm::CrashRecoveryContextCleanupRegistrar<
4013 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004014
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004015 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004016 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004017 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004018 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004020
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004021 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4022 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004023 return CXError_Success;
4024 if (isASTReadError(CXXUnit))
4025 return CXError_ASTReadError;
4026 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004027}
4028
4029int clang_reparseTranslationUnit(CXTranslationUnit TU,
4030 unsigned num_unsaved_files,
4031 struct CXUnsavedFile *unsaved_files,
4032 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004033 LOG_FUNC_SECTION {
4034 *Log << TU;
4035 }
4036
Alp Toker9d85b182014-07-07 01:23:14 +00004037 if (num_unsaved_files && !unsaved_files)
4038 return CXError_InvalidArguments;
4039
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004040 CXErrorCode result;
4041 auto ReparseTranslationUnitImpl = [=, &result]() {
4042 result = clang_reparseTranslationUnit_Impl(
4043 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4044 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004045
4046 if (getenv("LIBCLANG_NOTHREADS")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004047 ReparseTranslationUnitImpl();
Alp Toker5c532982014-07-07 22:42:03 +00004048 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 }
4050
4051 llvm::CrashRecoveryContext CRC;
4052
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004053 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004055 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004056 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004057 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4058 PrintLibclangResourceUsage(TU);
4059
Alp Toker5c532982014-07-07 22:42:03 +00004060 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004061}
4062
4063
4064CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004065 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004066 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004067 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004068 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004069
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004070 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004071 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004072}
4073
4074CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004075 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004076 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004077 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004078 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004079
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004080 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4082}
4083
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004084CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4085 if (isNotUsableTU(CTUnit)) {
4086 LOG_BAD_TU(CTUnit);
4087 return nullptr;
4088 }
4089
4090 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4091 impl->TranslationUnit = CTUnit;
4092 return impl;
4093}
4094
4095CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4096 if (!TargetInfo)
4097 return cxstring::createEmpty();
4098
4099 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4100 assert(!isNotUsableTU(CTUnit) &&
4101 "Unexpected unusable translation unit in TargetInfo");
4102
4103 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4104 std::string Triple =
4105 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4106 return cxstring::createDup(Triple);
4107}
4108
4109int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4110 if (!TargetInfo)
4111 return -1;
4112
4113 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4114 assert(!isNotUsableTU(CTUnit) &&
4115 "Unexpected unusable translation unit in TargetInfo");
4116
4117 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4118 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4119}
4120
4121void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4122 if (!TargetInfo)
4123 return;
4124
4125 delete TargetInfo;
4126}
4127
Guy Benyei11169dd2012-12-18 14:30:41 +00004128//===----------------------------------------------------------------------===//
4129// CXFile Operations.
4130//===----------------------------------------------------------------------===//
4131
Guy Benyei11169dd2012-12-18 14:30:41 +00004132CXString clang_getFileName(CXFile SFile) {
4133 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004134 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004135
4136 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004137 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004138}
4139
4140time_t clang_getFileTime(CXFile SFile) {
4141 if (!SFile)
4142 return 0;
4143
4144 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4145 return FEnt->getModificationTime();
4146}
4147
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004148CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004149 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004150 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004151 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004152 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004153
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004154 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004155
4156 FileManager &FMgr = CXXUnit->getFileManager();
4157 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4158}
4159
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004160unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4161 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004162 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004163 LOG_BAD_TU(TU);
4164 return 0;
4165 }
4166
4167 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004168 return 0;
4169
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004170 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 FileEntry *FEnt = static_cast<FileEntry *>(file);
4172 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4173 .isFileMultipleIncludeGuarded(FEnt);
4174}
4175
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004176int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4177 if (!file || !outID)
4178 return 1;
4179
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004180 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004181 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4182 outID->data[0] = ID.getDevice();
4183 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004184 outID->data[2] = FEnt->getModificationTime();
4185 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004186}
4187
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004188int clang_File_isEqual(CXFile file1, CXFile file2) {
4189 if (file1 == file2)
4190 return true;
4191
4192 if (!file1 || !file2)
4193 return false;
4194
4195 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4196 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4197 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4198}
4199
Guy Benyei11169dd2012-12-18 14:30:41 +00004200//===----------------------------------------------------------------------===//
4201// CXCursor Operations.
4202//===----------------------------------------------------------------------===//
4203
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004204static const Decl *getDeclFromExpr(const Stmt *E) {
4205 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004206 return getDeclFromExpr(CE->getSubExpr());
4207
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004208 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004210 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004212 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004214 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 if (PRE->isExplicitProperty())
4216 return PRE->getExplicitProperty();
4217 // It could be messaging both getter and setter as in:
4218 // ++myobj.myprop;
4219 // in which case prefer to associate the setter since it is less obvious
4220 // from inspecting the source that the setter is going to get called.
4221 if (PRE->isMessagingSetter())
4222 return PRE->getImplicitPropertySetter();
4223 return PRE->getImplicitPropertyGetter();
4224 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004225 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004226 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004227 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 if (Expr *Src = OVE->getSourceExpr())
4229 return getDeclFromExpr(Src);
4230
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004231 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004233 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 if (!CE->isElidable())
4235 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004236 if (const CXXInheritedCtorInitExpr *CE =
4237 dyn_cast<CXXInheritedCtorInitExpr>(E))
4238 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004239 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 return OME->getMethodDecl();
4241
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004242 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004244 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4246 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004247 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004248 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4249 isa<ParmVarDecl>(SizeOfPack->getPack()))
4250 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004251
4252 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004253}
4254
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004255static SourceLocation getLocationFromExpr(const Expr *E) {
4256 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 return getLocationFromExpr(CE->getSubExpr());
4258
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004259 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004261 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004263 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004265 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004267 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004269 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 return PropRef->getLocation();
4271
4272 return E->getLocStart();
4273}
4274
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004275extern "C" {
4276
Guy Benyei11169dd2012-12-18 14:30:41 +00004277unsigned clang_visitChildren(CXCursor parent,
4278 CXCursorVisitor visitor,
4279 CXClientData client_data) {
4280 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4281 /*VisitPreprocessorLast=*/false);
4282 return CursorVis.VisitChildren(parent);
4283}
4284
4285#ifndef __has_feature
4286#define __has_feature(x) 0
4287#endif
4288#if __has_feature(blocks)
4289typedef enum CXChildVisitResult
4290 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4291
4292static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4293 CXClientData client_data) {
4294 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4295 return block(cursor, parent);
4296}
4297#else
4298// If we are compiled with a compiler that doesn't have native blocks support,
4299// define and call the block manually, so the
4300typedef struct _CXChildVisitResult
4301{
4302 void *isa;
4303 int flags;
4304 int reserved;
4305 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4306 CXCursor);
4307} *CXCursorVisitorBlock;
4308
4309static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4310 CXClientData client_data) {
4311 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4312 return block->invoke(block, cursor, parent);
4313}
4314#endif
4315
4316
4317unsigned clang_visitChildrenWithBlock(CXCursor parent,
4318 CXCursorVisitorBlock block) {
4319 return clang_visitChildren(parent, visitWithBlock, block);
4320}
4321
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004322static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004324 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004325
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004326 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004328 if (const ObjCPropertyImplDecl *PropImpl =
4329 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004331 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004332
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004333 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004335 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004336
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004337 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 }
4339
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004340 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004341 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004342
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004343 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4345 // and returns different names. NamedDecl returns the class name and
4346 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004347 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004348
4349 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004350 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004351
4352 SmallString<1024> S;
4353 llvm::raw_svector_ostream os(S);
4354 ND->printName(os);
4355
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004356 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004357}
4358
4359CXString clang_getCursorSpelling(CXCursor C) {
4360 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004361 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004362
4363 if (clang_isReference(C.kind)) {
4364 switch (C.kind) {
4365 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004366 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004367 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 }
4369 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004370 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004371 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 }
4373 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004374 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004376 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 }
4378 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004379 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004380 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 }
4382 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004383 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 assert(Type && "Missing type decl");
4385
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004386 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 getAsString());
4388 }
4389 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004390 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 assert(Template && "Missing template decl");
4392
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004393 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 }
4395
4396 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004397 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 assert(NS && "Missing namespace decl");
4399
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004400 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 }
4402
4403 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004404 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 assert(Field && "Missing member decl");
4406
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004407 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004408 }
4409
4410 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004411 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 assert(Label && "Missing label");
4413
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004414 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 }
4416
4417 case CXCursor_OverloadedDeclRef: {
4418 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004419 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4420 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004421 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004422 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004424 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004425 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 OverloadedTemplateStorage *Ovl
4427 = Storage.get<OverloadedTemplateStorage*>();
4428 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004429 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004430 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 }
4432
4433 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004434 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 assert(Var && "Missing variable decl");
4436
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004437 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 }
4439
4440 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004441 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 }
4443 }
4444
4445 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004446 const Expr *E = getCursorExpr(C);
4447
4448 if (C.kind == CXCursor_ObjCStringLiteral ||
4449 C.kind == CXCursor_StringLiteral) {
4450 const StringLiteral *SLit;
4451 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4452 SLit = OSL->getString();
4453 } else {
4454 SLit = cast<StringLiteral>(E);
4455 }
4456 SmallString<256> Buf;
4457 llvm::raw_svector_ostream OS(Buf);
4458 SLit->outputString(OS);
4459 return cxstring::createDup(OS.str());
4460 }
4461
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004462 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 if (D)
4464 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004465 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 }
4467
4468 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004469 const Stmt *S = getCursorStmt(C);
4470 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004471 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004472
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004473 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 }
4475
4476 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004477 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 ->getNameStart());
4479
4480 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004481 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 ->getNameStart());
4483
4484 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004485 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004486
4487 if (clang_isDeclaration(C.kind))
4488 return getDeclSpelling(getCursorDecl(C));
4489
4490 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004491 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004492 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 }
4494
4495 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004496 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004497 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 }
4499
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004500 if (C.kind == CXCursor_PackedAttr) {
4501 return cxstring::createRef("packed");
4502 }
4503
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004504 if (C.kind == CXCursor_VisibilityAttr) {
4505 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4506 switch (AA->getVisibility()) {
4507 case VisibilityAttr::VisibilityType::Default:
4508 return cxstring::createRef("default");
4509 case VisibilityAttr::VisibilityType::Hidden:
4510 return cxstring::createRef("hidden");
4511 case VisibilityAttr::VisibilityType::Protected:
4512 return cxstring::createRef("protected");
4513 }
4514 llvm_unreachable("unknown visibility type");
4515 }
4516
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004517 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004518}
4519
4520CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4521 unsigned pieceIndex,
4522 unsigned options) {
4523 if (clang_Cursor_isNull(C))
4524 return clang_getNullRange();
4525
4526 ASTContext &Ctx = getCursorContext(C);
4527
4528 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004529 const Stmt *S = getCursorStmt(C);
4530 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 if (pieceIndex > 0)
4532 return clang_getNullRange();
4533 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4534 }
4535
4536 return clang_getNullRange();
4537 }
4538
4539 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004540 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4542 if (pieceIndex >= ME->getNumSelectorLocs())
4543 return clang_getNullRange();
4544 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4545 }
4546 }
4547
4548 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4549 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004550 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4552 if (pieceIndex >= MD->getNumSelectorLocs())
4553 return clang_getNullRange();
4554 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4555 }
4556 }
4557
4558 if (C.kind == CXCursor_ObjCCategoryDecl ||
4559 C.kind == CXCursor_ObjCCategoryImplDecl) {
4560 if (pieceIndex > 0)
4561 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004562 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4564 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004565 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4567 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4568 }
4569
4570 if (C.kind == CXCursor_ModuleImportDecl) {
4571 if (pieceIndex > 0)
4572 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004573 if (const ImportDecl *ImportD =
4574 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4576 if (!Locs.empty())
4577 return cxloc::translateSourceRange(Ctx,
4578 SourceRange(Locs.front(), Locs.back()));
4579 }
4580 return clang_getNullRange();
4581 }
4582
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004583 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004584 C.kind == CXCursor_ConversionFunction ||
4585 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004586 if (pieceIndex > 0)
4587 return clang_getNullRange();
4588 if (const FunctionDecl *FD =
4589 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4590 DeclarationNameInfo FunctionName = FD->getNameInfo();
4591 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4592 }
4593 return clang_getNullRange();
4594 }
4595
Guy Benyei11169dd2012-12-18 14:30:41 +00004596 // FIXME: A CXCursor_InclusionDirective should give the location of the
4597 // filename, but we don't keep track of this.
4598
4599 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4600 // but we don't keep track of this.
4601
4602 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4603 // but we don't keep track of this.
4604
4605 // Default handling, give the location of the cursor.
4606
4607 if (pieceIndex > 0)
4608 return clang_getNullRange();
4609
4610 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4611 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4612 return cxloc::translateSourceRange(Ctx, Loc);
4613}
4614
Eli Bendersky44a206f2014-07-31 18:04:56 +00004615CXString clang_Cursor_getMangling(CXCursor C) {
4616 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4617 return cxstring::createEmpty();
4618
Eli Bendersky44a206f2014-07-31 18:04:56 +00004619 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004620 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004621 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4622 return cxstring::createEmpty();
4623
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004624 ASTContext &Ctx = D->getASTContext();
4625 index::CodegenNameGenerator CGNameGen(Ctx);
4626 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004627}
4628
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004629CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4630 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4631 return nullptr;
4632
4633 const Decl *D = getCursorDecl(C);
4634 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4635 return nullptr;
4636
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004637 ASTContext &Ctx = D->getASTContext();
4638 index::CodegenNameGenerator CGNameGen(Ctx);
4639 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004640 return cxstring::createSet(Manglings);
4641}
4642
Dave Lee1a532c92017-09-22 16:58:57 +00004643CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4644 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4645 return nullptr;
4646
4647 const Decl *D = getCursorDecl(C);
4648 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4649 return nullptr;
4650
4651 ASTContext &Ctx = D->getASTContext();
4652 index::CodegenNameGenerator CGNameGen(Ctx);
4653 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4654 return cxstring::createSet(Manglings);
4655}
4656
Guy Benyei11169dd2012-12-18 14:30:41 +00004657CXString clang_getCursorDisplayName(CXCursor C) {
4658 if (!clang_isDeclaration(C.kind))
4659 return clang_getCursorSpelling(C);
4660
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004661 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004663 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004664
4665 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004666 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 D = FunTmpl->getTemplatedDecl();
4668
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004669 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 SmallString<64> Str;
4671 llvm::raw_svector_ostream OS(Str);
4672 OS << *Function;
4673 if (Function->getPrimaryTemplate())
4674 OS << "<>";
4675 OS << "(";
4676 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4677 if (I)
4678 OS << ", ";
4679 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4680 }
4681
4682 if (Function->isVariadic()) {
4683 if (Function->getNumParams())
4684 OS << ", ";
4685 OS << "...";
4686 }
4687 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004688 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 }
4690
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004691 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 SmallString<64> Str;
4693 llvm::raw_svector_ostream OS(Str);
4694 OS << *ClassTemplate;
4695 OS << "<";
4696 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4697 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4698 if (I)
4699 OS << ", ";
4700
4701 NamedDecl *Param = Params->getParam(I);
4702 if (Param->getIdentifier()) {
4703 OS << Param->getIdentifier()->getName();
4704 continue;
4705 }
4706
4707 // There is no parameter name, which makes this tricky. Try to come up
4708 // with something useful that isn't too long.
4709 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4710 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4711 else if (NonTypeTemplateParmDecl *NTTP
4712 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4713 OS << NTTP->getType().getAsString(Policy);
4714 else
4715 OS << "template<...> class";
4716 }
4717
4718 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004719 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 }
4721
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004722 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4724 // If the type was explicitly written, use that.
4725 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004726 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Guy Benyei11169dd2012-12-18 14:30:41 +00004727
Benjamin Kramer9170e912013-02-22 15:46:01 +00004728 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 llvm::raw_svector_ostream OS(Str);
4730 OS << *ClassSpec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004731 TemplateSpecializationType::PrintTemplateArgumentList(
4732 OS, ClassSpec->getTemplateArgs().asArray(), Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004733 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 }
4735
4736 return clang_getCursorSpelling(C);
4737}
4738
4739CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4740 switch (Kind) {
4741 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004742 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004744 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004746 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004748 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004750 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004752 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004754 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004756 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004758 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004760 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004762 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004764 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004766 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004768 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004770 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004772 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004774 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004776 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004778 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004780 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004782 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004784 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004786 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004788 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004790 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004792 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004794 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004796 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004798 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004800 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004802 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004804 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004806 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004808 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004810 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004812 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004814 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004816 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004818 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004819 case CXCursor_OMPArraySectionExpr:
4820 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004822 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004824 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004826 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004828 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004829 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004830 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004832 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004834 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004836 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004838 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004840 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004842 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004843 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004844 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004846 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004848 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004850 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004852 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004854 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004855 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004856 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004858 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004860 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004862 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004864 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004866 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004868 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004870 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004871 case CXCursor_ObjCAvailabilityCheckExpr:
4872 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004873 case CXCursor_ObjCSelfExpr:
4874 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004876 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004878 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004880 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004882 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004884 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004886 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004888 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004890 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004891 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004892 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004894 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004895 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004896 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004898 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004899 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004900 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004902 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004904 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004905 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004906 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004907 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004908 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004910 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004912 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004914 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004916 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004918 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004920 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004922 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004924 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004926 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004928 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004930 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004931 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004932 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004934 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004936 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004938 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004940 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004941 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004942 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004943 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004944 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004946 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004947 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004948 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004950 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004952 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004953 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004954 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004956 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004958 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004960 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004962 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004963 case CXCursor_SEHLeaveStmt:
4964 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004965 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004966 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004968 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004969 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004970 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004971 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004972 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004974 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004976 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004978 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004980 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004982 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004984 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004986 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004988 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004990 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004992 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004993 case CXCursor_PackedAttr:
4994 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00004995 case CXCursor_PureAttr:
4996 return cxstring::createRef("attribute(pure)");
4997 case CXCursor_ConstAttr:
4998 return cxstring::createRef("attribute(const)");
4999 case CXCursor_NoDuplicateAttr:
5000 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005001 case CXCursor_CUDAConstantAttr:
5002 return cxstring::createRef("attribute(constant)");
5003 case CXCursor_CUDADeviceAttr:
5004 return cxstring::createRef("attribute(device)");
5005 case CXCursor_CUDAGlobalAttr:
5006 return cxstring::createRef("attribute(global)");
5007 case CXCursor_CUDAHostAttr:
5008 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005009 case CXCursor_CUDASharedAttr:
5010 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005011 case CXCursor_VisibilityAttr:
5012 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005013 case CXCursor_DLLExport:
5014 return cxstring::createRef("attribute(dllexport)");
5015 case CXCursor_DLLImport:
5016 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005018 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005020 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005022 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005024 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005026 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005028 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005030 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005032 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005034 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005065 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005066 return cxstring::createRef("OMPParallelDirective");
5067 case CXCursor_OMPSimdDirective:
5068 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005069 case CXCursor_OMPForDirective:
5070 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005071 case CXCursor_OMPForSimdDirective:
5072 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005073 case CXCursor_OMPSectionsDirective:
5074 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005075 case CXCursor_OMPSectionDirective:
5076 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005077 case CXCursor_OMPSingleDirective:
5078 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005079 case CXCursor_OMPMasterDirective:
5080 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005081 case CXCursor_OMPCriticalDirective:
5082 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005083 case CXCursor_OMPParallelForDirective:
5084 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005085 case CXCursor_OMPParallelForSimdDirective:
5086 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005087 case CXCursor_OMPParallelSectionsDirective:
5088 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005089 case CXCursor_OMPTaskDirective:
5090 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005091 case CXCursor_OMPTaskyieldDirective:
5092 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005093 case CXCursor_OMPBarrierDirective:
5094 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005095 case CXCursor_OMPTaskwaitDirective:
5096 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005097 case CXCursor_OMPTaskgroupDirective:
5098 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005099 case CXCursor_OMPFlushDirective:
5100 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005101 case CXCursor_OMPOrderedDirective:
5102 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005103 case CXCursor_OMPAtomicDirective:
5104 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005105 case CXCursor_OMPTargetDirective:
5106 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005107 case CXCursor_OMPTargetDataDirective:
5108 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005109 case CXCursor_OMPTargetEnterDataDirective:
5110 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005111 case CXCursor_OMPTargetExitDataDirective:
5112 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005113 case CXCursor_OMPTargetParallelDirective:
5114 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005115 case CXCursor_OMPTargetParallelForDirective:
5116 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005117 case CXCursor_OMPTargetUpdateDirective:
5118 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005119 case CXCursor_OMPTeamsDirective:
5120 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005121 case CXCursor_OMPCancellationPointDirective:
5122 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005123 case CXCursor_OMPCancelDirective:
5124 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005125 case CXCursor_OMPTaskLoopDirective:
5126 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005127 case CXCursor_OMPTaskLoopSimdDirective:
5128 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005129 case CXCursor_OMPDistributeDirective:
5130 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005131 case CXCursor_OMPDistributeParallelForDirective:
5132 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005133 case CXCursor_OMPDistributeParallelForSimdDirective:
5134 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005135 case CXCursor_OMPDistributeSimdDirective:
5136 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005137 case CXCursor_OMPTargetParallelForSimdDirective:
5138 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005139 case CXCursor_OMPTargetSimdDirective:
5140 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005141 case CXCursor_OMPTeamsDistributeDirective:
5142 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005143 case CXCursor_OMPTeamsDistributeSimdDirective:
5144 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005145 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5146 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005147 case CXCursor_OMPTeamsDistributeParallelForDirective:
5148 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005149 case CXCursor_OMPTargetTeamsDirective:
5150 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005151 case CXCursor_OMPTargetTeamsDistributeDirective:
5152 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005153 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5154 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005155 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5156 return cxstring::createRef(
5157 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005158 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5159 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005160 case CXCursor_OverloadCandidate:
5161 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005162 case CXCursor_TypeAliasTemplateDecl:
5163 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005164 case CXCursor_StaticAssert:
5165 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005166 case CXCursor_FriendDecl:
5167 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 }
5169
5170 llvm_unreachable("Unhandled CXCursorKind");
5171}
5172
5173struct GetCursorData {
5174 SourceLocation TokenBeginLoc;
5175 bool PointsAtMacroArgExpansion;
5176 bool VisitedObjCPropertyImplDecl;
5177 SourceLocation VisitedDeclaratorDeclStartLoc;
5178 CXCursor &BestCursor;
5179
5180 GetCursorData(SourceManager &SM,
5181 SourceLocation tokenBegin, CXCursor &outputCursor)
5182 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5183 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5184 VisitedObjCPropertyImplDecl = false;
5185 }
5186};
5187
5188static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5189 CXCursor parent,
5190 CXClientData client_data) {
5191 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5192 CXCursor *BestCursor = &Data->BestCursor;
5193
5194 // If we point inside a macro argument we should provide info of what the
5195 // token is so use the actual cursor, don't replace it with a macro expansion
5196 // cursor.
5197 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5198 return CXChildVisit_Recurse;
5199
5200 if (clang_isDeclaration(cursor.kind)) {
5201 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005202 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5204 if (MD->isImplicit())
5205 return CXChildVisit_Break;
5206
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005207 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5209 // Check that when we have multiple @class references in the same line,
5210 // that later ones do not override the previous ones.
5211 // If we have:
5212 // @class Foo, Bar;
5213 // source ranges for both start at '@', so 'Bar' will end up overriding
5214 // 'Foo' even though the cursor location was at 'Foo'.
5215 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5216 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005217 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5219 if (PrevID != ID &&
5220 !PrevID->isThisDeclarationADefinition() &&
5221 !ID->isThisDeclarationADefinition())
5222 return CXChildVisit_Break;
5223 }
5224
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005225 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5227 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5228 // Check that when we have multiple declarators in the same line,
5229 // that later ones do not override the previous ones.
5230 // If we have:
5231 // int Foo, Bar;
5232 // source ranges for both start at 'int', so 'Bar' will end up overriding
5233 // 'Foo' even though the cursor location was at 'Foo'.
5234 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5235 return CXChildVisit_Break;
5236 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5237
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005238 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5240 (void)PropImp;
5241 // Check that when we have multiple @synthesize in the same line,
5242 // that later ones do not override the previous ones.
5243 // If we have:
5244 // @synthesize Foo, Bar;
5245 // source ranges for both start at '@', so 'Bar' will end up overriding
5246 // 'Foo' even though the cursor location was at 'Foo'.
5247 if (Data->VisitedObjCPropertyImplDecl)
5248 return CXChildVisit_Break;
5249 Data->VisitedObjCPropertyImplDecl = true;
5250 }
5251 }
5252
5253 if (clang_isExpression(cursor.kind) &&
5254 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005255 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 // Avoid having the cursor of an expression replace the declaration cursor
5257 // when the expression source range overlaps the declaration range.
5258 // This can happen for C++ constructor expressions whose range generally
5259 // include the variable declaration, e.g.:
5260 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5261 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5262 D->getLocation() == Data->TokenBeginLoc)
5263 return CXChildVisit_Break;
5264 }
5265 }
5266
5267 // If our current best cursor is the construction of a temporary object,
5268 // don't replace that cursor with a type reference, because we want
5269 // clang_getCursor() to point at the constructor.
5270 if (clang_isExpression(BestCursor->kind) &&
5271 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5272 cursor.kind == CXCursor_TypeRef) {
5273 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5274 // as having the actual point on the type reference.
5275 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5276 return CXChildVisit_Recurse;
5277 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005278
5279 // If we already have an Objective-C superclass reference, don't
5280 // update it further.
5281 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5282 return CXChildVisit_Break;
5283
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 *BestCursor = cursor;
5285 return CXChildVisit_Recurse;
5286}
5287
5288CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005289 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005290 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005292 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005293
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005294 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005295 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5296
5297 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5298 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5299
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005300 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005301 CXFile SearchFile;
5302 unsigned SearchLine, SearchColumn;
5303 CXFile ResultFile;
5304 unsigned ResultLine, ResultColumn;
5305 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5306 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5307 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005308
5309 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5310 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005311 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005312 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005313 SearchFileName = clang_getFileName(SearchFile);
5314 ResultFileName = clang_getFileName(ResultFile);
5315 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5316 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005317 *Log << llvm::format("(%s:%d:%d) = %s",
5318 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5319 clang_getCString(KindSpelling))
5320 << llvm::format("(%s:%d:%d):%s%s",
5321 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5322 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005323 clang_disposeString(SearchFileName);
5324 clang_disposeString(ResultFileName);
5325 clang_disposeString(KindSpelling);
5326 clang_disposeString(USR);
5327
5328 CXCursor Definition = clang_getCursorDefinition(Result);
5329 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5330 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5331 CXString DefinitionKindSpelling
5332 = clang_getCursorKindSpelling(Definition.kind);
5333 CXFile DefinitionFile;
5334 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005335 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005336 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005338 *Log << llvm::format(" -> %s(%s:%d:%d)",
5339 clang_getCString(DefinitionKindSpelling),
5340 clang_getCString(DefinitionFileName),
5341 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 clang_disposeString(DefinitionFileName);
5343 clang_disposeString(DefinitionKindSpelling);
5344 }
5345 }
5346
5347 return Result;
5348}
5349
5350CXCursor clang_getNullCursor(void) {
5351 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5352}
5353
5354unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005355 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5356 // can't set consistently. For example, when visiting a DeclStmt we will set
5357 // it but we don't set it on the result of clang_getCursorDefinition for
5358 // a reference of the same declaration.
5359 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5360 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5361 // to provide that kind of info.
5362 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005363 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005364 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005365 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005366
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 return X == Y;
5368}
5369
5370unsigned clang_hashCursor(CXCursor C) {
5371 unsigned Index = 0;
5372 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5373 Index = 1;
5374
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005375 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005376 std::make_pair(C.kind, C.data[Index]));
5377}
5378
5379unsigned clang_isInvalid(enum CXCursorKind K) {
5380 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5381}
5382
5383unsigned clang_isDeclaration(enum CXCursorKind K) {
5384 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5385 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5386}
5387
5388unsigned clang_isReference(enum CXCursorKind K) {
5389 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5390}
5391
5392unsigned clang_isExpression(enum CXCursorKind K) {
5393 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5394}
5395
5396unsigned clang_isStatement(enum CXCursorKind K) {
5397 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5398}
5399
5400unsigned clang_isAttribute(enum CXCursorKind K) {
5401 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5402}
5403
5404unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5405 return K == CXCursor_TranslationUnit;
5406}
5407
5408unsigned clang_isPreprocessing(enum CXCursorKind K) {
5409 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5410}
5411
5412unsigned clang_isUnexposed(enum CXCursorKind K) {
5413 switch (K) {
5414 case CXCursor_UnexposedDecl:
5415 case CXCursor_UnexposedExpr:
5416 case CXCursor_UnexposedStmt:
5417 case CXCursor_UnexposedAttr:
5418 return true;
5419 default:
5420 return false;
5421 }
5422}
5423
5424CXCursorKind clang_getCursorKind(CXCursor C) {
5425 return C.kind;
5426}
5427
5428CXSourceLocation clang_getCursorLocation(CXCursor C) {
5429 if (clang_isReference(C.kind)) {
5430 switch (C.kind) {
5431 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005432 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005433 = getCursorObjCSuperClassRef(C);
5434 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5435 }
5436
5437 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005438 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005439 = getCursorObjCProtocolRef(C);
5440 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5441 }
5442
5443 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005444 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005445 = getCursorObjCClassRef(C);
5446 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5447 }
5448
5449 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005450 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005451 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5452 }
5453
5454 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005455 std::pair<const TemplateDecl *, SourceLocation> P =
5456 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005457 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5458 }
5459
5460 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005461 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005462 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5463 }
5464
5465 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005466 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005467 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5468 }
5469
5470 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005471 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005472 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5473 }
5474
5475 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005476 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005477 if (!BaseSpec)
5478 return clang_getNullLocation();
5479
5480 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5481 return cxloc::translateSourceLocation(getCursorContext(C),
5482 TSInfo->getTypeLoc().getBeginLoc());
5483
5484 return cxloc::translateSourceLocation(getCursorContext(C),
5485 BaseSpec->getLocStart());
5486 }
5487
5488 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005489 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005490 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5491 }
5492
5493 case CXCursor_OverloadedDeclRef:
5494 return cxloc::translateSourceLocation(getCursorContext(C),
5495 getCursorOverloadedDeclRef(C).second);
5496
5497 default:
5498 // FIXME: Need a way to enumerate all non-reference cases.
5499 llvm_unreachable("Missed a reference kind");
5500 }
5501 }
5502
5503 if (clang_isExpression(C.kind))
5504 return cxloc::translateSourceLocation(getCursorContext(C),
5505 getLocationFromExpr(getCursorExpr(C)));
5506
5507 if (clang_isStatement(C.kind))
5508 return cxloc::translateSourceLocation(getCursorContext(C),
5509 getCursorStmt(C)->getLocStart());
5510
5511 if (C.kind == CXCursor_PreprocessingDirective) {
5512 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5513 return cxloc::translateSourceLocation(getCursorContext(C), L);
5514 }
5515
5516 if (C.kind == CXCursor_MacroExpansion) {
5517 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005518 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 return cxloc::translateSourceLocation(getCursorContext(C), L);
5520 }
5521
5522 if (C.kind == CXCursor_MacroDefinition) {
5523 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5524 return cxloc::translateSourceLocation(getCursorContext(C), L);
5525 }
5526
5527 if (C.kind == CXCursor_InclusionDirective) {
5528 SourceLocation L
5529 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5530 return cxloc::translateSourceLocation(getCursorContext(C), L);
5531 }
5532
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005533 if (clang_isAttribute(C.kind)) {
5534 SourceLocation L
5535 = cxcursor::getCursorAttr(C)->getLocation();
5536 return cxloc::translateSourceLocation(getCursorContext(C), L);
5537 }
5538
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 if (!clang_isDeclaration(C.kind))
5540 return clang_getNullLocation();
5541
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005542 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005543 if (!D)
5544 return clang_getNullLocation();
5545
5546 SourceLocation Loc = D->getLocation();
5547 // FIXME: Multiple variables declared in a single declaration
5548 // currently lack the information needed to correctly determine their
5549 // ranges when accounting for the type-specifier. We use context
5550 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5551 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005552 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005553 if (!cxcursor::isFirstInDeclGroup(C))
5554 Loc = VD->getLocation();
5555 }
5556
5557 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005558 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005559 Loc = MD->getSelectorStartLoc();
5560
5561 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5562}
5563
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005564} // end extern "C"
5565
Guy Benyei11169dd2012-12-18 14:30:41 +00005566CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5567 assert(TU);
5568
5569 // Guard against an invalid SourceLocation, or we may assert in one
5570 // of the following calls.
5571 if (SLoc.isInvalid())
5572 return clang_getNullCursor();
5573
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005574 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005575
5576 // Translate the given source location to make it point at the beginning of
5577 // the token under the cursor.
5578 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5579 CXXUnit->getASTContext().getLangOpts());
5580
5581 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5582 if (SLoc.isValid()) {
5583 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5584 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5585 /*VisitPreprocessorLast=*/true,
5586 /*VisitIncludedEntities=*/false,
5587 SourceLocation(SLoc));
5588 CursorVis.visitFileRegion();
5589 }
5590
5591 return Result;
5592}
5593
5594static SourceRange getRawCursorExtent(CXCursor C) {
5595 if (clang_isReference(C.kind)) {
5596 switch (C.kind) {
5597 case CXCursor_ObjCSuperClassRef:
5598 return getCursorObjCSuperClassRef(C).second;
5599
5600 case CXCursor_ObjCProtocolRef:
5601 return getCursorObjCProtocolRef(C).second;
5602
5603 case CXCursor_ObjCClassRef:
5604 return getCursorObjCClassRef(C).second;
5605
5606 case CXCursor_TypeRef:
5607 return getCursorTypeRef(C).second;
5608
5609 case CXCursor_TemplateRef:
5610 return getCursorTemplateRef(C).second;
5611
5612 case CXCursor_NamespaceRef:
5613 return getCursorNamespaceRef(C).second;
5614
5615 case CXCursor_MemberRef:
5616 return getCursorMemberRef(C).second;
5617
5618 case CXCursor_CXXBaseSpecifier:
5619 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5620
5621 case CXCursor_LabelRef:
5622 return getCursorLabelRef(C).second;
5623
5624 case CXCursor_OverloadedDeclRef:
5625 return getCursorOverloadedDeclRef(C).second;
5626
5627 case CXCursor_VariableRef:
5628 return getCursorVariableRef(C).second;
5629
5630 default:
5631 // FIXME: Need a way to enumerate all non-reference cases.
5632 llvm_unreachable("Missed a reference kind");
5633 }
5634 }
5635
5636 if (clang_isExpression(C.kind))
5637 return getCursorExpr(C)->getSourceRange();
5638
5639 if (clang_isStatement(C.kind))
5640 return getCursorStmt(C)->getSourceRange();
5641
5642 if (clang_isAttribute(C.kind))
5643 return getCursorAttr(C)->getRange();
5644
5645 if (C.kind == CXCursor_PreprocessingDirective)
5646 return cxcursor::getCursorPreprocessingDirective(C);
5647
5648 if (C.kind == CXCursor_MacroExpansion) {
5649 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005650 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005651 return TU->mapRangeFromPreamble(Range);
5652 }
5653
5654 if (C.kind == CXCursor_MacroDefinition) {
5655 ASTUnit *TU = getCursorASTUnit(C);
5656 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5657 return TU->mapRangeFromPreamble(Range);
5658 }
5659
5660 if (C.kind == CXCursor_InclusionDirective) {
5661 ASTUnit *TU = getCursorASTUnit(C);
5662 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5663 return TU->mapRangeFromPreamble(Range);
5664 }
5665
5666 if (C.kind == CXCursor_TranslationUnit) {
5667 ASTUnit *TU = getCursorASTUnit(C);
5668 FileID MainID = TU->getSourceManager().getMainFileID();
5669 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5670 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5671 return SourceRange(Start, End);
5672 }
5673
5674 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005675 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005676 if (!D)
5677 return SourceRange();
5678
5679 SourceRange R = D->getSourceRange();
5680 // FIXME: Multiple variables declared in a single declaration
5681 // currently lack the information needed to correctly determine their
5682 // ranges when accounting for the type-specifier. We use context
5683 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5684 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005685 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005686 if (!cxcursor::isFirstInDeclGroup(C))
5687 R.setBegin(VD->getLocation());
5688 }
5689 return R;
5690 }
5691 return SourceRange();
5692}
5693
5694/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5695/// the decl-specifier-seq for declarations.
5696static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5697 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005698 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005699 if (!D)
5700 return SourceRange();
5701
5702 SourceRange R = D->getSourceRange();
5703
5704 // Adjust the start of the location for declarations preceded by
5705 // declaration specifiers.
5706 SourceLocation StartLoc;
5707 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5708 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5709 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005710 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005711 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5712 StartLoc = TI->getTypeLoc().getLocStart();
5713 }
5714
5715 if (StartLoc.isValid() && R.getBegin().isValid() &&
5716 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5717 R.setBegin(StartLoc);
5718
5719 // FIXME: Multiple variables declared in a single declaration
5720 // currently lack the information needed to correctly determine their
5721 // ranges when accounting for the type-specifier. We use context
5722 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5723 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005724 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005725 if (!cxcursor::isFirstInDeclGroup(C))
5726 R.setBegin(VD->getLocation());
5727 }
5728
5729 return R;
5730 }
5731
5732 return getRawCursorExtent(C);
5733}
5734
Guy Benyei11169dd2012-12-18 14:30:41 +00005735CXSourceRange clang_getCursorExtent(CXCursor C) {
5736 SourceRange R = getRawCursorExtent(C);
5737 if (R.isInvalid())
5738 return clang_getNullRange();
5739
5740 return cxloc::translateSourceRange(getCursorContext(C), R);
5741}
5742
5743CXCursor clang_getCursorReferenced(CXCursor C) {
5744 if (clang_isInvalid(C.kind))
5745 return clang_getNullCursor();
5746
5747 CXTranslationUnit tu = getCursorTU(C);
5748 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005749 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005750 if (!D)
5751 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005752 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005753 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005754 if (const ObjCPropertyImplDecl *PropImpl =
5755 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005756 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5757 return MakeCXCursor(Property, tu);
5758
5759 return C;
5760 }
5761
5762 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005763 const Expr *E = getCursorExpr(C);
5764 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005765 if (D) {
5766 CXCursor declCursor = MakeCXCursor(D, tu);
5767 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5768 declCursor);
5769 return declCursor;
5770 }
5771
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005772 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005773 return MakeCursorOverloadedDeclRef(Ovl, tu);
5774
5775 return clang_getNullCursor();
5776 }
5777
5778 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005779 const Stmt *S = getCursorStmt(C);
5780 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005781 if (LabelDecl *label = Goto->getLabel())
5782 if (LabelStmt *labelS = label->getStmt())
5783 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5784
5785 return clang_getNullCursor();
5786 }
Richard Smith66a81862015-05-04 02:25:31 +00005787
Guy Benyei11169dd2012-12-18 14:30:41 +00005788 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005789 if (const MacroDefinitionRecord *Def =
5790 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005791 return MakeMacroDefinitionCursor(Def, tu);
5792 }
5793
5794 if (!clang_isReference(C.kind))
5795 return clang_getNullCursor();
5796
5797 switch (C.kind) {
5798 case CXCursor_ObjCSuperClassRef:
5799 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5800
5801 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005802 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5803 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005804 return MakeCXCursor(Def, tu);
5805
5806 return MakeCXCursor(Prot, tu);
5807 }
5808
5809 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005810 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5811 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005812 return MakeCXCursor(Def, tu);
5813
5814 return MakeCXCursor(Class, tu);
5815 }
5816
5817 case CXCursor_TypeRef:
5818 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5819
5820 case CXCursor_TemplateRef:
5821 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5822
5823 case CXCursor_NamespaceRef:
5824 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5825
5826 case CXCursor_MemberRef:
5827 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5828
5829 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005830 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5832 tu ));
5833 }
5834
5835 case CXCursor_LabelRef:
5836 // FIXME: We end up faking the "parent" declaration here because we
5837 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005838 return MakeCXCursor(getCursorLabelRef(C).first,
5839 cxtu::getASTUnit(tu)->getASTContext()
5840 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 tu);
5842
5843 case CXCursor_OverloadedDeclRef:
5844 return C;
5845
5846 case CXCursor_VariableRef:
5847 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5848
5849 default:
5850 // We would prefer to enumerate all non-reference cursor kinds here.
5851 llvm_unreachable("Unhandled reference cursor kind");
5852 }
5853}
5854
5855CXCursor clang_getCursorDefinition(CXCursor C) {
5856 if (clang_isInvalid(C.kind))
5857 return clang_getNullCursor();
5858
5859 CXTranslationUnit TU = getCursorTU(C);
5860
5861 bool WasReference = false;
5862 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5863 C = clang_getCursorReferenced(C);
5864 WasReference = true;
5865 }
5866
5867 if (C.kind == CXCursor_MacroExpansion)
5868 return clang_getCursorReferenced(C);
5869
5870 if (!clang_isDeclaration(C.kind))
5871 return clang_getNullCursor();
5872
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005873 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005874 if (!D)
5875 return clang_getNullCursor();
5876
5877 switch (D->getKind()) {
5878 // Declaration kinds that don't really separate the notions of
5879 // declaration and definition.
5880 case Decl::Namespace:
5881 case Decl::Typedef:
5882 case Decl::TypeAlias:
5883 case Decl::TypeAliasTemplate:
5884 case Decl::TemplateTypeParm:
5885 case Decl::EnumConstant:
5886 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005887 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005888 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005889 case Decl::IndirectField:
5890 case Decl::ObjCIvar:
5891 case Decl::ObjCAtDefsField:
5892 case Decl::ImplicitParam:
5893 case Decl::ParmVar:
5894 case Decl::NonTypeTemplateParm:
5895 case Decl::TemplateTemplateParm:
5896 case Decl::ObjCCategoryImpl:
5897 case Decl::ObjCImplementation:
5898 case Decl::AccessSpec:
5899 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005900 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005901 case Decl::ObjCPropertyImpl:
5902 case Decl::FileScopeAsm:
5903 case Decl::StaticAssert:
5904 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005905 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005906 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005907 case Decl::Label: // FIXME: Is this right??
5908 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00005909 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00005910 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005911 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005912 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005913 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005914 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005915 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005916 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005917 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005918 return C;
5919
5920 // Declaration kinds that don't make any sense here, but are
5921 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005922 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005923 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005924 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005925 break;
5926
5927 // Declaration kinds for which the definition is not resolvable.
5928 case Decl::UnresolvedUsingTypename:
5929 case Decl::UnresolvedUsingValue:
5930 break;
5931
5932 case Decl::UsingDirective:
5933 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5934 TU);
5935
5936 case Decl::NamespaceAlias:
5937 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5938
5939 case Decl::Enum:
5940 case Decl::Record:
5941 case Decl::CXXRecord:
5942 case Decl::ClassTemplateSpecialization:
5943 case Decl::ClassTemplatePartialSpecialization:
5944 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5945 return MakeCXCursor(Def, TU);
5946 return clang_getNullCursor();
5947
5948 case Decl::Function:
5949 case Decl::CXXMethod:
5950 case Decl::CXXConstructor:
5951 case Decl::CXXDestructor:
5952 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005953 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005954 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005955 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 return clang_getNullCursor();
5957 }
5958
Larisse Voufo39a1e502013-08-06 01:03:05 +00005959 case Decl::Var:
5960 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005961 case Decl::VarTemplatePartialSpecialization:
5962 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005963 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005964 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005965 return MakeCXCursor(Def, TU);
5966 return clang_getNullCursor();
5967 }
5968
5969 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005970 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005971 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5972 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5973 return clang_getNullCursor();
5974 }
5975
5976 case Decl::ClassTemplate: {
5977 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5978 ->getDefinition())
5979 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5980 TU);
5981 return clang_getNullCursor();
5982 }
5983
Larisse Voufo39a1e502013-08-06 01:03:05 +00005984 case Decl::VarTemplate: {
5985 if (VarDecl *Def =
5986 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5987 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5988 return clang_getNullCursor();
5989 }
5990
Guy Benyei11169dd2012-12-18 14:30:41 +00005991 case Decl::Using:
5992 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
5993 D->getLocation(), TU);
5994
5995 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00005996 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00005997 return clang_getCursorDefinition(
5998 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5999 TU));
6000
6001 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006002 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006003 if (Method->isThisDeclarationADefinition())
6004 return C;
6005
6006 // Dig out the method definition in the associated
6007 // @implementation, if we have it.
6008 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006009 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006010 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6011 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6012 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6013 Method->isInstanceMethod()))
6014 if (Def->isThisDeclarationADefinition())
6015 return MakeCXCursor(Def, TU);
6016
6017 return clang_getNullCursor();
6018 }
6019
6020 case Decl::ObjCCategory:
6021 if (ObjCCategoryImplDecl *Impl
6022 = cast<ObjCCategoryDecl>(D)->getImplementation())
6023 return MakeCXCursor(Impl, TU);
6024 return clang_getNullCursor();
6025
6026 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006027 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 return MakeCXCursor(Def, TU);
6029 return clang_getNullCursor();
6030
6031 case Decl::ObjCInterface: {
6032 // There are two notions of a "definition" for an Objective-C
6033 // class: the interface and its implementation. When we resolved a
6034 // reference to an Objective-C class, produce the @interface as
6035 // the definition; when we were provided with the interface,
6036 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006037 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006039 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 return MakeCXCursor(Def, TU);
6041 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6042 return MakeCXCursor(Impl, TU);
6043 return clang_getNullCursor();
6044 }
6045
6046 case Decl::ObjCProperty:
6047 // FIXME: We don't really know where to find the
6048 // ObjCPropertyImplDecls that implement this property.
6049 return clang_getNullCursor();
6050
6051 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006052 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006053 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006054 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006055 return MakeCXCursor(Def, TU);
6056
6057 return clang_getNullCursor();
6058
6059 case Decl::Friend:
6060 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6061 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6062 return clang_getNullCursor();
6063
6064 case Decl::FriendTemplate:
6065 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6066 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6067 return clang_getNullCursor();
6068 }
6069
6070 return clang_getNullCursor();
6071}
6072
6073unsigned clang_isCursorDefinition(CXCursor C) {
6074 if (!clang_isDeclaration(C.kind))
6075 return 0;
6076
6077 return clang_getCursorDefinition(C) == C;
6078}
6079
6080CXCursor clang_getCanonicalCursor(CXCursor C) {
6081 if (!clang_isDeclaration(C.kind))
6082 return C;
6083
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006084 if (const Decl *D = getCursorDecl(C)) {
6085 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006086 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6087 return MakeCXCursor(CatD, getCursorTU(C));
6088
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006089 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6090 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 return MakeCXCursor(IFD, getCursorTU(C));
6092
6093 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6094 }
6095
6096 return C;
6097}
6098
6099int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6100 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6101}
6102
6103unsigned clang_getNumOverloadedDecls(CXCursor C) {
6104 if (C.kind != CXCursor_OverloadedDeclRef)
6105 return 0;
6106
6107 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006108 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006109 return E->getNumDecls();
6110
6111 if (OverloadedTemplateStorage *S
6112 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6113 return S->size();
6114
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006115 const Decl *D = Storage.get<const Decl *>();
6116 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006117 return Using->shadow_size();
6118
6119 return 0;
6120}
6121
6122CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6123 if (cursor.kind != CXCursor_OverloadedDeclRef)
6124 return clang_getNullCursor();
6125
6126 if (index >= clang_getNumOverloadedDecls(cursor))
6127 return clang_getNullCursor();
6128
6129 CXTranslationUnit TU = getCursorTU(cursor);
6130 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006131 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 return MakeCXCursor(E->decls_begin()[index], TU);
6133
6134 if (OverloadedTemplateStorage *S
6135 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6136 return MakeCXCursor(S->begin()[index], TU);
6137
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006138 const Decl *D = Storage.get<const Decl *>();
6139 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006140 // FIXME: This is, unfortunately, linear time.
6141 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6142 std::advance(Pos, index);
6143 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6144 }
6145
6146 return clang_getNullCursor();
6147}
6148
6149void clang_getDefinitionSpellingAndExtent(CXCursor C,
6150 const char **startBuf,
6151 const char **endBuf,
6152 unsigned *startLine,
6153 unsigned *startColumn,
6154 unsigned *endLine,
6155 unsigned *endColumn) {
6156 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006157 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6159
6160 SourceManager &SM = FD->getASTContext().getSourceManager();
6161 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6162 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6163 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6164 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6165 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6166 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6167}
6168
6169
6170CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6171 unsigned PieceIndex) {
6172 RefNamePieces Pieces;
6173
6174 switch (C.kind) {
6175 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006176 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006177 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6178 E->getQualifierLoc().getSourceRange());
6179 break;
6180
6181 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006182 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6183 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6184 Pieces =
6185 buildPieces(NameFlags, false, E->getNameInfo(),
6186 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6187 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006188 break;
6189
6190 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006191 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006193 const Expr *Callee = OCE->getCallee();
6194 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006195 Callee = ICE->getSubExpr();
6196
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006197 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006198 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6199 DRE->getQualifierLoc().getSourceRange());
6200 }
6201 break;
6202
6203 default:
6204 break;
6205 }
6206
6207 if (Pieces.empty()) {
6208 if (PieceIndex == 0)
6209 return clang_getCursorExtent(C);
6210 } else if (PieceIndex < Pieces.size()) {
6211 SourceRange R = Pieces[PieceIndex];
6212 if (R.isValid())
6213 return cxloc::translateSourceRange(getCursorContext(C), R);
6214 }
6215
6216 return clang_getNullRange();
6217}
6218
6219void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006220 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6221 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006222}
6223
6224void clang_executeOnThread(void (*fn)(void*), void *user_data,
6225 unsigned stack_size) {
6226 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6227}
6228
Guy Benyei11169dd2012-12-18 14:30:41 +00006229//===----------------------------------------------------------------------===//
6230// Token-based Operations.
6231//===----------------------------------------------------------------------===//
6232
6233/* CXToken layout:
6234 * int_data[0]: a CXTokenKind
6235 * int_data[1]: starting token location
6236 * int_data[2]: token length
6237 * int_data[3]: reserved
6238 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6239 * otherwise unused.
6240 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006241CXTokenKind clang_getTokenKind(CXToken CXTok) {
6242 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6243}
6244
6245CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6246 switch (clang_getTokenKind(CXTok)) {
6247 case CXToken_Identifier:
6248 case CXToken_Keyword:
6249 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006250 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006251 ->getNameStart());
6252
6253 case CXToken_Literal: {
6254 // We have stashed the starting pointer in the ptr_data field. Use it.
6255 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006256 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006257 }
6258
6259 case CXToken_Punctuation:
6260 case CXToken_Comment:
6261 break;
6262 }
6263
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006264 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006265 LOG_BAD_TU(TU);
6266 return cxstring::createEmpty();
6267 }
6268
Guy Benyei11169dd2012-12-18 14:30:41 +00006269 // We have to find the starting buffer pointer the hard way, by
6270 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006271 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006272 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006273 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006274
6275 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6276 std::pair<FileID, unsigned> LocInfo
6277 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6278 bool Invalid = false;
6279 StringRef Buffer
6280 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6281 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006282 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006283
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006284 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006285}
6286
6287CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006288 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006289 LOG_BAD_TU(TU);
6290 return clang_getNullLocation();
6291 }
6292
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006293 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 if (!CXXUnit)
6295 return clang_getNullLocation();
6296
6297 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6298 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6299}
6300
6301CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006302 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006303 LOG_BAD_TU(TU);
6304 return clang_getNullRange();
6305 }
6306
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006307 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006308 if (!CXXUnit)
6309 return clang_getNullRange();
6310
6311 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6312 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6313}
6314
6315static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6316 SmallVectorImpl<CXToken> &CXTokens) {
6317 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6318 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006319 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006321 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006322
6323 // Cannot tokenize across files.
6324 if (BeginLocInfo.first != EndLocInfo.first)
6325 return;
6326
6327 // Create a lexer
6328 bool Invalid = false;
6329 StringRef Buffer
6330 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6331 if (Invalid)
6332 return;
6333
6334 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6335 CXXUnit->getASTContext().getLangOpts(),
6336 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6337 Lex.SetCommentRetentionState(true);
6338
6339 // Lex tokens until we hit the end of the range.
6340 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6341 Token Tok;
6342 bool previousWasAt = false;
6343 do {
6344 // Lex the next token
6345 Lex.LexFromRawLexer(Tok);
6346 if (Tok.is(tok::eof))
6347 break;
6348
6349 // Initialize the CXToken.
6350 CXToken CXTok;
6351
6352 // - Common fields
6353 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6354 CXTok.int_data[2] = Tok.getLength();
6355 CXTok.int_data[3] = 0;
6356
6357 // - Kind-specific fields
6358 if (Tok.isLiteral()) {
6359 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006360 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006361 } else if (Tok.is(tok::raw_identifier)) {
6362 // Lookup the identifier to determine whether we have a keyword.
6363 IdentifierInfo *II
6364 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6365
6366 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6367 CXTok.int_data[0] = CXToken_Keyword;
6368 }
6369 else {
6370 CXTok.int_data[0] = Tok.is(tok::identifier)
6371 ? CXToken_Identifier
6372 : CXToken_Keyword;
6373 }
6374 CXTok.ptr_data = II;
6375 } else if (Tok.is(tok::comment)) {
6376 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006377 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006378 } else {
6379 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006380 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 }
6382 CXTokens.push_back(CXTok);
6383 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006384 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006385}
6386
6387void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6388 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006389 LOG_FUNC_SECTION {
6390 *Log << TU << ' ' << Range;
6391 }
6392
Guy Benyei11169dd2012-12-18 14:30:41 +00006393 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006394 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006395 if (NumTokens)
6396 *NumTokens = 0;
6397
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006398 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006399 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006400 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006401 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006402
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006403 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 if (!CXXUnit || !Tokens || !NumTokens)
6405 return;
6406
6407 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6408
6409 SourceRange R = cxloc::translateCXSourceRange(Range);
6410 if (R.isInvalid())
6411 return;
6412
6413 SmallVector<CXToken, 32> CXTokens;
6414 getTokens(CXXUnit, R, CXTokens);
6415
6416 if (CXTokens.empty())
6417 return;
6418
6419 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6420 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6421 *NumTokens = CXTokens.size();
6422}
6423
6424void clang_disposeTokens(CXTranslationUnit TU,
6425 CXToken *Tokens, unsigned NumTokens) {
6426 free(Tokens);
6427}
6428
Guy Benyei11169dd2012-12-18 14:30:41 +00006429//===----------------------------------------------------------------------===//
6430// Token annotation APIs.
6431//===----------------------------------------------------------------------===//
6432
Guy Benyei11169dd2012-12-18 14:30:41 +00006433static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6434 CXCursor parent,
6435 CXClientData client_data);
6436static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6437 CXClientData client_data);
6438
6439namespace {
6440class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006441 CXToken *Tokens;
6442 CXCursor *Cursors;
6443 unsigned NumTokens;
6444 unsigned TokIdx;
6445 unsigned PreprocessingTokIdx;
6446 CursorVisitor AnnotateVis;
6447 SourceManager &SrcMgr;
6448 bool HasContextSensitiveKeywords;
6449
6450 struct PostChildrenInfo {
6451 CXCursor Cursor;
6452 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006453 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 unsigned BeforeChildrenTokenIdx;
6455 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006456 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006457
6458 CXToken &getTok(unsigned Idx) {
6459 assert(Idx < NumTokens);
6460 return Tokens[Idx];
6461 }
6462 const CXToken &getTok(unsigned Idx) const {
6463 assert(Idx < NumTokens);
6464 return Tokens[Idx];
6465 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006466 bool MoreTokens() const { return TokIdx < NumTokens; }
6467 unsigned NextToken() const { return TokIdx; }
6468 void AdvanceToken() { ++TokIdx; }
6469 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006470 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006471 }
6472 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006473 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006474 }
6475 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006476 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006477 }
6478
6479 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006480 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006481 SourceRange);
6482
6483public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006484 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006485 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006486 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006487 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006488 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006489 AnnotateTokensVisitor, this,
6490 /*VisitPreprocessorLast=*/true,
6491 /*VisitIncludedEntities=*/false,
6492 RegionOfInterest,
6493 /*VisitDeclsOnly=*/false,
6494 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006495 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006496 HasContextSensitiveKeywords(false) { }
6497
6498 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6499 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6500 bool postVisitChildren(CXCursor cursor);
6501 void AnnotateTokens();
6502
6503 /// \brief Determine whether the annotator saw any cursors that have
6504 /// context-sensitive keywords.
6505 bool hasContextSensitiveKeywords() const {
6506 return HasContextSensitiveKeywords;
6507 }
6508
6509 ~AnnotateTokensWorker() {
6510 assert(PostChildrenInfos.empty());
6511 }
6512};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006513}
Guy Benyei11169dd2012-12-18 14:30:41 +00006514
6515void AnnotateTokensWorker::AnnotateTokens() {
6516 // Walk the AST within the region of interest, annotating tokens
6517 // along the way.
6518 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006519}
Guy Benyei11169dd2012-12-18 14:30:41 +00006520
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006521static inline void updateCursorAnnotation(CXCursor &Cursor,
6522 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006523 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006524 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006525 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006526}
6527
6528/// \brief It annotates and advances tokens with a cursor until the comparison
6529//// between the cursor location and the source range is the same as
6530/// \arg compResult.
6531///
6532/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6533/// Pass RangeOverlap to annotate tokens inside a range.
6534void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6535 RangeComparisonResult compResult,
6536 SourceRange range) {
6537 while (MoreTokens()) {
6538 const unsigned I = NextToken();
6539 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006540 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6541 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006542
6543 SourceLocation TokLoc = GetTokenLoc(I);
6544 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006545 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 AdvanceToken();
6547 continue;
6548 }
6549 break;
6550 }
6551}
6552
6553/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006554/// \returns true if it advanced beyond all macro tokens, false otherwise.
6555bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 CXCursor updateC,
6557 RangeComparisonResult compResult,
6558 SourceRange range) {
6559 assert(MoreTokens());
6560 assert(isFunctionMacroToken(NextToken()) &&
6561 "Should be called only for macro arg tokens");
6562
6563 // This works differently than annotateAndAdvanceTokens; because expanded
6564 // macro arguments can have arbitrary translation-unit source order, we do not
6565 // advance the token index one by one until a token fails the range test.
6566 // We only advance once past all of the macro arg tokens if all of them
6567 // pass the range test. If one of them fails we keep the token index pointing
6568 // at the start of the macro arg tokens so that the failing token will be
6569 // annotated by a subsequent annotation try.
6570
6571 bool atLeastOneCompFail = false;
6572
6573 unsigned I = NextToken();
6574 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6575 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6576 if (TokLoc.isFileID())
6577 continue; // not macro arg token, it's parens or comma.
6578 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6579 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6580 Cursors[I] = updateC;
6581 } else
6582 atLeastOneCompFail = true;
6583 }
6584
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006585 if (atLeastOneCompFail)
6586 return false;
6587
6588 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6589 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006590}
6591
6592enum CXChildVisitResult
6593AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 SourceRange cursorRange = getRawCursorExtent(cursor);
6595 if (cursorRange.isInvalid())
6596 return CXChildVisit_Recurse;
6597
6598 if (!HasContextSensitiveKeywords) {
6599 // Objective-C properties can have context-sensitive keywords.
6600 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006601 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006602 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6603 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6604 }
6605 // Objective-C methods can have context-sensitive keywords.
6606 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6607 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006608 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006609 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6610 if (Method->getObjCDeclQualifier())
6611 HasContextSensitiveKeywords = true;
6612 else {
David Majnemer59f77922016-06-24 04:05:48 +00006613 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006614 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006615 HasContextSensitiveKeywords = true;
6616 break;
6617 }
6618 }
6619 }
6620 }
6621 }
6622 // C++ methods can have context-sensitive keywords.
6623 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006624 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006625 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6626 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6627 HasContextSensitiveKeywords = true;
6628 }
6629 }
6630 // C++ classes can have context-sensitive keywords.
6631 else if (cursor.kind == CXCursor_StructDecl ||
6632 cursor.kind == CXCursor_ClassDecl ||
6633 cursor.kind == CXCursor_ClassTemplate ||
6634 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006635 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006636 if (D->hasAttr<FinalAttr>())
6637 HasContextSensitiveKeywords = true;
6638 }
6639 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006640
6641 // Don't override a property annotation with its getter/setter method.
6642 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6643 parent.kind == CXCursor_ObjCPropertyDecl)
6644 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006645
6646 if (clang_isPreprocessing(cursor.kind)) {
6647 // Items in the preprocessing record are kept separate from items in
6648 // declarations, so we keep a separate token index.
6649 unsigned SavedTokIdx = TokIdx;
6650 TokIdx = PreprocessingTokIdx;
6651
6652 // Skip tokens up until we catch up to the beginning of the preprocessing
6653 // entry.
6654 while (MoreTokens()) {
6655 const unsigned I = NextToken();
6656 SourceLocation TokLoc = GetTokenLoc(I);
6657 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6658 case RangeBefore:
6659 AdvanceToken();
6660 continue;
6661 case RangeAfter:
6662 case RangeOverlap:
6663 break;
6664 }
6665 break;
6666 }
6667
6668 // Look at all of the tokens within this range.
6669 while (MoreTokens()) {
6670 const unsigned I = NextToken();
6671 SourceLocation TokLoc = GetTokenLoc(I);
6672 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6673 case RangeBefore:
6674 llvm_unreachable("Infeasible");
6675 case RangeAfter:
6676 break;
6677 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006678 // For macro expansions, just note where the beginning of the macro
6679 // expansion occurs.
6680 if (cursor.kind == CXCursor_MacroExpansion) {
6681 if (TokLoc == cursorRange.getBegin())
6682 Cursors[I] = cursor;
6683 AdvanceToken();
6684 break;
6685 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006686 // We may have already annotated macro names inside macro definitions.
6687 if (Cursors[I].kind != CXCursor_MacroExpansion)
6688 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006689 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006690 continue;
6691 }
6692 break;
6693 }
6694
6695 // Save the preprocessing token index; restore the non-preprocessing
6696 // token index.
6697 PreprocessingTokIdx = TokIdx;
6698 TokIdx = SavedTokIdx;
6699 return CXChildVisit_Recurse;
6700 }
6701
6702 if (cursorRange.isInvalid())
6703 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006704
6705 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006707 const enum CXCursorKind K = clang_getCursorKind(parent);
6708 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006709 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6710 // Attributes are annotated out-of-order, skip tokens until we reach it.
6711 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006712 ? clang_getNullCursor() : parent;
6713
6714 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6715
6716 // Avoid having the cursor of an expression "overwrite" the annotation of the
6717 // variable declaration that it belongs to.
6718 // This can happen for C++ constructor expressions whose range generally
6719 // include the variable declaration, e.g.:
6720 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006721 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006722 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006723 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006724 const unsigned I = NextToken();
6725 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6726 E->getLocStart() == D->getLocation() &&
6727 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006728 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006729 AdvanceToken();
6730 }
6731 }
6732 }
6733
6734 // Before recursing into the children keep some state that we are going
6735 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6736 // extra work after the child nodes are visited.
6737 // Note that we don't call VisitChildren here to avoid traversing statements
6738 // code-recursively which can blow the stack.
6739
6740 PostChildrenInfo Info;
6741 Info.Cursor = cursor;
6742 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006743 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006744 Info.BeforeChildrenTokenIdx = NextToken();
6745 PostChildrenInfos.push_back(Info);
6746
6747 return CXChildVisit_Recurse;
6748}
6749
6750bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6751 if (PostChildrenInfos.empty())
6752 return false;
6753 const PostChildrenInfo &Info = PostChildrenInfos.back();
6754 if (!clang_equalCursors(Info.Cursor, cursor))
6755 return false;
6756
6757 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6758 const unsigned AfterChildren = NextToken();
6759 SourceRange cursorRange = Info.CursorRange;
6760
6761 // Scan the tokens that are at the end of the cursor, but are not captured
6762 // but the child cursors.
6763 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6764
6765 // Scan the tokens that are at the beginning of the cursor, but are not
6766 // capture by the child cursors.
6767 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6768 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6769 break;
6770
6771 Cursors[I] = cursor;
6772 }
6773
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006774 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6775 // encountered the attribute cursor.
6776 if (clang_isAttribute(cursor.kind))
6777 TokIdx = Info.BeforeReachingCursorIdx;
6778
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 PostChildrenInfos.pop_back();
6780 return false;
6781}
6782
6783static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6784 CXCursor parent,
6785 CXClientData client_data) {
6786 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6787}
6788
6789static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6790 CXClientData client_data) {
6791 return static_cast<AnnotateTokensWorker*>(client_data)->
6792 postVisitChildren(cursor);
6793}
6794
6795namespace {
6796
6797/// \brief Uses the macro expansions in the preprocessing record to find
6798/// and mark tokens that are macro arguments. This info is used by the
6799/// AnnotateTokensWorker.
6800class MarkMacroArgTokensVisitor {
6801 SourceManager &SM;
6802 CXToken *Tokens;
6803 unsigned NumTokens;
6804 unsigned CurIdx;
6805
6806public:
6807 MarkMacroArgTokensVisitor(SourceManager &SM,
6808 CXToken *tokens, unsigned numTokens)
6809 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6810
6811 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6812 if (cursor.kind != CXCursor_MacroExpansion)
6813 return CXChildVisit_Continue;
6814
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006815 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006816 if (macroRange.getBegin() == macroRange.getEnd())
6817 return CXChildVisit_Continue; // it's not a function macro.
6818
6819 for (; CurIdx < NumTokens; ++CurIdx) {
6820 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6821 macroRange.getBegin()))
6822 break;
6823 }
6824
6825 if (CurIdx == NumTokens)
6826 return CXChildVisit_Break;
6827
6828 for (; CurIdx < NumTokens; ++CurIdx) {
6829 SourceLocation tokLoc = getTokenLoc(CurIdx);
6830 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6831 break;
6832
6833 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6834 }
6835
6836 if (CurIdx == NumTokens)
6837 return CXChildVisit_Break;
6838
6839 return CXChildVisit_Continue;
6840 }
6841
6842private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006843 CXToken &getTok(unsigned Idx) {
6844 assert(Idx < NumTokens);
6845 return Tokens[Idx];
6846 }
6847 const CXToken &getTok(unsigned Idx) const {
6848 assert(Idx < NumTokens);
6849 return Tokens[Idx];
6850 }
6851
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006853 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 }
6855
6856 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6857 // The third field is reserved and currently not used. Use it here
6858 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006859 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 }
6861};
6862
6863} // end anonymous namespace
6864
6865static CXChildVisitResult
6866MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6867 CXClientData client_data) {
6868 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6869 parent);
6870}
6871
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006872/// \brief Used by \c annotatePreprocessorTokens.
6873/// \returns true if lexing was finished, false otherwise.
6874static bool lexNext(Lexer &Lex, Token &Tok,
6875 unsigned &NextIdx, unsigned NumTokens) {
6876 if (NextIdx >= NumTokens)
6877 return true;
6878
6879 ++NextIdx;
6880 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006881 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006882}
6883
Guy Benyei11169dd2012-12-18 14:30:41 +00006884static void annotatePreprocessorTokens(CXTranslationUnit TU,
6885 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006886 CXCursor *Cursors,
6887 CXToken *Tokens,
6888 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006889 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006890
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006891 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006892 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6893 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006894 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006895 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006896 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006897
6898 if (BeginLocInfo.first != EndLocInfo.first)
6899 return;
6900
6901 StringRef Buffer;
6902 bool Invalid = false;
6903 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6904 if (Buffer.empty() || Invalid)
6905 return;
6906
6907 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6908 CXXUnit->getASTContext().getLangOpts(),
6909 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6910 Buffer.end());
6911 Lex.SetCommentRetentionState(true);
6912
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006913 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006914 // Lex tokens in raw mode until we hit the end of the range, to avoid
6915 // entering #includes or expanding macros.
6916 while (true) {
6917 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006918 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6919 break;
6920 unsigned TokIdx = NextIdx-1;
6921 assert(Tok.getLocation() ==
6922 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006923
6924 reprocess:
6925 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006926 // We have found a preprocessing directive. Annotate the tokens
6927 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006928 //
6929 // FIXME: Some simple tests here could identify macro definitions and
6930 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006931
6932 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006933 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6934 break;
6935
Craig Topper69186e72014-06-08 08:38:04 +00006936 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006937 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006938 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6939 break;
6940
6941 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006942 IdentifierInfo &II =
6943 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006944 SourceLocation MappedTokLoc =
6945 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6946 MI = getMacroInfo(II, MappedTokLoc, TU);
6947 }
6948 }
6949
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006950 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006951 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006952 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6953 finished = true;
6954 break;
6955 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006956 // If we are in a macro definition, check if the token was ever a
6957 // macro name and annotate it if that's the case.
6958 if (MI) {
6959 SourceLocation SaveLoc = Tok.getLocation();
6960 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006961 MacroDefinitionRecord *MacroDef =
6962 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006963 Tok.setLocation(SaveLoc);
6964 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006965 Cursors[NextIdx - 1] =
6966 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006967 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006968 } while (!Tok.isAtStartOfLine());
6969
6970 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6971 assert(TokIdx <= LastIdx);
6972 SourceLocation EndLoc =
6973 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6974 CXCursor Cursor =
6975 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6976
6977 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006978 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006979
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006980 if (finished)
6981 break;
6982 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 }
6985}
6986
6987// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00006988static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6989 CXToken *Tokens, unsigned NumTokens,
6990 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00006991 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006992 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6993 setThreadBackgroundPriority();
6994
6995 // Determine the region of interest, which contains all of the tokens.
6996 SourceRange RegionOfInterest;
6997 RegionOfInterest.setBegin(
6998 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6999 RegionOfInterest.setEnd(
7000 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7001 Tokens[NumTokens-1])));
7002
Guy Benyei11169dd2012-12-18 14:30:41 +00007003 // Relex the tokens within the source range to look for preprocessing
7004 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007005 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007006
7007 // If begin location points inside a macro argument, set it to the expansion
7008 // location so we can have the full context when annotating semantically.
7009 {
7010 SourceManager &SM = CXXUnit->getSourceManager();
7011 SourceLocation Loc =
7012 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7013 if (Loc.isMacroID())
7014 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7015 }
7016
Guy Benyei11169dd2012-12-18 14:30:41 +00007017 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7018 // Search and mark tokens that are macro argument expansions.
7019 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7020 Tokens, NumTokens);
7021 CursorVisitor MacroArgMarker(TU,
7022 MarkMacroArgTokensVisitorDelegate, &Visitor,
7023 /*VisitPreprocessorLast=*/true,
7024 /*VisitIncludedEntities=*/false,
7025 RegionOfInterest);
7026 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7027 }
7028
7029 // Annotate all of the source locations in the region of interest that map to
7030 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007031 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007032
7033 // FIXME: We use a ridiculous stack size here because the data-recursion
7034 // algorithm uses a large stack frame than the non-data recursive version,
7035 // and AnnotationTokensWorker currently transforms the data-recursion
7036 // algorithm back into a traditional recursion by explicitly calling
7037 // VisitChildren(). We will need to remove this explicit recursive call.
7038 W.AnnotateTokens();
7039
7040 // If we ran into any entities that involve context-sensitive keywords,
7041 // take another pass through the tokens to mark them as such.
7042 if (W.hasContextSensitiveKeywords()) {
7043 for (unsigned I = 0; I != NumTokens; ++I) {
7044 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7045 continue;
7046
7047 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7048 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007049 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007050 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7051 if (Property->getPropertyAttributesAsWritten() != 0 &&
7052 llvm::StringSwitch<bool>(II->getName())
7053 .Case("readonly", true)
7054 .Case("assign", true)
7055 .Case("unsafe_unretained", true)
7056 .Case("readwrite", true)
7057 .Case("retain", true)
7058 .Case("copy", true)
7059 .Case("nonatomic", true)
7060 .Case("atomic", true)
7061 .Case("getter", true)
7062 .Case("setter", true)
7063 .Case("strong", true)
7064 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007065 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 .Default(false))
7067 Tokens[I].int_data[0] = CXToken_Keyword;
7068 }
7069 continue;
7070 }
7071
7072 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7073 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7074 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7075 if (llvm::StringSwitch<bool>(II->getName())
7076 .Case("in", true)
7077 .Case("out", true)
7078 .Case("inout", true)
7079 .Case("oneway", true)
7080 .Case("bycopy", true)
7081 .Case("byref", true)
7082 .Default(false))
7083 Tokens[I].int_data[0] = CXToken_Keyword;
7084 continue;
7085 }
7086
7087 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7088 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7089 Tokens[I].int_data[0] = CXToken_Keyword;
7090 continue;
7091 }
7092 }
7093 }
7094}
7095
Guy Benyei11169dd2012-12-18 14:30:41 +00007096void clang_annotateTokens(CXTranslationUnit TU,
7097 CXToken *Tokens, unsigned NumTokens,
7098 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007099 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007100 LOG_BAD_TU(TU);
7101 return;
7102 }
7103 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007104 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007105 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007106 }
7107
7108 LOG_FUNC_SECTION {
7109 *Log << TU << ' ';
7110 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7111 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7112 *Log << clang_getRange(bloc, eloc);
7113 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007114
7115 // Any token we don't specifically annotate will have a NULL cursor.
7116 CXCursor C = clang_getNullCursor();
7117 for (unsigned I = 0; I != NumTokens; ++I)
7118 Cursors[I] = C;
7119
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007120 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007121 if (!CXXUnit)
7122 return;
7123
7124 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007125
7126 auto AnnotateTokensImpl = [=]() {
7127 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7128 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007129 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007130 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007131 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7132 }
7133}
7134
Guy Benyei11169dd2012-12-18 14:30:41 +00007135//===----------------------------------------------------------------------===//
7136// Operations for querying linkage of a cursor.
7137//===----------------------------------------------------------------------===//
7138
Guy Benyei11169dd2012-12-18 14:30:41 +00007139CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7140 if (!clang_isDeclaration(cursor.kind))
7141 return CXLinkage_Invalid;
7142
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007143 const Decl *D = cxcursor::getCursorDecl(cursor);
7144 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007145 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007146 case NoLinkage:
7147 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007148 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007149 case InternalLinkage: return CXLinkage_Internal;
7150 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007151 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007152 case ExternalLinkage: return CXLinkage_External;
7153 };
7154
7155 return CXLinkage_Invalid;
7156}
Guy Benyei11169dd2012-12-18 14:30:41 +00007157
7158//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007159// Operations for querying visibility of a cursor.
7160//===----------------------------------------------------------------------===//
7161
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007162CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7163 if (!clang_isDeclaration(cursor.kind))
7164 return CXVisibility_Invalid;
7165
7166 const Decl *D = cxcursor::getCursorDecl(cursor);
7167 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7168 switch (ND->getVisibility()) {
7169 case HiddenVisibility: return CXVisibility_Hidden;
7170 case ProtectedVisibility: return CXVisibility_Protected;
7171 case DefaultVisibility: return CXVisibility_Default;
7172 };
7173
7174 return CXVisibility_Invalid;
7175}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007176
7177//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007178// Operations for querying language of a cursor.
7179//===----------------------------------------------------------------------===//
7180
7181static CXLanguageKind getDeclLanguage(const Decl *D) {
7182 if (!D)
7183 return CXLanguage_C;
7184
7185 switch (D->getKind()) {
7186 default:
7187 break;
7188 case Decl::ImplicitParam:
7189 case Decl::ObjCAtDefsField:
7190 case Decl::ObjCCategory:
7191 case Decl::ObjCCategoryImpl:
7192 case Decl::ObjCCompatibleAlias:
7193 case Decl::ObjCImplementation:
7194 case Decl::ObjCInterface:
7195 case Decl::ObjCIvar:
7196 case Decl::ObjCMethod:
7197 case Decl::ObjCProperty:
7198 case Decl::ObjCPropertyImpl:
7199 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007200 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007201 return CXLanguage_ObjC;
7202 case Decl::CXXConstructor:
7203 case Decl::CXXConversion:
7204 case Decl::CXXDestructor:
7205 case Decl::CXXMethod:
7206 case Decl::CXXRecord:
7207 case Decl::ClassTemplate:
7208 case Decl::ClassTemplatePartialSpecialization:
7209 case Decl::ClassTemplateSpecialization:
7210 case Decl::Friend:
7211 case Decl::FriendTemplate:
7212 case Decl::FunctionTemplate:
7213 case Decl::LinkageSpec:
7214 case Decl::Namespace:
7215 case Decl::NamespaceAlias:
7216 case Decl::NonTypeTemplateParm:
7217 case Decl::StaticAssert:
7218 case Decl::TemplateTemplateParm:
7219 case Decl::TemplateTypeParm:
7220 case Decl::UnresolvedUsingTypename:
7221 case Decl::UnresolvedUsingValue:
7222 case Decl::Using:
7223 case Decl::UsingDirective:
7224 case Decl::UsingShadow:
7225 return CXLanguage_CPlusPlus;
7226 }
7227
7228 return CXLanguage_C;
7229}
7230
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007231static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7232 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007233 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007234
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007235 switch (D->getAvailability()) {
7236 case AR_Available:
7237 case AR_NotYetIntroduced:
7238 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007239 return getCursorAvailabilityForDecl(
7240 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007241 return CXAvailability_Available;
7242
7243 case AR_Deprecated:
7244 return CXAvailability_Deprecated;
7245
7246 case AR_Unavailable:
7247 return CXAvailability_NotAvailable;
7248 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007249
7250 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007251}
7252
Guy Benyei11169dd2012-12-18 14:30:41 +00007253enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7254 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007255 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7256 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007257
7258 return CXAvailability_Available;
7259}
7260
7261static CXVersion convertVersion(VersionTuple In) {
7262 CXVersion Out = { -1, -1, -1 };
7263 if (In.empty())
7264 return Out;
7265
7266 Out.Major = In.getMajor();
7267
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007268 Optional<unsigned> Minor = In.getMinor();
7269 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007270 Out.Minor = *Minor;
7271 else
7272 return Out;
7273
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007274 Optional<unsigned> Subminor = In.getSubminor();
7275 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 Out.Subminor = *Subminor;
7277
7278 return Out;
7279}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007280
Alex Lorenz1345ea22017-06-12 19:06:30 +00007281static void getCursorPlatformAvailabilityForDecl(
7282 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7283 int *always_unavailable, CXString *unavailable_message,
7284 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007285 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007286 for (auto A : D->attrs()) {
7287 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007288 HadAvailAttr = true;
7289 if (always_deprecated)
7290 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007291 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007292 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007293 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007294 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007295 continue;
7296 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007297
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007298 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007299 HadAvailAttr = true;
7300 if (always_unavailable)
7301 *always_unavailable = 1;
7302 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007303 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007304 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7305 }
7306 continue;
7307 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007308
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007309 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007310 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007311 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007312 }
7313 }
7314
7315 if (!HadAvailAttr)
7316 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7317 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007318 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7319 deprecated_message, always_unavailable, unavailable_message,
7320 AvailabilityAttrs);
7321
7322 if (AvailabilityAttrs.empty())
7323 return;
7324
7325 std::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7326 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
Reid Klecknere6cde142017-08-04 21:52:25 +00007327 return LHS->getPlatform()->getName() <
7328 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007329 });
7330 ASTContext &Ctx = D->getASTContext();
7331 auto It = std::unique(
7332 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7333 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7334 if (LHS->getPlatform() != RHS->getPlatform())
7335 return false;
7336
7337 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7338 LHS->getDeprecated() == RHS->getDeprecated() &&
7339 LHS->getObsoleted() == RHS->getObsoleted() &&
7340 LHS->getMessage() == RHS->getMessage() &&
7341 LHS->getReplacement() == RHS->getReplacement())
7342 return true;
7343
7344 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7345 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7346 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7347 return false;
7348
7349 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7350 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7351
7352 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7353 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7354 if (LHS->getMessage().empty())
7355 LHS->setMessage(Ctx, RHS->getMessage());
7356 if (LHS->getReplacement().empty())
7357 LHS->setReplacement(Ctx, RHS->getReplacement());
7358 }
7359
7360 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7361 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7362 if (LHS->getMessage().empty())
7363 LHS->setMessage(Ctx, RHS->getMessage());
7364 if (LHS->getReplacement().empty())
7365 LHS->setReplacement(Ctx, RHS->getReplacement());
7366 }
7367
7368 return true;
7369 });
7370 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007371}
7372
Alex Lorenz1345ea22017-06-12 19:06:30 +00007373int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007374 CXString *deprecated_message,
7375 int *always_unavailable,
7376 CXString *unavailable_message,
7377 CXPlatformAvailability *availability,
7378 int availability_size) {
7379 if (always_deprecated)
7380 *always_deprecated = 0;
7381 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007382 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007383 if (always_unavailable)
7384 *always_unavailable = 0;
7385 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007386 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007387
Guy Benyei11169dd2012-12-18 14:30:41 +00007388 if (!clang_isDeclaration(cursor.kind))
7389 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007390
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007391 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007392 if (!D)
7393 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007394
Alex Lorenz1345ea22017-06-12 19:06:30 +00007395 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7396 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7397 always_unavailable, unavailable_message,
7398 AvailabilityAttrs);
7399 for (const auto &Avail :
7400 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7401 .take_front(availability_size))) {
7402 availability[Avail.index()].Platform =
7403 cxstring::createDup(Avail.value()->getPlatform()->getName());
7404 availability[Avail.index()].Introduced =
7405 convertVersion(Avail.value()->getIntroduced());
7406 availability[Avail.index()].Deprecated =
7407 convertVersion(Avail.value()->getDeprecated());
7408 availability[Avail.index()].Obsoleted =
7409 convertVersion(Avail.value()->getObsoleted());
7410 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7411 availability[Avail.index()].Message =
7412 cxstring::createDup(Avail.value()->getMessage());
7413 }
7414
7415 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007416}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007417
Guy Benyei11169dd2012-12-18 14:30:41 +00007418void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7419 clang_disposeString(availability->Platform);
7420 clang_disposeString(availability->Message);
7421}
7422
7423CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7424 if (clang_isDeclaration(cursor.kind))
7425 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7426
7427 return CXLanguage_Invalid;
7428}
7429
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007430CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7431 const Decl *D = cxcursor::getCursorDecl(cursor);
7432 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7433 switch (VD->getTLSKind()) {
7434 case VarDecl::TLS_None:
7435 return CXTLS_None;
7436 case VarDecl::TLS_Dynamic:
7437 return CXTLS_Dynamic;
7438 case VarDecl::TLS_Static:
7439 return CXTLS_Static;
7440 }
7441 }
7442
7443 return CXTLS_None;
7444}
7445
Guy Benyei11169dd2012-12-18 14:30:41 +00007446 /// \brief If the given cursor is the "templated" declaration
7447 /// descibing a class or function template, return the class or
7448 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007449static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007450 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007451 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007452
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007453 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007454 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7455 return FunTmpl;
7456
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007457 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007458 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7459 return ClassTmpl;
7460
7461 return D;
7462}
7463
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007464
7465enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7466 StorageClass sc = SC_None;
7467 const Decl *D = getCursorDecl(C);
7468 if (D) {
7469 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7470 sc = FD->getStorageClass();
7471 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7472 sc = VD->getStorageClass();
7473 } else {
7474 return CX_SC_Invalid;
7475 }
7476 } else {
7477 return CX_SC_Invalid;
7478 }
7479 switch (sc) {
7480 case SC_None:
7481 return CX_SC_None;
7482 case SC_Extern:
7483 return CX_SC_Extern;
7484 case SC_Static:
7485 return CX_SC_Static;
7486 case SC_PrivateExtern:
7487 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007488 case SC_Auto:
7489 return CX_SC_Auto;
7490 case SC_Register:
7491 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007492 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007493 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007494}
7495
Guy Benyei11169dd2012-12-18 14:30:41 +00007496CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7497 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007498 if (const Decl *D = getCursorDecl(cursor)) {
7499 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007500 if (!DC)
7501 return clang_getNullCursor();
7502
7503 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7504 getCursorTU(cursor));
7505 }
7506 }
7507
7508 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007509 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007510 return MakeCXCursor(D, getCursorTU(cursor));
7511 }
7512
7513 return clang_getNullCursor();
7514}
7515
7516CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7517 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007518 if (const Decl *D = getCursorDecl(cursor)) {
7519 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007520 if (!DC)
7521 return clang_getNullCursor();
7522
7523 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7524 getCursorTU(cursor));
7525 }
7526 }
7527
7528 // FIXME: Note that we can't easily compute the lexical context of a
7529 // statement or expression, so we return nothing.
7530 return clang_getNullCursor();
7531}
7532
7533CXFile clang_getIncludedFile(CXCursor cursor) {
7534 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007535 return nullptr;
7536
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007537 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007538 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007539}
7540
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007541unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7542 if (C.kind != CXCursor_ObjCPropertyDecl)
7543 return CXObjCPropertyAttr_noattr;
7544
7545 unsigned Result = CXObjCPropertyAttr_noattr;
7546 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7547 ObjCPropertyDecl::PropertyAttributeKind Attr =
7548 PD->getPropertyAttributesAsWritten();
7549
7550#define SET_CXOBJCPROP_ATTR(A) \
7551 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7552 Result |= CXObjCPropertyAttr_##A
7553 SET_CXOBJCPROP_ATTR(readonly);
7554 SET_CXOBJCPROP_ATTR(getter);
7555 SET_CXOBJCPROP_ATTR(assign);
7556 SET_CXOBJCPROP_ATTR(readwrite);
7557 SET_CXOBJCPROP_ATTR(retain);
7558 SET_CXOBJCPROP_ATTR(copy);
7559 SET_CXOBJCPROP_ATTR(nonatomic);
7560 SET_CXOBJCPROP_ATTR(setter);
7561 SET_CXOBJCPROP_ATTR(atomic);
7562 SET_CXOBJCPROP_ATTR(weak);
7563 SET_CXOBJCPROP_ATTR(strong);
7564 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007565 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007566#undef SET_CXOBJCPROP_ATTR
7567
7568 return Result;
7569}
7570
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007571unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7572 if (!clang_isDeclaration(C.kind))
7573 return CXObjCDeclQualifier_None;
7574
7575 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7576 const Decl *D = getCursorDecl(C);
7577 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7578 QT = MD->getObjCDeclQualifier();
7579 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7580 QT = PD->getObjCDeclQualifier();
7581 if (QT == Decl::OBJC_TQ_None)
7582 return CXObjCDeclQualifier_None;
7583
7584 unsigned Result = CXObjCDeclQualifier_None;
7585 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7586 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7587 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7588 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7589 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7590 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7591
7592 return Result;
7593}
7594
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007595unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7596 if (!clang_isDeclaration(C.kind))
7597 return 0;
7598
7599 const Decl *D = getCursorDecl(C);
7600 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7601 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7602 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7603 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7604
7605 return 0;
7606}
7607
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007608unsigned clang_Cursor_isVariadic(CXCursor C) {
7609 if (!clang_isDeclaration(C.kind))
7610 return 0;
7611
7612 const Decl *D = getCursorDecl(C);
7613 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7614 return FD->isVariadic();
7615 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7616 return MD->isVariadic();
7617
7618 return 0;
7619}
7620
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007621unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7622 CXString *language, CXString *definedIn,
7623 unsigned *isGenerated) {
7624 if (!clang_isDeclaration(C.kind))
7625 return 0;
7626
7627 const Decl *D = getCursorDecl(C);
7628
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00007629 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007630 if (language)
7631 *language = cxstring::createDup(attr->getLanguage());
7632 if (definedIn)
7633 *definedIn = cxstring::createDup(attr->getDefinedIn());
7634 if (isGenerated)
7635 *isGenerated = attr->getGeneratedDeclaration();
7636 return 1;
7637 }
7638 return 0;
7639}
7640
Guy Benyei11169dd2012-12-18 14:30:41 +00007641CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7642 if (!clang_isDeclaration(C.kind))
7643 return clang_getNullRange();
7644
7645 const Decl *D = getCursorDecl(C);
7646 ASTContext &Context = getCursorContext(C);
7647 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7648 if (!RC)
7649 return clang_getNullRange();
7650
7651 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7652}
7653
7654CXString clang_Cursor_getRawCommentText(CXCursor C) {
7655 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007656 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007657
7658 const Decl *D = getCursorDecl(C);
7659 ASTContext &Context = getCursorContext(C);
7660 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7661 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7662 StringRef();
7663
7664 // Don't duplicate the string because RawText points directly into source
7665 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007666 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007667}
7668
7669CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7670 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007671 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007672
7673 const Decl *D = getCursorDecl(C);
7674 const ASTContext &Context = getCursorContext(C);
7675 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7676
7677 if (RC) {
7678 StringRef BriefText = RC->getBriefText(Context);
7679
7680 // Don't duplicate the string because RawComment ensures that this memory
7681 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007682 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007683 }
7684
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007685 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007686}
7687
Guy Benyei11169dd2012-12-18 14:30:41 +00007688CXModule clang_Cursor_getModule(CXCursor C) {
7689 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007690 if (const ImportDecl *ImportD =
7691 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007692 return ImportD->getImportedModule();
7693 }
7694
Craig Topper69186e72014-06-08 08:38:04 +00007695 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007696}
7697
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007698CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7699 if (isNotUsableTU(TU)) {
7700 LOG_BAD_TU(TU);
7701 return nullptr;
7702 }
7703 if (!File)
7704 return nullptr;
7705 FileEntry *FE = static_cast<FileEntry *>(File);
7706
7707 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7708 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7709 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7710
Richard Smithfeb54b62014-10-23 02:01:19 +00007711 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007712}
7713
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007714CXFile clang_Module_getASTFile(CXModule CXMod) {
7715 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007716 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007717 Module *Mod = static_cast<Module*>(CXMod);
7718 return const_cast<FileEntry *>(Mod->getASTFile());
7719}
7720
Guy Benyei11169dd2012-12-18 14:30:41 +00007721CXModule clang_Module_getParent(CXModule CXMod) {
7722 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007723 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007724 Module *Mod = static_cast<Module*>(CXMod);
7725 return Mod->Parent;
7726}
7727
7728CXString clang_Module_getName(CXModule CXMod) {
7729 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007730 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007731 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007732 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007733}
7734
7735CXString clang_Module_getFullName(CXModule CXMod) {
7736 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007737 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007738 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007739 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007740}
7741
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007742int clang_Module_isSystem(CXModule CXMod) {
7743 if (!CXMod)
7744 return 0;
7745 Module *Mod = static_cast<Module*>(CXMod);
7746 return Mod->IsSystem;
7747}
7748
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007749unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7750 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007751 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007752 LOG_BAD_TU(TU);
7753 return 0;
7754 }
7755 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007756 return 0;
7757 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007758 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7759 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7760 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007761}
7762
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007763CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7764 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007765 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007766 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007767 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007768 }
7769 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007770 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007771 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007772 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007773
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007774 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7775 if (Index < TopHeaders.size())
7776 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007777
Craig Topper69186e72014-06-08 08:38:04 +00007778 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007779}
7780
Guy Benyei11169dd2012-12-18 14:30:41 +00007781//===----------------------------------------------------------------------===//
7782// C++ AST instrospection.
7783//===----------------------------------------------------------------------===//
7784
Jonathan Coe29565352016-04-27 12:48:25 +00007785unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7786 if (!clang_isDeclaration(C.kind))
7787 return 0;
7788
7789 const Decl *D = cxcursor::getCursorDecl(C);
7790 const CXXConstructorDecl *Constructor =
7791 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7792 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7793}
7794
7795unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7796 if (!clang_isDeclaration(C.kind))
7797 return 0;
7798
7799 const Decl *D = cxcursor::getCursorDecl(C);
7800 const CXXConstructorDecl *Constructor =
7801 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7802 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7803}
7804
7805unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7806 if (!clang_isDeclaration(C.kind))
7807 return 0;
7808
7809 const Decl *D = cxcursor::getCursorDecl(C);
7810 const CXXConstructorDecl *Constructor =
7811 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7812 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7813}
7814
7815unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7816 if (!clang_isDeclaration(C.kind))
7817 return 0;
7818
7819 const Decl *D = cxcursor::getCursorDecl(C);
7820 const CXXConstructorDecl *Constructor =
7821 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7822 // Passing 'false' excludes constructors marked 'explicit'.
7823 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7824}
7825
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007826unsigned clang_CXXField_isMutable(CXCursor C) {
7827 if (!clang_isDeclaration(C.kind))
7828 return 0;
7829
7830 if (const auto D = cxcursor::getCursorDecl(C))
7831 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7832 return FD->isMutable() ? 1 : 0;
7833 return 0;
7834}
7835
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007836unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7837 if (!clang_isDeclaration(C.kind))
7838 return 0;
7839
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007840 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007841 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007842 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007843 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7844}
7845
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007846unsigned clang_CXXMethod_isConst(CXCursor C) {
7847 if (!clang_isDeclaration(C.kind))
7848 return 0;
7849
7850 const Decl *D = cxcursor::getCursorDecl(C);
7851 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007852 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007853 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7854}
7855
Jonathan Coe29565352016-04-27 12:48:25 +00007856unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7857 if (!clang_isDeclaration(C.kind))
7858 return 0;
7859
7860 const Decl *D = cxcursor::getCursorDecl(C);
7861 const CXXMethodDecl *Method =
7862 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7863 return (Method && Method->isDefaulted()) ? 1 : 0;
7864}
7865
Guy Benyei11169dd2012-12-18 14:30:41 +00007866unsigned clang_CXXMethod_isStatic(CXCursor C) {
7867 if (!clang_isDeclaration(C.kind))
7868 return 0;
7869
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007870 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007871 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007872 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007873 return (Method && Method->isStatic()) ? 1 : 0;
7874}
7875
7876unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7877 if (!clang_isDeclaration(C.kind))
7878 return 0;
7879
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007880 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007881 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007882 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007883 return (Method && Method->isVirtual()) ? 1 : 0;
7884}
Guy Benyei11169dd2012-12-18 14:30:41 +00007885
Alex Lorenzff7f42e2017-07-12 11:35:11 +00007886unsigned clang_EnumDecl_isScoped(CXCursor C) {
7887 if (!clang_isDeclaration(C.kind))
7888 return 0;
7889
7890 const Decl *D = cxcursor::getCursorDecl(C);
7891 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
7892 return (Enum && Enum->isScoped()) ? 1 : 0;
7893}
7894
Guy Benyei11169dd2012-12-18 14:30:41 +00007895//===----------------------------------------------------------------------===//
7896// Attribute introspection.
7897//===----------------------------------------------------------------------===//
7898
Guy Benyei11169dd2012-12-18 14:30:41 +00007899CXType clang_getIBOutletCollectionType(CXCursor C) {
7900 if (C.kind != CXCursor_IBOutletCollectionAttr)
7901 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7902
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007903 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7905
7906 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7907}
Guy Benyei11169dd2012-12-18 14:30:41 +00007908
7909//===----------------------------------------------------------------------===//
7910// Inspecting memory usage.
7911//===----------------------------------------------------------------------===//
7912
7913typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7914
7915static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7916 enum CXTUResourceUsageKind k,
7917 unsigned long amount) {
7918 CXTUResourceUsageEntry entry = { k, amount };
7919 entries.push_back(entry);
7920}
7921
Guy Benyei11169dd2012-12-18 14:30:41 +00007922const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7923 const char *str = "";
7924 switch (kind) {
7925 case CXTUResourceUsage_AST:
7926 str = "ASTContext: expressions, declarations, and types";
7927 break;
7928 case CXTUResourceUsage_Identifiers:
7929 str = "ASTContext: identifiers";
7930 break;
7931 case CXTUResourceUsage_Selectors:
7932 str = "ASTContext: selectors";
7933 break;
7934 case CXTUResourceUsage_GlobalCompletionResults:
7935 str = "Code completion: cached global results";
7936 break;
7937 case CXTUResourceUsage_SourceManagerContentCache:
7938 str = "SourceManager: content cache allocator";
7939 break;
7940 case CXTUResourceUsage_AST_SideTables:
7941 str = "ASTContext: side tables";
7942 break;
7943 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7944 str = "SourceManager: malloc'ed memory buffers";
7945 break;
7946 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7947 str = "SourceManager: mmap'ed memory buffers";
7948 break;
7949 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7950 str = "ExternalASTSource: malloc'ed memory buffers";
7951 break;
7952 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7953 str = "ExternalASTSource: mmap'ed memory buffers";
7954 break;
7955 case CXTUResourceUsage_Preprocessor:
7956 str = "Preprocessor: malloc'ed memory";
7957 break;
7958 case CXTUResourceUsage_PreprocessingRecord:
7959 str = "Preprocessor: PreprocessingRecord";
7960 break;
7961 case CXTUResourceUsage_SourceManager_DataStructures:
7962 str = "SourceManager: data structures and tables";
7963 break;
7964 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7965 str = "Preprocessor: header search tables";
7966 break;
7967 }
7968 return str;
7969}
7970
7971CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007972 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007973 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007974 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00007975 return usage;
7976 }
7977
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007978 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00007979 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00007980 ASTContext &astContext = astUnit->getASTContext();
7981
7982 // How much memory is used by AST nodes and types?
7983 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7984 (unsigned long) astContext.getASTAllocatedMemory());
7985
7986 // How much memory is used by identifiers?
7987 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7988 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7989
7990 // How much memory is used for selectors?
7991 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7992 (unsigned long) astContext.Selectors.getTotalMemory());
7993
7994 // How much memory is used by ASTContext's side tables?
7995 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7996 (unsigned long) astContext.getSideTableAllocatedMemory());
7997
7998 // How much memory is used for caching global code completion results?
7999 unsigned long completionBytes = 0;
8000 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008001 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008002 completionBytes = completionAllocator->getTotalMemory();
8003 }
8004 createCXTUResourceUsageEntry(*entries,
8005 CXTUResourceUsage_GlobalCompletionResults,
8006 completionBytes);
8007
8008 // How much memory is being used by SourceManager's content cache?
8009 createCXTUResourceUsageEntry(*entries,
8010 CXTUResourceUsage_SourceManagerContentCache,
8011 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8012
8013 // How much memory is being used by the MemoryBuffer's in SourceManager?
8014 const SourceManager::MemoryBufferSizes &srcBufs =
8015 astUnit->getSourceManager().getMemoryBufferSizes();
8016
8017 createCXTUResourceUsageEntry(*entries,
8018 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8019 (unsigned long) srcBufs.malloc_bytes);
8020 createCXTUResourceUsageEntry(*entries,
8021 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8022 (unsigned long) srcBufs.mmap_bytes);
8023 createCXTUResourceUsageEntry(*entries,
8024 CXTUResourceUsage_SourceManager_DataStructures,
8025 (unsigned long) astContext.getSourceManager()
8026 .getDataStructureSizes());
8027
8028 // How much memory is being used by the ExternalASTSource?
8029 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8030 const ExternalASTSource::MemoryBufferSizes &sizes =
8031 esrc->getMemoryBufferSizes();
8032
8033 createCXTUResourceUsageEntry(*entries,
8034 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8035 (unsigned long) sizes.malloc_bytes);
8036 createCXTUResourceUsageEntry(*entries,
8037 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8038 (unsigned long) sizes.mmap_bytes);
8039 }
8040
8041 // How much memory is being used by the Preprocessor?
8042 Preprocessor &pp = astUnit->getPreprocessor();
8043 createCXTUResourceUsageEntry(*entries,
8044 CXTUResourceUsage_Preprocessor,
8045 pp.getTotalMemory());
8046
8047 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8048 createCXTUResourceUsageEntry(*entries,
8049 CXTUResourceUsage_PreprocessingRecord,
8050 pRec->getTotalMemory());
8051 }
8052
8053 createCXTUResourceUsageEntry(*entries,
8054 CXTUResourceUsage_Preprocessor_HeaderSearch,
8055 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008056
Guy Benyei11169dd2012-12-18 14:30:41 +00008057 CXTUResourceUsage usage = { (void*) entries.get(),
8058 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008059 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008060 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 return usage;
8062}
8063
8064void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8065 if (usage.data)
8066 delete (MemUsageEntries*) usage.data;
8067}
8068
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008069CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8070 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008071 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008072 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008073
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008074 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008075 LOG_BAD_TU(TU);
8076 return skipped;
8077 }
8078
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008079 if (!file)
8080 return skipped;
8081
8082 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8083 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8084 if (!ppRec)
8085 return skipped;
8086
8087 ASTContext &Ctx = astUnit->getASTContext();
8088 SourceManager &sm = Ctx.getSourceManager();
8089 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8090 FileID wantedFileID = sm.translateFile(fileEntry);
8091
8092 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8093 std::vector<SourceRange> wantedRanges;
8094 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8095 i != ei; ++i) {
8096 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8097 wantedRanges.push_back(*i);
8098 }
8099
8100 skipped->count = wantedRanges.size();
8101 skipped->ranges = new CXSourceRange[skipped->count];
8102 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8103 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8104
8105 return skipped;
8106}
8107
Cameron Desrochersd8091282016-08-18 15:43:55 +00008108CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8109 CXSourceRangeList *skipped = new CXSourceRangeList;
8110 skipped->count = 0;
8111 skipped->ranges = nullptr;
8112
8113 if (isNotUsableTU(TU)) {
8114 LOG_BAD_TU(TU);
8115 return skipped;
8116 }
8117
8118 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8119 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8120 if (!ppRec)
8121 return skipped;
8122
8123 ASTContext &Ctx = astUnit->getASTContext();
8124
8125 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8126
8127 skipped->count = SkippedRanges.size();
8128 skipped->ranges = new CXSourceRange[skipped->count];
8129 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8130 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8131
8132 return skipped;
8133}
8134
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008135void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8136 if (ranges) {
8137 delete[] ranges->ranges;
8138 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008139 }
8140}
8141
Guy Benyei11169dd2012-12-18 14:30:41 +00008142void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8143 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8144 for (unsigned I = 0; I != Usage.numEntries; ++I)
8145 fprintf(stderr, " %s: %lu\n",
8146 clang_getTUResourceUsageName(Usage.entries[I].kind),
8147 Usage.entries[I].amount);
8148
8149 clang_disposeCXTUResourceUsage(Usage);
8150}
8151
8152//===----------------------------------------------------------------------===//
8153// Misc. utility functions.
8154//===----------------------------------------------------------------------===//
8155
8156/// Default to using an 8 MB stack size on "safety" threads.
8157static unsigned SafetyStackThreadSize = 8 << 20;
8158
8159namespace clang {
8160
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008161bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008162 unsigned Size) {
8163 if (!Size)
8164 Size = GetSafetyThreadStackSize();
8165 if (Size)
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008166 return CRC.RunSafelyOnThread(Fn, Size);
8167 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008168}
8169
8170unsigned GetSafetyThreadStackSize() {
8171 return SafetyStackThreadSize;
8172}
8173
8174void SetSafetyThreadStackSize(unsigned Value) {
8175 SafetyStackThreadSize = Value;
8176}
8177
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008178}
Guy Benyei11169dd2012-12-18 14:30:41 +00008179
8180void clang::setThreadBackgroundPriority() {
8181 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8182 return;
8183
Alp Toker1a86ad22014-07-06 06:24:00 +00008184#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8186#endif
8187}
8188
8189void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8190 if (!Unit)
8191 return;
8192
8193 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8194 DEnd = Unit->stored_diag_end();
8195 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008196 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008197 CXString Msg = clang_formatDiagnostic(&Diag,
8198 clang_defaultDiagnosticDisplayOptions());
8199 fprintf(stderr, "%s\n", clang_getCString(Msg));
8200 clang_disposeString(Msg);
8201 }
8202#ifdef LLVM_ON_WIN32
8203 // On Windows, force a flush, since there may be multiple copies of
8204 // stderr and stdout in the file system, all with different buffers
8205 // but writing to the same device.
8206 fflush(stderr);
8207#endif
8208}
8209
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008210MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8211 SourceLocation MacroDefLoc,
8212 CXTranslationUnit TU){
8213 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008214 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008215 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008216 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008217
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008218 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008219 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008220 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008221 if (MD) {
8222 for (MacroDirective::DefInfo
8223 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8224 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8225 return Def.getMacroInfo();
8226 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008227 }
8228
Craig Topper69186e72014-06-08 08:38:04 +00008229 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008230}
8231
Richard Smith66a81862015-05-04 02:25:31 +00008232const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008233 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008234 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008235 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008236 const IdentifierInfo *II = MacroDef->getName();
8237 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008238 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008239
8240 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8241}
8242
Richard Smith66a81862015-05-04 02:25:31 +00008243MacroDefinitionRecord *
8244cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8245 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008246 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008247 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008248 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008249 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008250
8251 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008252 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008253 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8254 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008255 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008256
8257 // Check that the token is inside the definition and not its argument list.
8258 SourceManager &SM = Unit->getSourceManager();
8259 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008260 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008261 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008262 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008263
8264 Preprocessor &PP = Unit->getPreprocessor();
8265 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8266 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008267 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008268
Alp Toker2d57cea2014-05-17 04:53:25 +00008269 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008270 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008271 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008272
8273 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008274 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008275 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008276
Richard Smith20e883e2015-04-29 23:20:19 +00008277 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008278 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008279 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008280
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008281 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008282}
8283
Richard Smith66a81862015-05-04 02:25:31 +00008284MacroDefinitionRecord *
8285cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8286 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008287 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008288 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008289
8290 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008291 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008292 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008293 Preprocessor &PP = Unit->getPreprocessor();
8294 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008295 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008296 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8297 Token Tok;
8298 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008299 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008300
8301 return checkForMacroInMacroDefinition(MI, Tok, TU);
8302}
8303
Guy Benyei11169dd2012-12-18 14:30:41 +00008304CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008305 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008306}
8307
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008308Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8309 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008310 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008311 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008312 if (Unit->isMainFileAST())
8313 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008314 return *this;
8315 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008316 } else {
8317 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008318 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008319 return *this;
8320}
8321
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008322Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8323 *this << FE->getName();
8324 return *this;
8325}
8326
8327Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8328 CXString cursorName = clang_getCursorDisplayName(cursor);
8329 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8330 clang_disposeString(cursorName);
8331 return *this;
8332}
8333
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008334Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8335 CXFile File;
8336 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008337 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008338 CXString FileName = clang_getFileName(File);
8339 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8340 clang_disposeString(FileName);
8341 return *this;
8342}
8343
8344Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8345 CXSourceLocation BLoc = clang_getRangeStart(range);
8346 CXSourceLocation ELoc = clang_getRangeEnd(range);
8347
8348 CXFile BFile;
8349 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008350 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008351
8352 CXFile EFile;
8353 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008354 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008355
8356 CXString BFileName = clang_getFileName(BFile);
8357 if (BFile == EFile) {
8358 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8359 BLine, BColumn, ELine, EColumn);
8360 } else {
8361 CXString EFileName = clang_getFileName(EFile);
8362 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8363 BLine, BColumn)
8364 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8365 ELine, EColumn);
8366 clang_disposeString(EFileName);
8367 }
8368 clang_disposeString(BFileName);
8369 return *this;
8370}
8371
8372Logger &cxindex::Logger::operator<<(CXString Str) {
8373 *this << clang_getCString(Str);
8374 return *this;
8375}
8376
8377Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8378 LogOS << Fmt;
8379 return *this;
8380}
8381
Chandler Carruth37ad2582014-06-27 15:14:39 +00008382static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8383
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008384cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008385 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008386
8387 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8388
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008389 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008390 OS << "[libclang:" << Name << ':';
8391
Alp Toker1a86ad22014-07-06 06:24:00 +00008392#ifdef USE_DARWIN_THREADS
8393 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008394 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8395 OS << tid << ':';
8396#endif
8397
8398 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8399 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008400 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008401
8402 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008403 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008404 OS << "--------------------------------------------------\n";
8405 }
8406}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008407
8408#ifdef CLANG_TOOL_EXTRA_BUILD
8409// This anchor is used to force the linker to link the clang-tidy plugin.
8410extern volatile int ClangTidyPluginAnchorSource;
8411static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8412 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008413
8414// This anchor is used to force the linker to link the clang-include-fixer
8415// plugin.
8416extern volatile int ClangIncludeFixerPluginAnchorSource;
8417static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8418 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008419#endif