blob: c348506545d081f6a9d92eb20de45c1863dfb894 [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;
Alex Lorenz690f0e22017-12-07 20:37:50 +000084 D->ParsingOptions = 0;
85 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000086 return D;
87}
88
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000089bool cxtu::isASTReadError(ASTUnit *AU) {
90 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
91 DEnd = AU->stored_diag_end();
92 D != DEnd; ++D) {
93 if (D->getLevel() >= DiagnosticsEngine::Error &&
94 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
95 diag::DiagCat_AST_Deserialization_Issue)
96 return true;
97 }
98 return false;
99}
100
Guy Benyei11169dd2012-12-18 14:30:41 +0000101cxtu::CXTUOwner::~CXTUOwner() {
102 if (TU)
103 clang_disposeTranslationUnit(TU);
104}
105
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000106/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000107/// the translation unit.
108static RangeComparisonResult RangeCompare(SourceManager &SM,
109 SourceRange R1,
110 SourceRange R2) {
111 assert(R1.isValid() && "First range is invalid?");
112 assert(R2.isValid() && "Second range is invalid?");
113 if (R1.getEnd() != R2.getBegin() &&
114 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
115 return RangeBefore;
116 if (R2.getEnd() != R1.getBegin() &&
117 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
118 return RangeAfter;
119 return RangeOverlap;
120}
121
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000122/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000123/// a given source range.
124static RangeComparisonResult LocationCompare(SourceManager &SM,
125 SourceLocation L, SourceRange R) {
126 assert(R.isValid() && "First range is invalid?");
127 assert(L.isValid() && "Second range is invalid?");
128 if (L == R.getBegin() || L == R.getEnd())
129 return RangeOverlap;
130 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
131 return RangeBefore;
132 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
133 return RangeAfter;
134 return RangeOverlap;
135}
136
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000137/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000138///
139/// Clang internally represents ranges where the end location points to the
140/// start of the token at the end. However, for external clients it is more
141/// useful to have a CXSourceRange be a proper half-open interval. This routine
142/// does the appropriate translation.
143CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
144 const LangOptions &LangOpts,
145 const CharSourceRange &R) {
146 // We want the last character in this location, so we will adjust the
147 // location accordingly.
148 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000149 bool IsTokenRange = R.isTokenRange();
150 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
151 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
152 EndLoc = Expansion.getEnd();
153 IsTokenRange = Expansion.isTokenRange();
154 }
155 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000156 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
157 SM, LangOpts);
158 EndLoc = EndLoc.getLocWithOffset(Length);
159 }
160
Bill Wendlingeade3622013-01-23 08:25:41 +0000161 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000162 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000163 R.getBegin().getRawEncoding(),
164 EndLoc.getRawEncoding()
165 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000166 return Result;
167}
168
169//===----------------------------------------------------------------------===//
170// Cursor visitor.
171//===----------------------------------------------------------------------===//
172
173static SourceRange getRawCursorExtent(CXCursor C);
174static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
175
176
177RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
178 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
179}
180
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000181/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000182/// its children.
183///
184/// \param Cursor the cursor to visit.
185///
186/// \param CheckedRegionOfInterest if true, then the caller already checked
187/// that this cursor is within the region of interest.
188///
189/// \returns true if the visitation should be aborted, false if it
190/// should continue.
191bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
192 if (clang_isInvalid(Cursor.kind))
193 return false;
194
195 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000196 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000197 if (!D) {
198 assert(0 && "Invalid declaration cursor");
199 return true; // abort.
200 }
201
202 // Ignore implicit declarations, unless it's an objc method because
203 // currently we should report implicit methods for properties when indexing.
204 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
205 return false;
206 }
207
208 // If we have a range of interest, and this cursor doesn't intersect with it,
209 // we're done.
210 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
211 SourceRange Range = getRawCursorExtent(Cursor);
212 if (Range.isInvalid() || CompareRegionOfInterest(Range))
213 return false;
214 }
215
216 switch (Visitor(Cursor, Parent, ClientData)) {
217 case CXChildVisit_Break:
218 return true;
219
220 case CXChildVisit_Continue:
221 return false;
222
223 case CXChildVisit_Recurse: {
224 bool ret = VisitChildren(Cursor);
225 if (PostChildrenVisitor)
226 if (PostChildrenVisitor(Cursor, ClientData))
227 return true;
228 return ret;
229 }
230 }
231
232 llvm_unreachable("Invalid CXChildVisitResult!");
233}
234
235static bool visitPreprocessedEntitiesInRange(SourceRange R,
236 PreprocessingRecord &PPRec,
237 CursorVisitor &Visitor) {
238 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
239 FileID FID;
240
241 if (!Visitor.shouldVisitIncludedEntities()) {
242 // If the begin/end of the range lie in the same FileID, do the optimization
243 // where we skip preprocessed entities that do not come from the same FileID.
244 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
245 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
246 FID = FileID();
247 }
248
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000249 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
250 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000251 PPRec, FID);
252}
253
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000254bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000255 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000256 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000257
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000258 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000259 SourceManager &SM = Unit->getSourceManager();
260
261 std::pair<FileID, unsigned>
262 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
263 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
264
265 if (End.first != Begin.first) {
266 // If the end does not reside in the same file, try to recover by
267 // picking the end of the file of begin location.
268 End.first = Begin.first;
269 End.second = SM.getFileIDSize(Begin.first);
270 }
271
272 assert(Begin.first == End.first);
273 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000274 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000275
276 FileID File = Begin.first;
277 unsigned Offset = Begin.second;
278 unsigned Length = End.second - Begin.second;
279
280 if (!VisitDeclsOnly && !VisitPreprocessorLast)
281 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000282 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000283
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000284 if (visitDeclsFromFileRegion(File, Offset, Length))
285 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000286
287 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000288 return visitPreprocessedEntitiesInRegion();
289
290 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000291}
292
293static bool isInLexicalContext(Decl *D, DeclContext *DC) {
294 if (!DC)
295 return false;
296
297 for (DeclContext *DeclDC = D->getLexicalDeclContext();
298 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
299 if (DeclDC == DC)
300 return true;
301 }
302 return false;
303}
304
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000305bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000307 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 SourceManager &SM = Unit->getSourceManager();
309 SourceRange Range = RegionOfInterest;
310
311 SmallVector<Decl *, 16> Decls;
312 Unit->findFileRegionDecls(File, Offset, Length, Decls);
313
314 // If we didn't find any file level decls for the file, try looking at the
315 // file that it was included from.
316 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
317 bool Invalid = false;
318 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
319 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000320 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000321
322 SourceLocation Outer;
323 if (SLEntry.isFile())
324 Outer = SLEntry.getFile().getIncludeLoc();
325 else
326 Outer = SLEntry.getExpansion().getExpansionLocStart();
327 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000328 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000329
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000330 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000331 Length = 0;
332 Unit->findFileRegionDecls(File, Offset, Length, Decls);
333 }
334
335 assert(!Decls.empty());
336
337 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000338 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000339 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
340 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000341 Decl *D = *DIt;
342 if (D->getSourceRange().isInvalid())
343 continue;
344
345 if (isInLexicalContext(D, CurDC))
346 continue;
347
348 CurDC = dyn_cast<DeclContext>(D);
349
350 if (TagDecl *TD = dyn_cast<TagDecl>(D))
351 if (!TD->isFreeStanding())
352 continue;
353
354 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
355 if (CompRes == RangeBefore)
356 continue;
357 if (CompRes == RangeAfter)
358 break;
359
360 assert(CompRes == RangeOverlap);
361 VisitedAtLeastOnce = true;
362
363 if (isa<ObjCContainerDecl>(D)) {
364 FileDI_current = &DIt;
365 FileDE_current = DE;
366 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000367 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000368 }
369
370 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000371 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000372 }
373
374 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000375 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000376
377 // No Decls overlapped with the range. Move up the lexical context until there
378 // is a context that contains the range or we reach the translation unit
379 // level.
380 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
381 : (*(DIt-1))->getLexicalDeclContext();
382
383 while (DC && !DC->isTranslationUnit()) {
384 Decl *D = cast<Decl>(DC);
385 SourceRange CurDeclRange = D->getSourceRange();
386 if (CurDeclRange.isInvalid())
387 break;
388
389 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000390 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
391 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000392 }
393
394 DC = D->getLexicalDeclContext();
395 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000396
397 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000398}
399
400bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
401 if (!AU->getPreprocessor().getPreprocessingRecord())
402 return false;
403
404 PreprocessingRecord &PPRec
405 = *AU->getPreprocessor().getPreprocessingRecord();
406 SourceManager &SM = AU->getSourceManager();
407
408 if (RegionOfInterest.isValid()) {
409 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
410 SourceLocation B = MappedRange.getBegin();
411 SourceLocation E = MappedRange.getEnd();
412
413 if (AU->isInPreambleFileID(B)) {
414 if (SM.isLoadedSourceLocation(E))
415 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
416 PPRec, *this);
417
418 // Beginning of range lies in the preamble but it also extends beyond
419 // it into the main file. Split the range into 2 parts, one covering
420 // the preamble and another covering the main file. This allows subsequent
421 // calls to visitPreprocessedEntitiesInRange to accept a source range that
422 // lies in the same FileID, allowing it to skip preprocessed entities that
423 // do not come from the same FileID.
424 bool breaked =
425 visitPreprocessedEntitiesInRange(
426 SourceRange(B, AU->getEndOfPreambleFileID()),
427 PPRec, *this);
428 if (breaked) return true;
429 return visitPreprocessedEntitiesInRange(
430 SourceRange(AU->getStartOfMainFileID(), E),
431 PPRec, *this);
432 }
433
434 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
435 }
436
437 bool OnlyLocalDecls
438 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
439
440 if (OnlyLocalDecls)
441 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
442 PPRec);
443
444 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
445}
446
447template<typename InputIterator>
448bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
449 InputIterator Last,
450 PreprocessingRecord &PPRec,
451 FileID FID) {
452 for (; First != Last; ++First) {
453 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
454 continue;
455
456 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000457 if (!PPE)
458 continue;
459
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
461 if (Visit(MakeMacroExpansionCursor(ME, TU)))
462 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000463
Guy Benyei11169dd2012-12-18 14:30:41 +0000464 continue;
465 }
Richard Smith66a81862015-05-04 02:25:31 +0000466
467 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
469 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000470
Guy Benyei11169dd2012-12-18 14:30:41 +0000471 continue;
472 }
473
474 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
475 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
476 return true;
477
478 continue;
479 }
480 }
481
482 return false;
483}
484
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000485/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000486///
487/// \returns true if the visitation should be aborted, false if it
488/// should continue.
489bool CursorVisitor::VisitChildren(CXCursor Cursor) {
490 if (clang_isReference(Cursor.kind) &&
491 Cursor.kind != CXCursor_CXXBaseSpecifier) {
492 // By definition, references have no children.
493 return false;
494 }
495
496 // Set the Parent field to Cursor, then back to its old value once we're
497 // done.
498 SetParentRAII SetParent(Parent, StmtParent, Cursor);
499
500 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000501 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000502 if (!D)
503 return false;
504
505 return VisitAttributes(D) || Visit(D);
506 }
507
508 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000509 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000510 return Visit(S);
511
512 return false;
513 }
514
515 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000516 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 return Visit(E);
518
519 return false;
520 }
521
522 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000523 CXTranslationUnit TU = getCursorTU(Cursor);
524 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000525
526 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
527 for (unsigned I = 0; I != 2; ++I) {
528 if (VisitOrder[I]) {
529 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
530 RegionOfInterest.isInvalid()) {
531 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
532 TLEnd = CXXUnit->top_level_end();
533 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000534 const Optional<bool> V = handleDeclForVisitation(*TL);
535 if (!V.hasValue())
536 continue;
537 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000538 }
539 } else if (VisitDeclContext(
540 CXXUnit->getASTContext().getTranslationUnitDecl()))
541 return true;
542 continue;
543 }
544
545 // Walk the preprocessing record.
546 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
547 visitPreprocessedEntitiesInRegion();
548 }
549
550 return false;
551 }
552
553 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000554 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
556 return Visit(BaseTSInfo->getTypeLoc());
557 }
558 }
559 }
560
561 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000562 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000563 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000564 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000565 return Visit(cxcursor::MakeCursorObjCClassRef(
566 ObjT->getInterface(),
567 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000568 }
569
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000570 // If pointing inside a macro definition, check if the token is an identifier
571 // that was ever defined as a macro. In such a case, create a "pseudo" macro
572 // expansion cursor for that token.
573 SourceLocation BeginLoc = RegionOfInterest.getBegin();
574 if (Cursor.kind == CXCursor_MacroDefinition &&
575 BeginLoc == RegionOfInterest.getEnd()) {
576 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000577 const MacroInfo *MI =
578 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000579 if (MacroDefinitionRecord *MacroDef =
580 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000581 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
582 }
583
Guy Benyei11169dd2012-12-18 14:30:41 +0000584 // Nothing to visit at the moment.
585 return false;
586}
587
588bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
589 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
590 if (Visit(TSInfo->getTypeLoc()))
591 return true;
592
593 if (Stmt *Body = B->getBody())
594 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
595
596 return false;
597}
598
Ted Kremenek03325582013-02-21 01:29:01 +0000599Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000600 if (RegionOfInterest.isValid()) {
601 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
602 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000603 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000604
605 switch (CompareRegionOfInterest(Range)) {
606 case RangeBefore:
607 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000608 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000609
610 case RangeAfter:
611 // This declaration comes after the region of interest; we're done.
612 return false;
613
614 case RangeOverlap:
615 // This declaration overlaps the region of interest; visit it.
616 break;
617 }
618 }
619 return true;
620}
621
622bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
623 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
624
625 // FIXME: Eventually remove. This part of a hack to support proper
626 // iteration over all Decls contained lexically within an ObjC container.
627 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
628 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
629
630 for ( ; I != E; ++I) {
631 Decl *D = *I;
632 if (D->getLexicalDeclContext() != DC)
633 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000634 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000635 if (!V.hasValue())
636 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000637 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 }
639 return false;
640}
641
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000642Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
643 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
644
645 // Ignore synthesized ivars here, otherwise if we have something like:
646 // @synthesize prop = _prop;
647 // and '_prop' is not declared, we will encounter a '_prop' ivar before
648 // encountering the 'prop' synthesize declaration and we will think that
649 // we passed the region-of-interest.
650 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
651 if (ivarD->getSynthesize())
652 return None;
653 }
654
655 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
656 // declarations is a mismatch with the compiler semantics.
657 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
658 auto *ID = cast<ObjCInterfaceDecl>(D);
659 if (!ID->isThisDeclarationADefinition())
660 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
661
662 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
663 auto *PD = cast<ObjCProtocolDecl>(D);
664 if (!PD->isThisDeclarationADefinition())
665 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
666 }
667
668 const Optional<bool> V = shouldVisitCursor(Cursor);
669 if (!V.hasValue())
670 return None;
671 if (!V.getValue())
672 return false;
673 if (Visit(Cursor, true))
674 return true;
675 return None;
676}
677
Guy Benyei11169dd2012-12-18 14:30:41 +0000678bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
679 llvm_unreachable("Translation units are visited directly by Visit()");
680}
681
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000682bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
683 if (VisitTemplateParameters(D->getTemplateParameters()))
684 return true;
685
686 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
687}
688
Guy Benyei11169dd2012-12-18 14:30:41 +0000689bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
690 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
691 return Visit(TSInfo->getTypeLoc());
692
693 return false;
694}
695
696bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
697 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
698 return Visit(TSInfo->getTypeLoc());
699
700 return false;
701}
702
703bool CursorVisitor::VisitTagDecl(TagDecl *D) {
704 return VisitDeclContext(D);
705}
706
707bool CursorVisitor::VisitClassTemplateSpecializationDecl(
708 ClassTemplateSpecializationDecl *D) {
709 bool ShouldVisitBody = false;
710 switch (D->getSpecializationKind()) {
711 case TSK_Undeclared:
712 case TSK_ImplicitInstantiation:
713 // Nothing to visit
714 return false;
715
716 case TSK_ExplicitInstantiationDeclaration:
717 case TSK_ExplicitInstantiationDefinition:
718 break;
719
720 case TSK_ExplicitSpecialization:
721 ShouldVisitBody = true;
722 break;
723 }
724
725 // Visit the template arguments used in the specialization.
726 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
727 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000728 if (TemplateSpecializationTypeLoc TSTLoc =
729 TL.getAs<TemplateSpecializationTypeLoc>()) {
730 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
731 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 return true;
733 }
734 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000735
736 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000737}
738
739bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
740 ClassTemplatePartialSpecializationDecl *D) {
741 // FIXME: Visit the "outer" template parameter lists on the TagDecl
742 // before visiting these template parameters.
743 if (VisitTemplateParameters(D->getTemplateParameters()))
744 return true;
745
746 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000747 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
748 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
749 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000750 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
751 return true;
752
753 return VisitCXXRecordDecl(D);
754}
755
756bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
757 // Visit the default argument.
758 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
759 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
760 if (Visit(DefArg->getTypeLoc()))
761 return true;
762
763 return false;
764}
765
766bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
767 if (Expr *Init = D->getInitExpr())
768 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
769 return false;
770}
771
772bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000773 unsigned NumParamList = DD->getNumTemplateParameterLists();
774 for (unsigned i = 0; i < NumParamList; i++) {
775 TemplateParameterList* Params = DD->getTemplateParameterList(i);
776 if (VisitTemplateParameters(Params))
777 return true;
778 }
779
Guy Benyei11169dd2012-12-18 14:30:41 +0000780 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
781 if (Visit(TSInfo->getTypeLoc()))
782 return true;
783
784 // Visit the nested-name-specifier, if present.
785 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
786 if (VisitNestedNameSpecifierLoc(QualifierLoc))
787 return true;
788
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000789 return false;
790}
791
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000792static bool HasTrailingReturnType(FunctionDecl *ND) {
793 const QualType Ty = ND->getType();
794 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
795 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
796 return FT->hasTrailingReturn();
797 }
798
799 return false;
800}
801
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000802/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000803static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
804 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000805 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
806}
807
Guy Benyei11169dd2012-12-18 14:30:41 +0000808bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000809 unsigned NumParamList = ND->getNumTemplateParameterLists();
810 for (unsigned i = 0; i < NumParamList; i++) {
811 TemplateParameterList* Params = ND->getTemplateParameterList(i);
812 if (VisitTemplateParameters(Params))
813 return true;
814 }
815
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
817 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000818 // written. This requires a bit of work.
819 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
820 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000821 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000822
823 // If we have a function declared directly (without the use of a typedef),
824 // visit just the return type. Otherwise, just visit the function's type
825 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000826 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
827 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000828 (!FTL && Visit(TL)))
829 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000830
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000831 // Visit the nested-name-specifier, if present.
832 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
833 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000834 return true;
835
836 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000837 if (!isa<CXXDestructorDecl>(ND))
838 if (VisitDeclarationNameInfo(ND->getNameInfo()))
839 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000840
841 // FIXME: Visit explicitly-specified template arguments!
842
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000843 // Visit the function parameters, if we have a function type.
844 if (FTL && VisitFunctionTypeLoc(FTL, true))
845 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000846
847 // Visit the function's trailing return type.
848 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
849 return true;
850
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000851 // FIXME: Attributes?
852 }
853
Guy Benyei11169dd2012-12-18 14:30:41 +0000854 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
855 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
856 // Find the initializers that were written in the source.
857 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000858 for (auto *I : Constructor->inits()) {
859 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 continue;
861
Aaron Ballman0ad78302014-03-13 17:34:31 +0000862 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 }
864
865 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000866 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
867 &CompareCXXCtorInitializers);
868
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 // Visit the initializers in source order
870 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
871 CXXCtorInitializer *Init = WrittenInits[I];
872 if (Init->isAnyMemberInitializer()) {
873 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
874 Init->getMemberLocation(), TU)))
875 return true;
876 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
877 if (Visit(TInfo->getTypeLoc()))
878 return true;
879 }
880
881 // Visit the initializer value.
882 if (Expr *Initializer = Init->getInit())
883 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
884 return true;
885 }
886 }
887
888 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
889 return true;
890 }
891
892 return false;
893}
894
895bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
896 if (VisitDeclaratorDecl(D))
897 return true;
898
899 if (Expr *BitWidth = D->getBitWidth())
900 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
901
Benjamin Kramer99f97592017-11-15 12:20:41 +0000902 if (Expr *Init = D->getInClassInitializer())
903 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
904
Guy Benyei11169dd2012-12-18 14:30:41 +0000905 return false;
906}
907
908bool CursorVisitor::VisitVarDecl(VarDecl *D) {
909 if (VisitDeclaratorDecl(D))
910 return true;
911
912 if (Expr *Init = D->getInit())
913 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
914
915 return false;
916}
917
918bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
919 if (VisitDeclaratorDecl(D))
920 return true;
921
922 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
923 if (Expr *DefArg = D->getDefaultArgument())
924 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
925
926 return false;
927}
928
929bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
930 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
931 // before visiting these template parameters.
932 if (VisitTemplateParameters(D->getTemplateParameters()))
933 return true;
934
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000935 auto* FD = D->getTemplatedDecl();
936 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000937}
938
939bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
940 // FIXME: Visit the "outer" template parameter lists on the TagDecl
941 // before visiting these template parameters.
942 if (VisitTemplateParameters(D->getTemplateParameters()))
943 return true;
944
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000945 auto* CD = D->getTemplatedDecl();
946 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000947}
948
949bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
950 if (VisitTemplateParameters(D->getTemplateParameters()))
951 return true;
952
953 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
954 VisitTemplateArgumentLoc(D->getDefaultArgument()))
955 return true;
956
957 return false;
958}
959
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000960bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
961 // Visit the bound, if it's explicit.
962 if (D->hasExplicitBound()) {
963 if (auto TInfo = D->getTypeSourceInfo()) {
964 if (Visit(TInfo->getTypeLoc()))
965 return true;
966 }
967 }
968
969 return false;
970}
971
Guy Benyei11169dd2012-12-18 14:30:41 +0000972bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000973 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 if (Visit(TSInfo->getTypeLoc()))
975 return true;
976
David Majnemer59f77922016-06-24 04:05:48 +0000977 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000978 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 return true;
980 }
981
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000982 return ND->isThisDeclarationADefinition() &&
983 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000984}
985
986template <typename DeclIt>
987static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
988 SourceManager &SM, SourceLocation EndLoc,
989 SmallVectorImpl<Decl *> &Decls) {
990 DeclIt next = *DI_current;
991 while (++next != DE_current) {
992 Decl *D_next = *next;
993 if (!D_next)
994 break;
995 SourceLocation L = D_next->getLocStart();
996 if (!L.isValid())
997 break;
998 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
999 *DI_current = next;
1000 Decls.push_back(D_next);
1001 continue;
1002 }
1003 break;
1004 }
1005}
1006
Guy Benyei11169dd2012-12-18 14:30:41 +00001007bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1008 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1009 // an @implementation can lexically contain Decls that are not properly
1010 // nested in the AST. When we identify such cases, we need to retrofit
1011 // this nesting here.
1012 if (!DI_current && !FileDI_current)
1013 return VisitDeclContext(D);
1014
1015 // Scan the Decls that immediately come after the container
1016 // in the current DeclContext. If any fall within the
1017 // container's lexical region, stash them into a vector
1018 // for later processing.
1019 SmallVector<Decl *, 24> DeclsInContainer;
1020 SourceLocation EndLoc = D->getSourceRange().getEnd();
1021 SourceManager &SM = AU->getSourceManager();
1022 if (EndLoc.isValid()) {
1023 if (DI_current) {
1024 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1025 DeclsInContainer);
1026 } else {
1027 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1028 DeclsInContainer);
1029 }
1030 }
1031
1032 // The common case.
1033 if (DeclsInContainer.empty())
1034 return VisitDeclContext(D);
1035
1036 // Get all the Decls in the DeclContext, and sort them with the
1037 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001038 for (auto *SubDecl : D->decls()) {
1039 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1040 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001042 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001043 }
1044
1045 // Now sort the Decls so that they appear in lexical order.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001046 llvm::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1047 [&SM](Decl *A, Decl *B) {
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001048 SourceLocation L_A = A->getLocStart();
1049 SourceLocation L_B = B->getLocStart();
Mandeep Singh Grangfa51e1d2017-11-29 20:55:13 +00001050 return L_A != L_B ?
1051 SM.isBeforeInTranslationUnit(L_A, L_B) :
1052 SM.isBeforeInTranslationUnit(A->getLocEnd(), B->getLocEnd());
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001053 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001054
1055 // Now visit the decls.
1056 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1057 E = DeclsInContainer.end(); I != E; ++I) {
1058 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001059 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001060 if (!V.hasValue())
1061 continue;
1062 if (!V.getValue())
1063 return false;
1064 if (Visit(Cursor, true))
1065 return true;
1066 }
1067 return false;
1068}
1069
1070bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1071 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1072 TU)))
1073 return true;
1074
Douglas Gregore9d95f12015-07-07 03:57:35 +00001075 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1076 return true;
1077
Guy Benyei11169dd2012-12-18 14:30:41 +00001078 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1079 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1080 E = ND->protocol_end(); I != E; ++I, ++PL)
1081 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1082 return true;
1083
1084 return VisitObjCContainerDecl(ND);
1085}
1086
1087bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1088 if (!PID->isThisDeclarationADefinition())
1089 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1090
1091 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1092 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1093 E = PID->protocol_end(); I != E; ++I, ++PL)
1094 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1095 return true;
1096
1097 return VisitObjCContainerDecl(PID);
1098}
1099
1100bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1101 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1102 return true;
1103
1104 // FIXME: This implements a workaround with @property declarations also being
1105 // installed in the DeclContext for the @interface. Eventually this code
1106 // should be removed.
1107 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1108 if (!CDecl || !CDecl->IsClassExtension())
1109 return false;
1110
1111 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1112 if (!ID)
1113 return false;
1114
1115 IdentifierInfo *PropertyId = PD->getIdentifier();
1116 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001117 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1118 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001119
1120 if (!prevDecl)
1121 return false;
1122
1123 // Visit synthesized methods since they will be skipped when visiting
1124 // the @interface.
1125 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1126 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1127 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1128 return true;
1129
1130 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1131 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1132 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1133 return true;
1134
1135 return false;
1136}
1137
Douglas Gregore9d95f12015-07-07 03:57:35 +00001138bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1139 if (!typeParamList)
1140 return false;
1141
1142 for (auto *typeParam : *typeParamList) {
1143 // Visit the type parameter.
1144 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1145 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001146 }
1147
1148 return false;
1149}
1150
Guy Benyei11169dd2012-12-18 14:30:41 +00001151bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1152 if (!D->isThisDeclarationADefinition()) {
1153 // Forward declaration is treated like a reference.
1154 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1155 }
1156
Douglas Gregore9d95f12015-07-07 03:57:35 +00001157 // Objective-C type parameters.
1158 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1159 return true;
1160
Guy Benyei11169dd2012-12-18 14:30:41 +00001161 // Issue callbacks for super class.
1162 if (D->getSuperClass() &&
1163 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1164 D->getSuperClassLoc(),
1165 TU)))
1166 return true;
1167
Douglas Gregore9d95f12015-07-07 03:57:35 +00001168 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1169 if (Visit(SuperClassTInfo->getTypeLoc()))
1170 return true;
1171
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1173 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1174 E = D->protocol_end(); I != E; ++I, ++PL)
1175 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1176 return true;
1177
1178 return VisitObjCContainerDecl(D);
1179}
1180
1181bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1182 return VisitObjCContainerDecl(D);
1183}
1184
1185bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1186 // 'ID' could be null when dealing with invalid code.
1187 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1188 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1189 return true;
1190
1191 return VisitObjCImplDecl(D);
1192}
1193
1194bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1195#if 0
1196 // Issue callbacks for super class.
1197 // FIXME: No source location information!
1198 if (D->getSuperClass() &&
1199 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1200 D->getSuperClassLoc(),
1201 TU)))
1202 return true;
1203#endif
1204
1205 return VisitObjCImplDecl(D);
1206}
1207
1208bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1209 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1210 if (PD->isIvarNameSpecified())
1211 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1212
1213 return false;
1214}
1215
1216bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1217 return VisitDeclContext(D);
1218}
1219
1220bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1221 // Visit nested-name-specifier.
1222 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1223 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1224 return true;
1225
1226 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1227 D->getTargetNameLoc(), TU));
1228}
1229
1230bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1231 // Visit nested-name-specifier.
1232 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1233 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1234 return true;
1235 }
1236
1237 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1238 return true;
1239
1240 return VisitDeclarationNameInfo(D->getNameInfo());
1241}
1242
1243bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1244 // Visit nested-name-specifier.
1245 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1246 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1247 return true;
1248
1249 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1250 D->getIdentLocation(), TU));
1251}
1252
1253bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1254 // Visit nested-name-specifier.
1255 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1256 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1257 return true;
1258 }
1259
1260 return VisitDeclarationNameInfo(D->getNameInfo());
1261}
1262
1263bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1264 UnresolvedUsingTypenameDecl *D) {
1265 // Visit nested-name-specifier.
1266 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1267 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1268 return true;
1269
1270 return false;
1271}
1272
Olivier Goffart81978012016-06-09 16:15:55 +00001273bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1274 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1275 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001276 if (StringLiteral *Message = D->getMessage())
1277 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1278 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001279 return false;
1280}
1281
Olivier Goffartd211c642016-11-04 06:29:27 +00001282bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1283 if (NamedDecl *FriendD = D->getFriendDecl()) {
1284 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1285 return true;
1286 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1287 if (Visit(TI->getTypeLoc()))
1288 return true;
1289 }
1290 return false;
1291}
1292
Guy Benyei11169dd2012-12-18 14:30:41 +00001293bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1294 switch (Name.getName().getNameKind()) {
1295 case clang::DeclarationName::Identifier:
1296 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001297 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001298 case clang::DeclarationName::CXXOperatorName:
1299 case clang::DeclarationName::CXXUsingDirective:
1300 return false;
Richard Smith35845152017-02-07 01:37:30 +00001301
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 case clang::DeclarationName::CXXConstructorName:
1303 case clang::DeclarationName::CXXDestructorName:
1304 case clang::DeclarationName::CXXConversionFunctionName:
1305 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1306 return Visit(TSInfo->getTypeLoc());
1307 return false;
1308
1309 case clang::DeclarationName::ObjCZeroArgSelector:
1310 case clang::DeclarationName::ObjCOneArgSelector:
1311 case clang::DeclarationName::ObjCMultiArgSelector:
1312 // FIXME: Per-identifier location info?
1313 return false;
1314 }
1315
1316 llvm_unreachable("Invalid DeclarationName::Kind!");
1317}
1318
1319bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1320 SourceRange Range) {
1321 // FIXME: This whole routine is a hack to work around the lack of proper
1322 // source information in nested-name-specifiers (PR5791). Since we do have
1323 // a beginning source location, we can visit the first component of the
1324 // nested-name-specifier, if it's a single-token component.
1325 if (!NNS)
1326 return false;
1327
1328 // Get the first component in the nested-name-specifier.
1329 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1330 NNS = Prefix;
1331
1332 switch (NNS->getKind()) {
1333 case NestedNameSpecifier::Namespace:
1334 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1335 TU));
1336
1337 case NestedNameSpecifier::NamespaceAlias:
1338 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1339 Range.getBegin(), TU));
1340
1341 case NestedNameSpecifier::TypeSpec: {
1342 // If the type has a form where we know that the beginning of the source
1343 // range matches up with a reference cursor. Visit the appropriate reference
1344 // cursor.
1345 const Type *T = NNS->getAsType();
1346 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1347 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1348 if (const TagType *Tag = dyn_cast<TagType>(T))
1349 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1350 if (const TemplateSpecializationType *TST
1351 = dyn_cast<TemplateSpecializationType>(T))
1352 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1353 break;
1354 }
1355
1356 case NestedNameSpecifier::TypeSpecWithTemplate:
1357 case NestedNameSpecifier::Global:
1358 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001359 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 break;
1361 }
1362
1363 return false;
1364}
1365
1366bool
1367CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1368 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1369 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1370 Qualifiers.push_back(Qualifier);
1371
1372 while (!Qualifiers.empty()) {
1373 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1374 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1375 switch (NNS->getKind()) {
1376 case NestedNameSpecifier::Namespace:
1377 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1378 Q.getLocalBeginLoc(),
1379 TU)))
1380 return true;
1381
1382 break;
1383
1384 case NestedNameSpecifier::NamespaceAlias:
1385 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1386 Q.getLocalBeginLoc(),
1387 TU)))
1388 return true;
1389
1390 break;
1391
1392 case NestedNameSpecifier::TypeSpec:
1393 case NestedNameSpecifier::TypeSpecWithTemplate:
1394 if (Visit(Q.getTypeLoc()))
1395 return true;
1396
1397 break;
1398
1399 case NestedNameSpecifier::Global:
1400 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001401 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001402 break;
1403 }
1404 }
1405
1406 return false;
1407}
1408
1409bool CursorVisitor::VisitTemplateParameters(
1410 const TemplateParameterList *Params) {
1411 if (!Params)
1412 return false;
1413
1414 for (TemplateParameterList::const_iterator P = Params->begin(),
1415 PEnd = Params->end();
1416 P != PEnd; ++P) {
1417 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1418 return true;
1419 }
1420
1421 return false;
1422}
1423
1424bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1425 switch (Name.getKind()) {
1426 case TemplateName::Template:
1427 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1428
1429 case TemplateName::OverloadedTemplate:
1430 // Visit the overloaded template set.
1431 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1432 return true;
1433
1434 return false;
1435
1436 case TemplateName::DependentTemplate:
1437 // FIXME: Visit nested-name-specifier.
1438 return false;
1439
1440 case TemplateName::QualifiedTemplate:
1441 // FIXME: Visit nested-name-specifier.
1442 return Visit(MakeCursorTemplateRef(
1443 Name.getAsQualifiedTemplateName()->getDecl(),
1444 Loc, TU));
1445
1446 case TemplateName::SubstTemplateTemplateParm:
1447 return Visit(MakeCursorTemplateRef(
1448 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1449 Loc, TU));
1450
1451 case TemplateName::SubstTemplateTemplateParmPack:
1452 return Visit(MakeCursorTemplateRef(
1453 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1454 Loc, TU));
1455 }
1456
1457 llvm_unreachable("Invalid TemplateName::Kind!");
1458}
1459
1460bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1461 switch (TAL.getArgument().getKind()) {
1462 case TemplateArgument::Null:
1463 case TemplateArgument::Integral:
1464 case TemplateArgument::Pack:
1465 return false;
1466
1467 case TemplateArgument::Type:
1468 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1469 return Visit(TSInfo->getTypeLoc());
1470 return false;
1471
1472 case TemplateArgument::Declaration:
1473 if (Expr *E = TAL.getSourceDeclExpression())
1474 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1475 return false;
1476
1477 case TemplateArgument::NullPtr:
1478 if (Expr *E = TAL.getSourceNullPtrExpression())
1479 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1480 return false;
1481
1482 case TemplateArgument::Expression:
1483 if (Expr *E = TAL.getSourceExpression())
1484 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1485 return false;
1486
1487 case TemplateArgument::Template:
1488 case TemplateArgument::TemplateExpansion:
1489 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1490 return true;
1491
1492 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1493 TAL.getTemplateNameLoc());
1494 }
1495
1496 llvm_unreachable("Invalid TemplateArgument::Kind!");
1497}
1498
1499bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1500 return VisitDeclContext(D);
1501}
1502
1503bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1504 return Visit(TL.getUnqualifiedLoc());
1505}
1506
1507bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1508 ASTContext &Context = AU->getASTContext();
1509
1510 // Some builtin types (such as Objective-C's "id", "sel", and
1511 // "Class") have associated declarations. Create cursors for those.
1512 QualType VisitType;
1513 switch (TL.getTypePtr()->getKind()) {
1514
1515 case BuiltinType::Void:
1516 case BuiltinType::NullPtr:
1517 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001518#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1519 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001520#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001521 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001522 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001523 case BuiltinType::OCLClkEvent:
1524 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001525 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001526#define BUILTIN_TYPE(Id, SingletonId)
1527#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1528#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1529#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1530#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1531#include "clang/AST/BuiltinTypes.def"
1532 break;
1533
1534 case BuiltinType::ObjCId:
1535 VisitType = Context.getObjCIdType();
1536 break;
1537
1538 case BuiltinType::ObjCClass:
1539 VisitType = Context.getObjCClassType();
1540 break;
1541
1542 case BuiltinType::ObjCSel:
1543 VisitType = Context.getObjCSelType();
1544 break;
1545 }
1546
1547 if (!VisitType.isNull()) {
1548 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1549 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1550 TU));
1551 }
1552
1553 return false;
1554}
1555
1556bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1557 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1558}
1559
1560bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1561 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1562}
1563
1564bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1565 if (TL.isDefinition())
1566 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1567
1568 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1569}
1570
1571bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1572 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1573}
1574
1575bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001576 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001577}
1578
Manman Rene6be26c2016-09-13 17:25:08 +00001579bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1580 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1581 return true;
1582 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1583 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1584 TU)))
1585 return true;
1586 }
1587
1588 return false;
1589}
1590
Guy Benyei11169dd2012-12-18 14:30:41 +00001591bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1592 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1593 return true;
1594
Douglas Gregore9d95f12015-07-07 03:57:35 +00001595 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1596 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1597 return true;
1598 }
1599
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1601 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1602 TU)))
1603 return true;
1604 }
1605
1606 return false;
1607}
1608
1609bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1610 return Visit(TL.getPointeeLoc());
1611}
1612
1613bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1614 return Visit(TL.getInnerLoc());
1615}
1616
1617bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1618 return Visit(TL.getPointeeLoc());
1619}
1620
1621bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1622 return Visit(TL.getPointeeLoc());
1623}
1624
1625bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1626 return Visit(TL.getPointeeLoc());
1627}
1628
1629bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1630 return Visit(TL.getPointeeLoc());
1631}
1632
1633bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1634 return Visit(TL.getPointeeLoc());
1635}
1636
1637bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1638 return Visit(TL.getModifiedLoc());
1639}
1640
1641bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1642 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001643 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 return true;
1645
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001646 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1647 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001648 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1649 return true;
1650
1651 return false;
1652}
1653
1654bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1655 if (Visit(TL.getElementLoc()))
1656 return true;
1657
1658 if (Expr *Size = TL.getSizeExpr())
1659 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1660
1661 return false;
1662}
1663
Reid Kleckner8a365022013-06-24 17:51:48 +00001664bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1665 return Visit(TL.getOriginalLoc());
1666}
1667
Reid Kleckner0503a872013-12-05 01:23:43 +00001668bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1669 return Visit(TL.getOriginalLoc());
1670}
1671
Richard Smith600b5262017-01-26 20:40:47 +00001672bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1673 DeducedTemplateSpecializationTypeLoc TL) {
1674 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1675 TL.getTemplateNameLoc()))
1676 return true;
1677
1678 return false;
1679}
1680
Guy Benyei11169dd2012-12-18 14:30:41 +00001681bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1682 TemplateSpecializationTypeLoc TL) {
1683 // Visit the template name.
1684 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1685 TL.getTemplateNameLoc()))
1686 return true;
1687
1688 // Visit the template arguments.
1689 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1690 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1691 return true;
1692
1693 return false;
1694}
1695
1696bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1697 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1698}
1699
1700bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1701 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1702 return Visit(TSInfo->getTypeLoc());
1703
1704 return false;
1705}
1706
1707bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1708 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1709 return Visit(TSInfo->getTypeLoc());
1710
1711 return false;
1712}
1713
1714bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001715 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001716}
1717
1718bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1719 DependentTemplateSpecializationTypeLoc TL) {
1720 // Visit the nested-name-specifier, if there is one.
1721 if (TL.getQualifierLoc() &&
1722 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1723 return true;
1724
1725 // Visit the template arguments.
1726 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1727 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1728 return true;
1729
1730 return false;
1731}
1732
1733bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1734 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1735 return true;
1736
1737 return Visit(TL.getNamedTypeLoc());
1738}
1739
1740bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1741 return Visit(TL.getPatternLoc());
1742}
1743
1744bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1745 if (Expr *E = TL.getUnderlyingExpr())
1746 return Visit(MakeCXCursor(E, StmtParent, TU));
1747
1748 return false;
1749}
1750
1751bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1752 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1753}
1754
1755bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1756 return Visit(TL.getValueLoc());
1757}
1758
Xiuli Pan9c14e282016-01-09 12:53:17 +00001759bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1760 return Visit(TL.getValueLoc());
1761}
1762
Guy Benyei11169dd2012-12-18 14:30:41 +00001763#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1764bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1765 return Visit##PARENT##Loc(TL); \
1766}
1767
1768DEFAULT_TYPELOC_IMPL(Complex, Type)
1769DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1770DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1771DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1772DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001773DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001774DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1775DEFAULT_TYPELOC_IMPL(Vector, Type)
1776DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1777DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1778DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1779DEFAULT_TYPELOC_IMPL(Record, TagType)
1780DEFAULT_TYPELOC_IMPL(Enum, TagType)
1781DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1782DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1783DEFAULT_TYPELOC_IMPL(Auto, Type)
1784
1785bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1786 // Visit the nested-name-specifier, if present.
1787 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1788 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1789 return true;
1790
1791 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001792 for (const auto &I : D->bases()) {
1793 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 return true;
1795 }
1796 }
1797
1798 return VisitTagDecl(D);
1799}
1800
1801bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001802 for (const auto *I : D->attrs())
Erik Verbruggenc068e902018-04-24 08:39:46 +00001803 if (!I->isImplicit() && Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 return true;
1805
1806 return false;
1807}
1808
1809//===----------------------------------------------------------------------===//
1810// Data-recursive visitor methods.
1811//===----------------------------------------------------------------------===//
1812
1813namespace {
1814#define DEF_JOB(NAME, DATA, KIND)\
1815class NAME : public VisitorJob {\
1816public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001817 NAME(const DATA *d, CXCursor parent) : \
1818 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001819 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001820 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001821};
1822
1823DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1824DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1825DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1826DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001827DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1828DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1829DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1830#undef DEF_JOB
1831
James Y Knight04ec5bf2015-12-24 02:59:37 +00001832class ExplicitTemplateArgsVisit : public VisitorJob {
1833public:
1834 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1835 const TemplateArgumentLoc *End, CXCursor parent)
1836 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1837 End) {}
1838 static bool classof(const VisitorJob *VJ) {
1839 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1840 }
1841 const TemplateArgumentLoc *begin() const {
1842 return static_cast<const TemplateArgumentLoc *>(data[0]);
1843 }
1844 const TemplateArgumentLoc *end() {
1845 return static_cast<const TemplateArgumentLoc *>(data[1]);
1846 }
1847};
Guy Benyei11169dd2012-12-18 14:30:41 +00001848class DeclVisit : public VisitorJob {
1849public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001850 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001851 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001852 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001853 static bool classof(const VisitorJob *VJ) {
1854 return VJ->getKind() == DeclVisitKind;
1855 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001856 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001857 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001858};
1859class TypeLocVisit : public VisitorJob {
1860public:
1861 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1862 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1863 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1864
1865 static bool classof(const VisitorJob *VJ) {
1866 return VJ->getKind() == TypeLocVisitKind;
1867 }
1868
1869 TypeLoc get() const {
1870 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001871 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001872 }
1873};
1874
1875class LabelRefVisit : public VisitorJob {
1876public:
1877 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1878 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1879 labelLoc.getPtrEncoding()) {}
1880
1881 static bool classof(const VisitorJob *VJ) {
1882 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1883 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001884 const LabelDecl *get() const {
1885 return static_cast<const LabelDecl *>(data[0]);
1886 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 SourceLocation getLoc() const {
1888 return SourceLocation::getFromPtrEncoding(data[1]); }
1889};
1890
1891class NestedNameSpecifierLocVisit : public VisitorJob {
1892public:
1893 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1894 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1895 Qualifier.getNestedNameSpecifier(),
1896 Qualifier.getOpaqueData()) { }
1897
1898 static bool classof(const VisitorJob *VJ) {
1899 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1900 }
1901
1902 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001903 return NestedNameSpecifierLoc(
1904 const_cast<NestedNameSpecifier *>(
1905 static_cast<const NestedNameSpecifier *>(data[0])),
1906 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001907 }
1908};
1909
1910class DeclarationNameInfoVisit : public VisitorJob {
1911public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001912 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001913 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001914 static bool classof(const VisitorJob *VJ) {
1915 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1916 }
1917 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001918 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001919 switch (S->getStmtClass()) {
1920 default:
1921 llvm_unreachable("Unhandled Stmt");
1922 case clang::Stmt::MSDependentExistsStmtClass:
1923 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1924 case Stmt::CXXDependentScopeMemberExprClass:
1925 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1926 case Stmt::DependentScopeDeclRefExprClass:
1927 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001928 case Stmt::OMPCriticalDirectiveClass:
1929 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001930 }
1931 }
1932};
1933class MemberRefVisit : public VisitorJob {
1934public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001935 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001936 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1937 L.getPtrEncoding()) {}
1938 static bool classof(const VisitorJob *VJ) {
1939 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1940 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001941 const FieldDecl *get() const {
1942 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001943 }
1944 SourceLocation getLoc() const {
1945 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1946 }
1947};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001948class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001949 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001950 VisitorWorkList &WL;
1951 CXCursor Parent;
1952public:
1953 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1954 : WL(wl), Parent(parent) {}
1955
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001956 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1957 void VisitBlockExpr(const BlockExpr *B);
1958 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1959 void VisitCompoundStmt(const CompoundStmt *S);
1960 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1961 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1962 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1963 void VisitCXXNewExpr(const CXXNewExpr *E);
1964 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1965 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1966 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1967 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1968 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1969 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1970 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1971 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001972 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001973 void VisitDeclRefExpr(const DeclRefExpr *D);
1974 void VisitDeclStmt(const DeclStmt *S);
1975 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1976 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1977 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1978 void VisitForStmt(const ForStmt *FS);
1979 void VisitGotoStmt(const GotoStmt *GS);
1980 void VisitIfStmt(const IfStmt *If);
1981 void VisitInitListExpr(const InitListExpr *IE);
1982 void VisitMemberExpr(const MemberExpr *M);
1983 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1984 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1985 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1986 void VisitOverloadExpr(const OverloadExpr *E);
1987 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1988 void VisitStmt(const Stmt *S);
1989 void VisitSwitchStmt(const SwitchStmt *S);
1990 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001991 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1992 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1993 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1994 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1995 void VisitVAArgExpr(const VAArgExpr *E);
1996 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1997 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1998 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1999 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002000 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002001 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002002 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002003 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002004 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002005 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002006 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002007 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002008 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002009 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002010 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002011 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002012 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002013 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002014 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002015 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002016 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002017 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002018 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002019 void
2020 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002021 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002022 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002023 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002024 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002025 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002026 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002027 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002028 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002029 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002030 void
2031 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002032 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002033 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002034 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002035 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002036 void VisitOMPDistributeParallelForDirective(
2037 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002038 void VisitOMPDistributeParallelForSimdDirective(
2039 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002040 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002041 void VisitOMPTargetParallelForSimdDirective(
2042 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002043 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002044 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002045 void VisitOMPTeamsDistributeSimdDirective(
2046 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002047 void VisitOMPTeamsDistributeParallelForSimdDirective(
2048 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002049 void VisitOMPTeamsDistributeParallelForDirective(
2050 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002051 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002052 void VisitOMPTargetTeamsDistributeDirective(
2053 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002054 void VisitOMPTargetTeamsDistributeParallelForDirective(
2055 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002056 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2057 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002058 void VisitOMPTargetTeamsDistributeSimdDirective(
2059 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002060
Guy Benyei11169dd2012-12-18 14:30:41 +00002061private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002062 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002063 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002064 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2065 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002066 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2067 void AddStmt(const Stmt *S);
2068 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002069 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002070 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002071 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002072};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002073} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002074
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002075void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002076 // 'S' should always be non-null, since it comes from the
2077 // statement we are visiting.
2078 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2079}
2080
2081void
2082EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2083 if (Qualifier)
2084 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2085}
2086
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002087void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002088 if (S)
2089 WL.push_back(StmtVisit(S, Parent));
2090}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002091void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002092 if (D)
2093 WL.push_back(DeclVisit(D, Parent, isFirst));
2094}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002095void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2096 unsigned NumTemplateArgs) {
2097 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002098}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002099void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002100 if (D)
2101 WL.push_back(MemberRefVisit(D, L, Parent));
2102}
2103void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2104 if (TI)
2105 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2106 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002107void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002109 for (const Stmt *SubStmt : S->children()) {
2110 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 }
2112 if (size == WL.size())
2113 return;
2114 // Now reverse the entries we just added. This will match the DFS
2115 // ordering performed by the worklist.
2116 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2117 std::reverse(I, E);
2118}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002119namespace {
2120class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2121 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002122 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002123 template <typename T>
2124 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002125public:
2126 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2127#define OPENMP_CLAUSE(Name, Class) \
2128 void Visit##Class(const Class *C);
2129#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002130 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002131 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002132};
2133
Alexey Bataev3392d762016-02-16 11:18:12 +00002134void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2135 const OMPClauseWithPreInit *C) {
2136 Visitor->AddStmt(C->getPreInitStmt());
2137}
2138
Alexey Bataev005248a2016-02-25 05:25:57 +00002139void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2140 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002141 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002142 Visitor->AddStmt(C->getPostUpdateExpr());
2143}
2144
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002145void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002146 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002147 Visitor->AddStmt(C->getCondition());
2148}
2149
Alexey Bataev3778b602014-07-17 07:32:53 +00002150void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2151 Visitor->AddStmt(C->getCondition());
2152}
2153
Alexey Bataev568a8332014-03-06 06:15:19 +00002154void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002155 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002156 Visitor->AddStmt(C->getNumThreads());
2157}
2158
Alexey Bataev62c87d22014-03-21 04:51:18 +00002159void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2160 Visitor->AddStmt(C->getSafelen());
2161}
2162
Alexey Bataev66b15b52015-08-21 11:14:16 +00002163void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2164 Visitor->AddStmt(C->getSimdlen());
2165}
2166
Alexander Musman8bd31e62014-05-27 15:12:19 +00002167void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2168 Visitor->AddStmt(C->getNumForLoops());
2169}
2170
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002171void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002172
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002173void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2174
Alexey Bataev56dafe82014-06-20 07:16:17 +00002175void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002176 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002177 Visitor->AddStmt(C->getChunkSize());
2178}
2179
Alexey Bataev10e775f2015-07-30 11:36:16 +00002180void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2181 Visitor->AddStmt(C->getNumForLoops());
2182}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002183
Alexey Bataev236070f2014-06-20 11:19:47 +00002184void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2185
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002186void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2187
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002188void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2189
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002190void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2191
Alexey Bataevdea47612014-07-23 07:46:59 +00002192void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2193
Alexey Bataev67a4f222014-07-23 10:25:33 +00002194void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2195
Alexey Bataev459dec02014-07-24 06:46:57 +00002196void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2197
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002198void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2199
Alexey Bataev346265e2015-09-25 10:37:12 +00002200void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2201
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002202void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2203
Alexey Bataevb825de12015-12-07 10:51:44 +00002204void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2205
Michael Wonge710d542015-08-07 16:16:36 +00002206void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2207 Visitor->AddStmt(C->getDevice());
2208}
2209
Kelvin Li099bb8c2015-11-24 20:50:12 +00002210void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002211 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002212 Visitor->AddStmt(C->getNumTeams());
2213}
2214
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002215void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002216 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002217 Visitor->AddStmt(C->getThreadLimit());
2218}
2219
Alexey Bataeva0569352015-12-01 10:17:31 +00002220void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2221 Visitor->AddStmt(C->getPriority());
2222}
2223
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002224void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2225 Visitor->AddStmt(C->getGrainsize());
2226}
2227
Alexey Bataev382967a2015-12-08 12:06:20 +00002228void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2229 Visitor->AddStmt(C->getNumTasks());
2230}
2231
Alexey Bataev28c75412015-12-15 08:19:24 +00002232void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2233 Visitor->AddStmt(C->getHint());
2234}
2235
Alexey Bataev756c1962013-09-24 03:17:45 +00002236template<typename T>
2237void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002238 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002239 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002240 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002241}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002242
2243void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002244 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002245 for (const auto *E : C->private_copies()) {
2246 Visitor->AddStmt(E);
2247 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002248}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002249void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2250 const OMPFirstprivateClause *C) {
2251 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002252 VisitOMPClauseWithPreInit(C);
2253 for (const auto *E : C->private_copies()) {
2254 Visitor->AddStmt(E);
2255 }
2256 for (const auto *E : C->inits()) {
2257 Visitor->AddStmt(E);
2258 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002259}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002260void OMPClauseEnqueue::VisitOMPLastprivateClause(
2261 const OMPLastprivateClause *C) {
2262 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002263 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002264 for (auto *E : C->private_copies()) {
2265 Visitor->AddStmt(E);
2266 }
2267 for (auto *E : C->source_exprs()) {
2268 Visitor->AddStmt(E);
2269 }
2270 for (auto *E : C->destination_exprs()) {
2271 Visitor->AddStmt(E);
2272 }
2273 for (auto *E : C->assignment_ops()) {
2274 Visitor->AddStmt(E);
2275 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002276}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002277void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002278 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002279}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002280void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2281 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002282 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002283 for (auto *E : C->privates()) {
2284 Visitor->AddStmt(E);
2285 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002286 for (auto *E : C->lhs_exprs()) {
2287 Visitor->AddStmt(E);
2288 }
2289 for (auto *E : C->rhs_exprs()) {
2290 Visitor->AddStmt(E);
2291 }
2292 for (auto *E : C->reduction_ops()) {
2293 Visitor->AddStmt(E);
2294 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002295}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002296void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2297 const OMPTaskReductionClause *C) {
2298 VisitOMPClauseList(C);
2299 VisitOMPClauseWithPostUpdate(C);
2300 for (auto *E : C->privates()) {
2301 Visitor->AddStmt(E);
2302 }
2303 for (auto *E : C->lhs_exprs()) {
2304 Visitor->AddStmt(E);
2305 }
2306 for (auto *E : C->rhs_exprs()) {
2307 Visitor->AddStmt(E);
2308 }
2309 for (auto *E : C->reduction_ops()) {
2310 Visitor->AddStmt(E);
2311 }
2312}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002313void OMPClauseEnqueue::VisitOMPInReductionClause(
2314 const OMPInReductionClause *C) {
2315 VisitOMPClauseList(C);
2316 VisitOMPClauseWithPostUpdate(C);
2317 for (auto *E : C->privates()) {
2318 Visitor->AddStmt(E);
2319 }
2320 for (auto *E : C->lhs_exprs()) {
2321 Visitor->AddStmt(E);
2322 }
2323 for (auto *E : C->rhs_exprs()) {
2324 Visitor->AddStmt(E);
2325 }
2326 for (auto *E : C->reduction_ops()) {
2327 Visitor->AddStmt(E);
2328 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002329 for (auto *E : C->taskgroup_descriptors())
2330 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002331}
Alexander Musman8dba6642014-04-22 13:09:42 +00002332void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2333 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002334 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002335 for (const auto *E : C->privates()) {
2336 Visitor->AddStmt(E);
2337 }
Alexander Musman3276a272015-03-21 10:12:56 +00002338 for (const auto *E : C->inits()) {
2339 Visitor->AddStmt(E);
2340 }
2341 for (const auto *E : C->updates()) {
2342 Visitor->AddStmt(E);
2343 }
2344 for (const auto *E : C->finals()) {
2345 Visitor->AddStmt(E);
2346 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002347 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002348 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002349}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002350void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2351 VisitOMPClauseList(C);
2352 Visitor->AddStmt(C->getAlignment());
2353}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002354void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2355 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002356 for (auto *E : C->source_exprs()) {
2357 Visitor->AddStmt(E);
2358 }
2359 for (auto *E : C->destination_exprs()) {
2360 Visitor->AddStmt(E);
2361 }
2362 for (auto *E : C->assignment_ops()) {
2363 Visitor->AddStmt(E);
2364 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002365}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002366void
2367OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2368 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002369 for (auto *E : C->source_exprs()) {
2370 Visitor->AddStmt(E);
2371 }
2372 for (auto *E : C->destination_exprs()) {
2373 Visitor->AddStmt(E);
2374 }
2375 for (auto *E : C->assignment_ops()) {
2376 Visitor->AddStmt(E);
2377 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002378}
Alexey Bataev6125da92014-07-21 11:26:11 +00002379void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2380 VisitOMPClauseList(C);
2381}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002382void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2383 VisitOMPClauseList(C);
2384}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002385void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2386 VisitOMPClauseList(C);
2387}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002388void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2389 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002390 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002391 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002392}
Alexey Bataev3392d762016-02-16 11:18:12 +00002393void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2394 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002395void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2396 VisitOMPClauseList(C);
2397}
Samuel Antaoec172c62016-05-26 17:49:04 +00002398void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2399 VisitOMPClauseList(C);
2400}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002401void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2402 VisitOMPClauseList(C);
2403}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002404void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2405 VisitOMPClauseList(C);
2406}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002407}
Alexey Bataev756c1962013-09-24 03:17:45 +00002408
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002409void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2410 unsigned size = WL.size();
2411 OMPClauseEnqueue Visitor(this);
2412 Visitor.Visit(S);
2413 if (size == WL.size())
2414 return;
2415 // Now reverse the entries we just added. This will match the DFS
2416 // ordering performed by the worklist.
2417 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2418 std::reverse(I, E);
2419}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002420void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2422}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002423void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 AddDecl(B->getBlockDecl());
2425}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002426void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 EnqueueChildren(E);
2428 AddTypeLoc(E->getTypeSourceInfo());
2429}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002430void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002431 for (auto &I : llvm::reverse(S->body()))
2432 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002433}
2434void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002435VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 AddStmt(S->getSubStmt());
2437 AddDeclarationNameInfo(S);
2438 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2439 AddNestedNameSpecifierLoc(QualifierLoc);
2440}
2441
2442void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002443VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002444 if (E->hasExplicitTemplateArgs())
2445 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 AddDeclarationNameInfo(E);
2447 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2448 AddNestedNameSpecifierLoc(QualifierLoc);
2449 if (!E->isImplicitAccess())
2450 AddStmt(E->getBase());
2451}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002452void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 // Enqueue the initializer , if any.
2454 AddStmt(E->getInitializer());
2455 // Enqueue the array size, if any.
2456 AddStmt(E->getArraySize());
2457 // Enqueue the allocated type.
2458 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2459 // Enqueue the placement arguments.
2460 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2461 AddStmt(E->getPlacementArg(I-1));
2462}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002463void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2465 AddStmt(CE->getArg(I-1));
2466 AddStmt(CE->getCallee());
2467 AddStmt(CE->getArg(0));
2468}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002469void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2470 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 // Visit the name of the type being destroyed.
2472 AddTypeLoc(E->getDestroyedTypeInfo());
2473 // Visit the scope type that looks disturbingly like the nested-name-specifier
2474 // but isn't.
2475 AddTypeLoc(E->getScopeTypeInfo());
2476 // Visit the nested-name-specifier.
2477 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2478 AddNestedNameSpecifierLoc(QualifierLoc);
2479 // Visit base expression.
2480 AddStmt(E->getBase());
2481}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002482void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2483 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 AddTypeLoc(E->getTypeSourceInfo());
2485}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002486void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2487 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 EnqueueChildren(E);
2489 AddTypeLoc(E->getTypeSourceInfo());
2490}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002491void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 EnqueueChildren(E);
2493 if (E->isTypeOperand())
2494 AddTypeLoc(E->getTypeOperandSourceInfo());
2495}
2496
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002497void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2498 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 EnqueueChildren(E);
2500 AddTypeLoc(E->getTypeSourceInfo());
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 EnqueueChildren(E);
2504 if (E->isTypeOperand())
2505 AddTypeLoc(E->getTypeOperandSourceInfo());
2506}
2507
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002508void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 EnqueueChildren(S);
2510 AddDecl(S->getExceptionDecl());
2511}
2512
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002513void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002514 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002515 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002516 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002517}
2518
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002519void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002520 if (DR->hasExplicitTemplateArgs())
2521 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 WL.push_back(DeclRefExprParts(DR, Parent));
2523}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002524void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2525 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002526 if (E->hasExplicitTemplateArgs())
2527 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 AddDeclarationNameInfo(E);
2529 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2530}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002531void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 unsigned size = WL.size();
2533 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002534 for (const auto *D : S->decls()) {
2535 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 isFirst = false;
2537 }
2538 if (size == WL.size())
2539 return;
2540 // Now reverse the entries we just added. This will match the DFS
2541 // ordering performed by the worklist.
2542 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2543 std::reverse(I, E);
2544}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002545void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002547 for (const DesignatedInitExpr::Designator &D :
2548 llvm::reverse(E->designators())) {
2549 if (D.isFieldDesignator()) {
2550 if (FieldDecl *Field = D.getField())
2551 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 continue;
2553 }
David Majnemerf7e36092016-06-23 00:15:04 +00002554 if (D.isArrayDesignator()) {
2555 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 continue;
2557 }
David Majnemerf7e36092016-06-23 00:15:04 +00002558 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2559 AddStmt(E->getArrayRangeEnd(D));
2560 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 }
2562}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002563void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 EnqueueChildren(E);
2565 AddTypeLoc(E->getTypeInfoAsWritten());
2566}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002567void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 AddStmt(FS->getBody());
2569 AddStmt(FS->getInc());
2570 AddStmt(FS->getCond());
2571 AddDecl(FS->getConditionVariable());
2572 AddStmt(FS->getInit());
2573}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002574void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2576}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002577void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 AddStmt(If->getElse());
2579 AddStmt(If->getThen());
2580 AddStmt(If->getCond());
2581 AddDecl(If->getConditionVariable());
2582}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002583void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 // We care about the syntactic form of the initializer list, only.
2585 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2586 IE = Syntactic;
2587 EnqueueChildren(IE);
2588}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002589void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 WL.push_back(MemberExprParts(M, Parent));
2591
2592 // If the base of the member access expression is an implicit 'this', don't
2593 // visit it.
2594 // FIXME: If we ever want to show these implicit accesses, this will be
2595 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002596 if (M->isImplicitAccess())
2597 return;
2598
2599 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002600 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002601 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2602 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2603 if (FD->isAnonymousStructOrUnion()) {
2604 AddStmt(SubME->getBase());
2605 return;
2606 }
2607 }
2608 }
2609
2610 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002611}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002612void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 AddTypeLoc(E->getEncodedTypeSourceInfo());
2614}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002615void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 EnqueueChildren(M);
2617 AddTypeLoc(M->getClassReceiverTypeInfo());
2618}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002619void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 // Visit the components of the offsetof expression.
2621 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 const OffsetOfNode &Node = E->getComponent(I-1);
2623 switch (Node.getKind()) {
2624 case OffsetOfNode::Array:
2625 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2626 break;
2627 case OffsetOfNode::Field:
2628 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2629 break;
2630 case OffsetOfNode::Identifier:
2631 case OffsetOfNode::Base:
2632 continue;
2633 }
2634 }
2635 // Visit the type into which we're computing the offset.
2636 AddTypeLoc(E->getTypeSourceInfo());
2637}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002638void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002639 if (E->hasExplicitTemplateArgs())
2640 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 WL.push_back(OverloadExprParts(E, Parent));
2642}
2643void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002644 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 EnqueueChildren(E);
2646 if (E->isArgumentType())
2647 AddTypeLoc(E->getArgumentTypeInfo());
2648}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002649void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 EnqueueChildren(S);
2651}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002652void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 AddStmt(S->getBody());
2654 AddStmt(S->getCond());
2655 AddDecl(S->getConditionVariable());
2656}
2657
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002658void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 AddStmt(W->getBody());
2660 AddStmt(W->getCond());
2661 AddDecl(W->getConditionVariable());
2662}
2663
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002664void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 for (unsigned I = E->getNumArgs(); I > 0; --I)
2666 AddTypeLoc(E->getArg(I-1));
2667}
2668
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002669void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 AddTypeLoc(E->getQueriedTypeSourceInfo());
2671}
2672
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002673void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 EnqueueChildren(E);
2675}
2676
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002677void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 VisitOverloadExpr(U);
2679 if (!U->isImplicitAccess())
2680 AddStmt(U->getBase());
2681}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002682void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 AddStmt(E->getSubExpr());
2684 AddTypeLoc(E->getWrittenTypeInfo());
2685}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002686void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 WL.push_back(SizeOfPackExprParts(E, Parent));
2688}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002689void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 // If the opaque value has a source expression, just transparently
2691 // visit that. This is useful for (e.g.) pseudo-object expressions.
2692 if (Expr *SourceExpr = E->getSourceExpr())
2693 return Visit(SourceExpr);
2694}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002695void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 AddStmt(E->getBody());
2697 WL.push_back(LambdaExprParts(E, Parent));
2698}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002699void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 // Treat the expression like its syntactic form.
2701 Visit(E->getSyntacticForm());
2702}
2703
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002704void EnqueueVisitor::VisitOMPExecutableDirective(
2705 const OMPExecutableDirective *D) {
2706 EnqueueChildren(D);
2707 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2708 E = D->clauses().end();
2709 I != E; ++I)
2710 EnqueueChildren(*I);
2711}
2712
Alexander Musman3aaab662014-08-19 11:27:13 +00002713void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2714 VisitOMPExecutableDirective(D);
2715}
2716
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002717void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2718 VisitOMPExecutableDirective(D);
2719}
2720
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002721void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002722 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002723}
2724
Alexey Bataevf29276e2014-06-18 04:14:57 +00002725void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002726 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002727}
2728
Alexander Musmanf82886e2014-09-18 05:12:34 +00002729void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2730 VisitOMPLoopDirective(D);
2731}
2732
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002733void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2734 VisitOMPExecutableDirective(D);
2735}
2736
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002737void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2738 VisitOMPExecutableDirective(D);
2739}
2740
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002741void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2742 VisitOMPExecutableDirective(D);
2743}
2744
Alexander Musman80c22892014-07-17 08:54:58 +00002745void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2746 VisitOMPExecutableDirective(D);
2747}
2748
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002749void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2750 VisitOMPExecutableDirective(D);
2751 AddDeclarationNameInfo(D);
2752}
2753
Alexey Bataev4acb8592014-07-07 13:01:15 +00002754void
2755EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002756 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002757}
2758
Alexander Musmane4e893b2014-09-23 09:33:00 +00002759void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2760 const OMPParallelForSimdDirective *D) {
2761 VisitOMPLoopDirective(D);
2762}
2763
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002764void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2765 const OMPParallelSectionsDirective *D) {
2766 VisitOMPExecutableDirective(D);
2767}
2768
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002769void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2770 VisitOMPExecutableDirective(D);
2771}
2772
Alexey Bataev68446b72014-07-18 07:47:19 +00002773void
2774EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2775 VisitOMPExecutableDirective(D);
2776}
2777
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002778void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2779 VisitOMPExecutableDirective(D);
2780}
2781
Alexey Bataev2df347a2014-07-18 10:17:07 +00002782void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2783 VisitOMPExecutableDirective(D);
2784}
2785
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002786void EnqueueVisitor::VisitOMPTaskgroupDirective(
2787 const OMPTaskgroupDirective *D) {
2788 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002789 if (const Expr *E = D->getReductionRef())
2790 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002791}
2792
Alexey Bataev6125da92014-07-21 11:26:11 +00002793void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2794 VisitOMPExecutableDirective(D);
2795}
2796
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002797void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2798 VisitOMPExecutableDirective(D);
2799}
2800
Alexey Bataev0162e452014-07-22 10:10:35 +00002801void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2802 VisitOMPExecutableDirective(D);
2803}
2804
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002805void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2806 VisitOMPExecutableDirective(D);
2807}
2808
Michael Wong65f367f2015-07-21 13:44:28 +00002809void EnqueueVisitor::VisitOMPTargetDataDirective(const
2810 OMPTargetDataDirective *D) {
2811 VisitOMPExecutableDirective(D);
2812}
2813
Samuel Antaodf67fc42016-01-19 19:15:56 +00002814void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2815 const OMPTargetEnterDataDirective *D) {
2816 VisitOMPExecutableDirective(D);
2817}
2818
Samuel Antao72590762016-01-19 20:04:50 +00002819void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2820 const OMPTargetExitDataDirective *D) {
2821 VisitOMPExecutableDirective(D);
2822}
2823
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002824void EnqueueVisitor::VisitOMPTargetParallelDirective(
2825 const OMPTargetParallelDirective *D) {
2826 VisitOMPExecutableDirective(D);
2827}
2828
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002829void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2830 const OMPTargetParallelForDirective *D) {
2831 VisitOMPLoopDirective(D);
2832}
2833
Alexey Bataev13314bf2014-10-09 04:18:56 +00002834void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2835 VisitOMPExecutableDirective(D);
2836}
2837
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002838void EnqueueVisitor::VisitOMPCancellationPointDirective(
2839 const OMPCancellationPointDirective *D) {
2840 VisitOMPExecutableDirective(D);
2841}
2842
Alexey Bataev80909872015-07-02 11:25:17 +00002843void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2844 VisitOMPExecutableDirective(D);
2845}
2846
Alexey Bataev49f6e782015-12-01 04:18:41 +00002847void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2848 VisitOMPLoopDirective(D);
2849}
2850
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002851void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2852 const OMPTaskLoopSimdDirective *D) {
2853 VisitOMPLoopDirective(D);
2854}
2855
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002856void EnqueueVisitor::VisitOMPDistributeDirective(
2857 const OMPDistributeDirective *D) {
2858 VisitOMPLoopDirective(D);
2859}
2860
Carlo Bertolli9925f152016-06-27 14:55:37 +00002861void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2862 const OMPDistributeParallelForDirective *D) {
2863 VisitOMPLoopDirective(D);
2864}
2865
Kelvin Li4a39add2016-07-05 05:00:15 +00002866void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2867 const OMPDistributeParallelForSimdDirective *D) {
2868 VisitOMPLoopDirective(D);
2869}
2870
Kelvin Li787f3fc2016-07-06 04:45:38 +00002871void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2872 const OMPDistributeSimdDirective *D) {
2873 VisitOMPLoopDirective(D);
2874}
2875
Kelvin Lia579b912016-07-14 02:54:56 +00002876void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2877 const OMPTargetParallelForSimdDirective *D) {
2878 VisitOMPLoopDirective(D);
2879}
2880
Kelvin Li986330c2016-07-20 22:57:10 +00002881void EnqueueVisitor::VisitOMPTargetSimdDirective(
2882 const OMPTargetSimdDirective *D) {
2883 VisitOMPLoopDirective(D);
2884}
2885
Kelvin Li02532872016-08-05 14:37:37 +00002886void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2887 const OMPTeamsDistributeDirective *D) {
2888 VisitOMPLoopDirective(D);
2889}
2890
Kelvin Li4e325f72016-10-25 12:50:55 +00002891void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2892 const OMPTeamsDistributeSimdDirective *D) {
2893 VisitOMPLoopDirective(D);
2894}
2895
Kelvin Li579e41c2016-11-30 23:51:03 +00002896void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2897 const OMPTeamsDistributeParallelForSimdDirective *D) {
2898 VisitOMPLoopDirective(D);
2899}
2900
Kelvin Li7ade93f2016-12-09 03:24:30 +00002901void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2902 const OMPTeamsDistributeParallelForDirective *D) {
2903 VisitOMPLoopDirective(D);
2904}
2905
Kelvin Libf594a52016-12-17 05:48:59 +00002906void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2907 const OMPTargetTeamsDirective *D) {
2908 VisitOMPExecutableDirective(D);
2909}
2910
Kelvin Li83c451e2016-12-25 04:52:54 +00002911void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2912 const OMPTargetTeamsDistributeDirective *D) {
2913 VisitOMPLoopDirective(D);
2914}
2915
Kelvin Li80e8f562016-12-29 22:16:30 +00002916void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2917 const OMPTargetTeamsDistributeParallelForDirective *D) {
2918 VisitOMPLoopDirective(D);
2919}
2920
Kelvin Li1851df52017-01-03 05:23:48 +00002921void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2922 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2923 VisitOMPLoopDirective(D);
2924}
2925
Kelvin Lida681182017-01-10 18:08:18 +00002926void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2927 const OMPTargetTeamsDistributeSimdDirective *D) {
2928 VisitOMPLoopDirective(D);
2929}
2930
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002931void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2933}
2934
2935bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2936 if (RegionOfInterest.isValid()) {
2937 SourceRange Range = getRawCursorExtent(C);
2938 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2939 return false;
2940 }
2941 return true;
2942}
2943
2944bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2945 while (!WL.empty()) {
2946 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002947 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002948
2949 // Set the Parent field, then back to its old value once we're done.
2950 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2951
2952 switch (LI.getKind()) {
2953 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002954 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 if (!D)
2956 continue;
2957
2958 // For now, perform default visitation for Decls.
2959 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2960 cast<DeclVisit>(&LI)->isFirst())))
2961 return true;
2962
2963 continue;
2964 }
2965 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002966 for (const TemplateArgumentLoc &Arg :
2967 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2968 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002969 return true;
2970 }
2971 continue;
2972 }
2973 case VisitorJob::TypeLocVisitKind: {
2974 // Perform default visitation for TypeLocs.
2975 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2976 return true;
2977 continue;
2978 }
2979 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002980 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 if (LabelStmt *stmt = LS->getStmt()) {
2982 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2983 TU))) {
2984 return true;
2985 }
2986 }
2987 continue;
2988 }
2989
2990 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2991 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2992 if (VisitNestedNameSpecifierLoc(V->get()))
2993 return true;
2994 continue;
2995 }
2996
2997 case VisitorJob::DeclarationNameInfoVisitKind: {
2998 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2999 ->get()))
3000 return true;
3001 continue;
3002 }
3003 case VisitorJob::MemberRefVisitKind: {
3004 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3005 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3006 return true;
3007 continue;
3008 }
3009 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003010 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 if (!S)
3012 continue;
3013
3014 // Update the current cursor.
3015 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3016 if (!IsInRegionOfInterest(Cursor))
3017 continue;
3018 switch (Visitor(Cursor, Parent, ClientData)) {
3019 case CXChildVisit_Break: return true;
3020 case CXChildVisit_Continue: break;
3021 case CXChildVisit_Recurse:
3022 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003023 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 EnqueueWorkList(WL, S);
3025 break;
3026 }
3027 continue;
3028 }
3029 case VisitorJob::MemberExprPartsKind: {
3030 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003031 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003032
3033 // Visit the nested-name-specifier
3034 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3035 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3036 return true;
3037
3038 // Visit the declaration name.
3039 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3040 return true;
3041
3042 // Visit the explicitly-specified template arguments, if any.
3043 if (M->hasExplicitTemplateArgs()) {
3044 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3045 *ArgEnd = Arg + M->getNumTemplateArgs();
3046 Arg != ArgEnd; ++Arg) {
3047 if (VisitTemplateArgumentLoc(*Arg))
3048 return true;
3049 }
3050 }
3051 continue;
3052 }
3053 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003054 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 // Visit nested-name-specifier, if present.
3056 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3057 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3058 return true;
3059 // Visit declaration name.
3060 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3061 return true;
3062 continue;
3063 }
3064 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003065 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 // Visit the nested-name-specifier.
3067 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3068 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3069 return true;
3070 // Visit the declaration name.
3071 if (VisitDeclarationNameInfo(O->getNameInfo()))
3072 return true;
3073 // Visit the overloaded declaration reference.
3074 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3075 return true;
3076 continue;
3077 }
3078 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003079 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 NamedDecl *Pack = E->getPack();
3081 if (isa<TemplateTypeParmDecl>(Pack)) {
3082 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3083 E->getPackLoc(), TU)))
3084 return true;
3085
3086 continue;
3087 }
3088
3089 if (isa<TemplateTemplateParmDecl>(Pack)) {
3090 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3091 E->getPackLoc(), TU)))
3092 return true;
3093
3094 continue;
3095 }
3096
3097 // Non-type template parameter packs and function parameter packs are
3098 // treated like DeclRefExpr cursors.
3099 continue;
3100 }
3101
3102 case VisitorJob::LambdaExprPartsKind: {
3103 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003104 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3106 CEnd = E->explicit_capture_end();
3107 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003108 // FIXME: Lambda init-captures.
3109 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003111
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3113 C->getLocation(),
3114 TU)))
3115 return true;
3116 }
3117
3118 // Visit parameters and return type, if present.
3119 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3120 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3121 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3122 // Visit the whole type.
3123 if (Visit(TL))
3124 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003125 } else if (FunctionProtoTypeLoc Proto =
3126 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 if (E->hasExplicitParameters()) {
3128 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003129 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3130 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 return true;
3132 } else {
3133 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003134 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 return true;
3136 }
3137 }
3138 }
3139 break;
3140 }
3141
3142 case VisitorJob::PostChildrenVisitKind:
3143 if (PostChildrenVisitor(Parent, ClientData))
3144 return true;
3145 break;
3146 }
3147 }
3148 return false;
3149}
3150
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003151bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003152 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 if (!WorkListFreeList.empty()) {
3154 WL = WorkListFreeList.back();
3155 WL->clear();
3156 WorkListFreeList.pop_back();
3157 }
3158 else {
3159 WL = new VisitorWorkList();
3160 WorkListCache.push_back(WL);
3161 }
3162 EnqueueWorkList(*WL, S);
3163 bool result = RunVisitorWorkList(*WL);
3164 WorkListFreeList.push_back(WL);
3165 return result;
3166}
3167
3168namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003169typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003170RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3171 const DeclarationNameInfo &NI, SourceRange QLoc,
3172 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3174 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3175 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3176
3177 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3178
3179 RefNamePieces Pieces;
3180
3181 if (WantQualifier && QLoc.isValid())
3182 Pieces.push_back(QLoc);
3183
3184 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3185 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003186
3187 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3188 Pieces.push_back(*TemplateArgsLoc);
3189
Guy Benyei11169dd2012-12-18 14:30:41 +00003190 if (Kind == DeclarationName::CXXOperatorName) {
3191 Pieces.push_back(SourceLocation::getFromRawEncoding(
3192 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3193 Pieces.push_back(SourceLocation::getFromRawEncoding(
3194 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3195 }
3196
3197 if (WantSinglePiece) {
3198 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3199 Pieces.clear();
3200 Pieces.push_back(R);
3201 }
3202
3203 return Pieces;
3204}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003205}
Guy Benyei11169dd2012-12-18 14:30:41 +00003206
3207//===----------------------------------------------------------------------===//
3208// Misc. API hooks.
3209//===----------------------------------------------------------------------===//
3210
Chad Rosier05c71aa2013-03-27 18:28:23 +00003211static void fatal_error_handler(void *user_data, const std::string& reason,
3212 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 // Write the result out to stderr avoiding errs() because raw_ostreams can
3214 // call report_fatal_error.
3215 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3216 ::abort();
3217}
3218
Chandler Carruth66660742014-06-27 16:37:27 +00003219namespace {
3220struct RegisterFatalErrorHandler {
3221 RegisterFatalErrorHandler() {
3222 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3223 }
3224};
3225}
3226
3227static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3228
Guy Benyei11169dd2012-12-18 14:30:41 +00003229CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3230 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 // We use crash recovery to make some of our APIs more reliable, implicitly
3232 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003233 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3234 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003235
Chandler Carruth66660742014-06-27 16:37:27 +00003236 // Look through the managed static to trigger construction of the managed
3237 // static which registers our fatal error handler. This ensures it is only
3238 // registered once.
3239 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003240
Adrian Prantlbc068582015-07-08 01:00:30 +00003241 // Initialize targets for clang module support.
3242 llvm::InitializeAllTargets();
3243 llvm::InitializeAllTargetMCs();
3244 llvm::InitializeAllAsmPrinters();
3245 llvm::InitializeAllAsmParsers();
3246
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003247 CIndexer *CIdxr = new CIndexer();
3248
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 if (excludeDeclarationsFromPCH)
3250 CIdxr->setOnlyLocalDecls();
3251 if (displayDiagnostics)
3252 CIdxr->setDisplayDiagnostics();
3253
3254 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3255 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3256 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3257 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3258 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3259 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3260
3261 return CIdxr;
3262}
3263
3264void clang_disposeIndex(CXIndex CIdx) {
3265 if (CIdx)
3266 delete static_cast<CIndexer *>(CIdx);
3267}
3268
3269void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3270 if (CIdx)
3271 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3272}
3273
3274unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3275 if (CIdx)
3276 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3277 return 0;
3278}
3279
Alex Lorenz08615792017-12-04 21:56:36 +00003280void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3281 const char *Path) {
3282 if (CIdx)
3283 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3284}
3285
Guy Benyei11169dd2012-12-18 14:30:41 +00003286void clang_toggleCrashRecovery(unsigned isEnabled) {
3287 if (isEnabled)
3288 llvm::CrashRecoveryContext::Enable();
3289 else
3290 llvm::CrashRecoveryContext::Disable();
3291}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3294 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003295 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003296 enum CXErrorCode Result =
3297 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003298 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003299 assert((TU && Result == CXError_Success) ||
3300 (!TU && Result != CXError_Success));
3301 return TU;
3302}
3303
3304enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3305 const char *ast_filename,
3306 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003307 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003308 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003309
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003310 if (!CIdx || !ast_filename || !out_TU)
3311 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003312
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003313 LOG_FUNC_SECTION {
3314 *Log << ast_filename;
3315 }
3316
Guy Benyei11169dd2012-12-18 14:30:41 +00003317 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3318 FileSystemOptions FileSystemOpts;
3319
Justin Bognerd512c1e2014-10-15 00:33:06 +00003320 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3321 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003322 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003323 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3324 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003325 FileSystemOpts, /*UseDebugInfo=*/false,
3326 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003327 /*CaptureDiagnostics=*/true,
3328 /*AllowPCHWithCompilerErrors=*/true,
3329 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003330 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003331 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003332}
3333
3334unsigned clang_defaultEditingTranslationUnitOptions() {
3335 return CXTranslationUnit_PrecompiledPreamble |
3336 CXTranslationUnit_CacheCompletionResults;
3337}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003338
Guy Benyei11169dd2012-12-18 14:30:41 +00003339CXTranslationUnit
3340clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3341 const char *source_filename,
3342 int num_command_line_args,
3343 const char * const *command_line_args,
3344 unsigned num_unsaved_files,
3345 struct CXUnsavedFile *unsaved_files) {
3346 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3347 return clang_parseTranslationUnit(CIdx, source_filename,
3348 command_line_args, num_command_line_args,
3349 unsaved_files, num_unsaved_files,
3350 Options);
3351}
3352
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003353static CXErrorCode
3354clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3355 const char *const *command_line_args,
3356 int num_command_line_args,
3357 ArrayRef<CXUnsavedFile> unsaved_files,
3358 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003359 // Set up the initial return values.
3360 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003361 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003362
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003363 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003364 if (!CIdx || !out_TU)
3365 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003366
Guy Benyei11169dd2012-12-18 14:30:41 +00003367 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3368
3369 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3370 setThreadBackgroundPriority();
3371
3372 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003373 bool CreatePreambleOnFirstParse =
3374 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 // FIXME: Add a flag for modules.
3376 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003377 = (options & (CXTranslationUnit_Incomplete |
3378 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003379 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003380 = options & CXTranslationUnit_CacheCompletionResults;
3381 bool IncludeBriefCommentsInCodeCompletion
3382 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3383 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3384 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3385 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3386
3387 // Configure the diagnostics.
3388 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003389 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003390
Manuel Klimek016c0242016-03-01 10:56:19 +00003391 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003392 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003393
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 // Recover resources if we crash before exiting this function.
3395 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3396 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003397 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003398
Ahmed Charlesb8984322014-03-07 20:03:18 +00003399 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3400 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003401
3402 // Recover resources if we crash before exiting this function.
3403 llvm::CrashRecoveryContextCleanupRegistrar<
3404 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3405
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003406 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003407 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003408 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003409 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003410 }
3411
Ahmed Charlesb8984322014-03-07 20:03:18 +00003412 std::unique_ptr<std::vector<const char *>> Args(
3413 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003414
3415 // Recover resources if we crash before exiting this method.
3416 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3417 ArgsCleanup(Args.get());
3418
3419 // Since the Clang C library is primarily used by batch tools dealing with
3420 // (often very broken) source code, where spell-checking can have a
3421 // significant negative impact on performance (particularly when
3422 // precompiled headers are involved), we disable it by default.
3423 // Only do this if we haven't found a spell-checking-related argument.
3424 bool FoundSpellCheckingArgument = false;
3425 for (int I = 0; I != num_command_line_args; ++I) {
3426 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3427 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3428 FoundSpellCheckingArgument = true;
3429 break;
3430 }
3431 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 Args->insert(Args->end(), command_line_args,
3433 command_line_args + num_command_line_args);
3434
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003435 if (!FoundSpellCheckingArgument)
3436 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3437
Guy Benyei11169dd2012-12-18 14:30:41 +00003438 // The 'source_filename' argument is optional. If the caller does not
3439 // specify it then it is assumed that the source file is specified
3440 // in the actual argument list.
3441 // Put the source file after command_line_args otherwise if '-x' flag is
3442 // present it will be unused.
3443 if (source_filename)
3444 Args->push_back(source_filename);
3445
3446 // Do we need the detailed preprocessing record?
3447 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3448 Args->push_back("-Xclang");
3449 Args->push_back("-detailed-preprocessing-record");
3450 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003451
3452 // Suppress any editor placeholder diagnostics.
3453 Args->push_back("-fallow-editor-placeholders");
3454
Guy Benyei11169dd2012-12-18 14:30:41 +00003455 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003456 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003457 // Unless the user specified that they want the preamble on the first parse
3458 // set it up to be created on the first reparse. This makes the first parse
3459 // faster, trading for a slower (first) reparse.
3460 unsigned PrecompilePreambleAfterNParses =
3461 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003462
Alex Lorenz08615792017-12-04 21:56:36 +00003463 LibclangInvocationReporter InvocationReporter(
3464 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003465 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3466 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003467 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003468 Args->data(), Args->data() + Args->size(),
3469 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003470 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3471 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003472 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3473 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003474 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003475 /*UserFilesAreVolatile=*/true, ForSerialization,
3476 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3477 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003478
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003479 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003480 if (!Unit && !ErrUnit)
3481 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003482
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 if (NumErrors != Diags->getClient()->getNumErrors()) {
3484 // Make sure to check that 'Unit' is non-NULL.
3485 if (CXXIdx->getDisplayDiagnostics())
3486 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3487 }
3488
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003489 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3490 return CXError_ASTReadError;
3491
David Blaikieea4395e2017-01-06 19:49:01 +00003492 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003493 if (CXTranslationUnitImpl *TU = *out_TU) {
3494 TU->ParsingOptions = options;
3495 TU->Arguments.reserve(Args->size());
3496 for (const char *Arg : *Args)
3497 TU->Arguments.push_back(Arg);
3498 return CXError_Success;
3499 }
3500 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003501}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003502
3503CXTranslationUnit
3504clang_parseTranslationUnit(CXIndex CIdx,
3505 const char *source_filename,
3506 const char *const *command_line_args,
3507 int num_command_line_args,
3508 struct CXUnsavedFile *unsaved_files,
3509 unsigned num_unsaved_files,
3510 unsigned options) {
3511 CXTranslationUnit TU;
3512 enum CXErrorCode Result = clang_parseTranslationUnit2(
3513 CIdx, source_filename, command_line_args, num_command_line_args,
3514 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003515 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003516 assert((TU && Result == CXError_Success) ||
3517 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003518 return TU;
3519}
3520
3521enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003522 CXIndex CIdx, const char *source_filename,
3523 const char *const *command_line_args, int num_command_line_args,
3524 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3525 unsigned options, CXTranslationUnit *out_TU) {
3526 SmallVector<const char *, 4> Args;
3527 Args.push_back("clang");
3528 Args.append(command_line_args, command_line_args + num_command_line_args);
3529 return clang_parseTranslationUnit2FullArgv(
3530 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3531 num_unsaved_files, options, out_TU);
3532}
3533
3534enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3535 CXIndex CIdx, const char *source_filename,
3536 const char *const *command_line_args, int num_command_line_args,
3537 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3538 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003539 LOG_FUNC_SECTION {
3540 *Log << source_filename << ": ";
3541 for (int i = 0; i != num_command_line_args; ++i)
3542 *Log << command_line_args[i] << " ";
3543 }
3544
Alp Toker9d85b182014-07-07 01:23:14 +00003545 if (num_unsaved_files && !unsaved_files)
3546 return CXError_InvalidArguments;
3547
Alp Toker5c532982014-07-07 22:42:03 +00003548 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003549 auto ParseTranslationUnitImpl = [=, &result] {
3550 result = clang_parseTranslationUnit_Impl(
3551 CIdx, source_filename, command_line_args, num_command_line_args,
3552 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3553 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003554
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 llvm::CrashRecoveryContext CRC;
3556
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003557 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003558 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3559 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3560 fprintf(stderr, " 'command_line_args' : [");
3561 for (int i = 0; i != num_command_line_args; ++i) {
3562 if (i)
3563 fprintf(stderr, ", ");
3564 fprintf(stderr, "'%s'", command_line_args[i]);
3565 }
3566 fprintf(stderr, "],\n");
3567 fprintf(stderr, " 'unsaved_files' : [");
3568 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3569 if (i)
3570 fprintf(stderr, ", ");
3571 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3572 unsaved_files[i].Length);
3573 }
3574 fprintf(stderr, "],\n");
3575 fprintf(stderr, " 'options' : %d,\n", options);
3576 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003577
3578 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003580 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003581 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003582 }
Alp Toker5c532982014-07-07 22:42:03 +00003583
3584 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003585}
3586
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003587CXString clang_Type_getObjCEncoding(CXType CT) {
3588 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3589 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3590 std::string encoding;
3591 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3592 encoding);
3593
3594 return cxstring::createDup(encoding);
3595}
3596
3597static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3598 if (C.kind == CXCursor_MacroDefinition) {
3599 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3600 return MDR->getName();
3601 } else if (C.kind == CXCursor_MacroExpansion) {
3602 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3603 return ME.getName();
3604 }
3605 return nullptr;
3606}
3607
3608unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3609 const IdentifierInfo *II = getMacroIdentifier(C);
3610 if (!II) {
3611 return false;
3612 }
3613 ASTUnit *ASTU = getCursorASTUnit(C);
3614 Preprocessor &PP = ASTU->getPreprocessor();
3615 if (const MacroInfo *MI = PP.getMacroInfo(II))
3616 return MI->isFunctionLike();
3617 return false;
3618}
3619
3620unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3621 const IdentifierInfo *II = getMacroIdentifier(C);
3622 if (!II) {
3623 return false;
3624 }
3625 ASTUnit *ASTU = getCursorASTUnit(C);
3626 Preprocessor &PP = ASTU->getPreprocessor();
3627 if (const MacroInfo *MI = PP.getMacroInfo(II))
3628 return MI->isBuiltinMacro();
3629 return false;
3630}
3631
3632unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3633 const Decl *D = getCursorDecl(C);
3634 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3635 if (!FD) {
3636 return false;
3637 }
3638 return FD->isInlined();
3639}
3640
3641static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3642 if (callExpr->getNumArgs() != 1) {
3643 return nullptr;
3644 }
3645
3646 StringLiteral *S = nullptr;
3647 auto *arg = callExpr->getArg(0);
3648 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3649 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3650 auto *subExpr = I->getSubExprAsWritten();
3651
3652 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3653 return nullptr;
3654 }
3655
3656 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3657 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3658 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3659 } else {
3660 return nullptr;
3661 }
3662 return S;
3663}
3664
David Blaikie59272572016-04-13 18:23:33 +00003665struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003666 CXEvalResultKind EvalType;
3667 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003668 unsigned long long unsignedVal;
3669 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003670 double floatVal;
3671 char *stringVal;
3672 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003673 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003674 ~ExprEvalResult() {
3675 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3676 EvalType != CXEval_Int) {
3677 delete EvalData.stringVal;
3678 }
3679 }
3680};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003681
3682void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003683 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003684}
3685
3686CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3687 if (!E) {
3688 return CXEval_UnExposed;
3689 }
3690 return ((ExprEvalResult *)E)->EvalType;
3691}
3692
3693int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003694 return clang_EvalResult_getAsLongLong(E);
3695}
3696
3697long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003698 if (!E) {
3699 return 0;
3700 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003701 ExprEvalResult *Result = (ExprEvalResult*)E;
3702 if (Result->IsUnsignedInt)
3703 return Result->EvalData.unsignedVal;
3704 return Result->EvalData.intVal;
3705}
3706
3707unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3708 return ((ExprEvalResult *)E)->IsUnsignedInt;
3709}
3710
3711unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3712 if (!E) {
3713 return 0;
3714 }
3715
3716 ExprEvalResult *Result = (ExprEvalResult*)E;
3717 if (Result->IsUnsignedInt)
3718 return Result->EvalData.unsignedVal;
3719 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003720}
3721
3722double clang_EvalResult_getAsDouble(CXEvalResult E) {
3723 if (!E) {
3724 return 0;
3725 }
3726 return ((ExprEvalResult *)E)->EvalData.floatVal;
3727}
3728
3729const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3730 if (!E) {
3731 return nullptr;
3732 }
3733 return ((ExprEvalResult *)E)->EvalData.stringVal;
3734}
3735
3736static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3737 Expr::EvalResult ER;
3738 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003739 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003740 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003741
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003742 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003743 if (!expr->EvaluateAsRValue(ER, ctx))
3744 return nullptr;
3745
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003746 QualType rettype;
3747 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003748 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003749 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003750 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003751
David Blaikiebbc00882016-04-13 18:36:19 +00003752 if (ER.Val.isInt()) {
3753 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003754
3755 auto& val = ER.Val.getInt();
3756 if (val.isUnsigned()) {
3757 result->IsUnsignedInt = true;
3758 result->EvalData.unsignedVal = val.getZExtValue();
3759 } else {
3760 result->EvalData.intVal = val.getExtValue();
3761 }
3762
David Blaikiebbc00882016-04-13 18:36:19 +00003763 return result.release();
3764 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003765
David Blaikiebbc00882016-04-13 18:36:19 +00003766 if (ER.Val.isFloat()) {
3767 llvm::SmallVector<char, 100> Buffer;
3768 ER.Val.getFloat().toString(Buffer);
3769 std::string floatStr(Buffer.data(), Buffer.size());
3770 result->EvalType = CXEval_Float;
3771 bool ignored;
3772 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003773 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003774 llvm::APFloat::rmNearestTiesToEven, &ignored);
3775 result->EvalData.floatVal = apFloat.convertToDouble();
3776 return result.release();
3777 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003778
David Blaikiebbc00882016-04-13 18:36:19 +00003779 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3780 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3781 auto *subExpr = I->getSubExprAsWritten();
3782 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3783 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003784 const StringLiteral *StrE = nullptr;
3785 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003786 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003787
3788 if (ObjCExpr) {
3789 StrE = ObjCExpr->getString();
3790 result->EvalType = CXEval_ObjCStrLiteral;
3791 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003792 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003793 result->EvalType = CXEval_StrLiteral;
3794 }
3795
3796 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003797 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003798 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3799 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003800 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003801 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003802 }
3803 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3804 expr->getStmtClass() == Stmt::StringLiteralClass) {
3805 const StringLiteral *StrE = nullptr;
3806 const ObjCStringLiteral *ObjCExpr;
3807 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003808
David Blaikiebbc00882016-04-13 18:36:19 +00003809 if (ObjCExpr) {
3810 StrE = ObjCExpr->getString();
3811 result->EvalType = CXEval_ObjCStrLiteral;
3812 } else {
3813 StrE = cast<StringLiteral>(expr);
3814 result->EvalType = CXEval_StrLiteral;
3815 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003816
David Blaikiebbc00882016-04-13 18:36:19 +00003817 std::string strRef(StrE->getString().str());
3818 result->EvalData.stringVal = new char[strRef.size() + 1];
3819 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3820 result->EvalData.stringVal[strRef.size()] = '\0';
3821 return result.release();
3822 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003823
David Blaikiebbc00882016-04-13 18:36:19 +00003824 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3825 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003826
David Blaikiebbc00882016-04-13 18:36:19 +00003827 rettype = CC->getType();
3828 if (rettype.getAsString() == "CFStringRef" &&
3829 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003830
David Blaikiebbc00882016-04-13 18:36:19 +00003831 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3832 StringLiteral *S = getCFSTR_value(callExpr);
3833 if (S) {
3834 std::string strLiteral(S->getString().str());
3835 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003836
David Blaikiebbc00882016-04-13 18:36:19 +00003837 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3838 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3839 strLiteral.size());
3840 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003841 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003842 }
3843 }
3844
David Blaikiebbc00882016-04-13 18:36:19 +00003845 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3846 callExpr = static_cast<CallExpr *>(expr);
3847 rettype = callExpr->getCallReturnType(ctx);
3848
3849 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3850 return nullptr;
3851
3852 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3853 if (callExpr->getNumArgs() == 1 &&
3854 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3855 return nullptr;
3856 } else if (rettype.getAsString() == "CFStringRef") {
3857
3858 StringLiteral *S = getCFSTR_value(callExpr);
3859 if (S) {
3860 std::string strLiteral(S->getString().str());
3861 result->EvalType = CXEval_CFStr;
3862 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3863 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3864 strLiteral.size());
3865 result->EvalData.stringVal[strLiteral.size()] = '\0';
3866 return result.release();
3867 }
3868 }
3869 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3870 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3871 ValueDecl *V = D->getDecl();
3872 if (V->getKind() == Decl::Function) {
3873 std::string strName = V->getNameAsString();
3874 result->EvalType = CXEval_Other;
3875 result->EvalData.stringVal = new char[strName.size() + 1];
3876 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3877 result->EvalData.stringVal[strName.size()] = '\0';
3878 return result.release();
3879 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003880 }
3881
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003882 return nullptr;
3883}
3884
3885CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3886 const Decl *D = getCursorDecl(C);
3887 if (D) {
3888 const Expr *expr = nullptr;
3889 if (auto *Var = dyn_cast<VarDecl>(D)) {
3890 expr = Var->getInit();
3891 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3892 expr = Field->getInClassInitializer();
3893 }
3894 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003895 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3896 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003897 return nullptr;
3898 }
3899
3900 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3901 if (compoundStmt) {
3902 Expr *expr = nullptr;
3903 for (auto *bodyIterator : compoundStmt->body()) {
3904 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3905 break;
3906 }
3907 }
3908 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003909 return const_cast<CXEvalResult>(
3910 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003911 }
3912 return nullptr;
3913}
3914
3915unsigned clang_Cursor_hasAttrs(CXCursor C) {
3916 const Decl *D = getCursorDecl(C);
3917 if (!D) {
3918 return 0;
3919 }
3920
3921 if (D->hasAttrs()) {
3922 return 1;
3923 }
3924
3925 return 0;
3926}
Guy Benyei11169dd2012-12-18 14:30:41 +00003927unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3928 return CXSaveTranslationUnit_None;
3929}
3930
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003931static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3932 const char *FileName,
3933 unsigned options) {
3934 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003935 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3936 setThreadBackgroundPriority();
3937
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003938 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3939 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003940}
3941
3942int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3943 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003944 LOG_FUNC_SECTION {
3945 *Log << TU << ' ' << FileName;
3946 }
3947
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003948 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003949 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003951 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003952
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003953 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003954 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3955 if (!CXXUnit->hasSema())
3956 return CXSaveError_InvalidTU;
3957
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003958 CXSaveError result;
3959 auto SaveTranslationUnitImpl = [=, &result]() {
3960 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3961 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003962
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003963 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003964 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003965
3966 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3967 PrintLibclangResourceUsage(TU);
3968
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003969 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 }
3971
3972 // We have an AST that has invalid nodes due to compiler errors.
3973 // Use a crash recovery thread for protection.
3974
3975 llvm::CrashRecoveryContext CRC;
3976
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003977 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3979 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3980 fprintf(stderr, " 'options' : %d,\n", options);
3981 fprintf(stderr, "}\n");
3982
3983 return CXSaveError_Unknown;
3984
3985 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3986 PrintLibclangResourceUsage(TU);
3987 }
3988
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003989 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003990}
3991
3992void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3993 if (CTUnit) {
3994 // If the translation unit has been marked as unsafe to free, just discard
3995 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003996 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3997 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 return;
3999
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004000 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004001 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4003 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004004 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 delete CTUnit;
4006 }
4007}
4008
Erik Verbruggen346066b2017-05-30 14:25:54 +00004009unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4010 if (CTUnit) {
4011 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4012
4013 if (Unit && Unit->isUnsafeToFree())
4014 return false;
4015
4016 Unit->ResetForParse();
4017 return true;
4018 }
4019
4020 return false;
4021}
4022
Guy Benyei11169dd2012-12-18 14:30:41 +00004023unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4024 return CXReparse_None;
4025}
4026
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004027static CXErrorCode
4028clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4029 ArrayRef<CXUnsavedFile> unsaved_files,
4030 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004031 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004032 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004033 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004034 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004035 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004036
4037 // Reset the associated diagnostics.
4038 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004039 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004040
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004041 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4043 setThreadBackgroundPriority();
4044
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004045 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004047
4048 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4049 new std::vector<ASTUnit::RemappedFile>());
4050
Guy Benyei11169dd2012-12-18 14:30:41 +00004051 // Recover resources if we crash before exiting this function.
4052 llvm::CrashRecoveryContextCleanupRegistrar<
4053 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004054
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004055 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004056 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004057 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004058 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004060
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004061 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4062 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004063 return CXError_Success;
4064 if (isASTReadError(CXXUnit))
4065 return CXError_ASTReadError;
4066 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004067}
4068
4069int clang_reparseTranslationUnit(CXTranslationUnit TU,
4070 unsigned num_unsaved_files,
4071 struct CXUnsavedFile *unsaved_files,
4072 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004073 LOG_FUNC_SECTION {
4074 *Log << TU;
4075 }
4076
Alp Toker9d85b182014-07-07 01:23:14 +00004077 if (num_unsaved_files && !unsaved_files)
4078 return CXError_InvalidArguments;
4079
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004080 CXErrorCode result;
4081 auto ReparseTranslationUnitImpl = [=, &result]() {
4082 result = clang_reparseTranslationUnit_Impl(
4083 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4084 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004085
Guy Benyei11169dd2012-12-18 14:30:41 +00004086 llvm::CrashRecoveryContext CRC;
4087
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004088 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004089 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004090 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004091 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004092 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4093 PrintLibclangResourceUsage(TU);
4094
Alp Toker5c532982014-07-07 22:42:03 +00004095 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004096}
4097
4098
4099CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004100 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004101 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004102 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004103 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004104
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004105 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004106 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004107}
4108
4109CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004110 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004111 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004112 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004113 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004114
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004115 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004116 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4117}
4118
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004119CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4120 if (isNotUsableTU(CTUnit)) {
4121 LOG_BAD_TU(CTUnit);
4122 return nullptr;
4123 }
4124
4125 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4126 impl->TranslationUnit = CTUnit;
4127 return impl;
4128}
4129
4130CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4131 if (!TargetInfo)
4132 return cxstring::createEmpty();
4133
4134 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4135 assert(!isNotUsableTU(CTUnit) &&
4136 "Unexpected unusable translation unit in TargetInfo");
4137
4138 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4139 std::string Triple =
4140 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4141 return cxstring::createDup(Triple);
4142}
4143
4144int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4145 if (!TargetInfo)
4146 return -1;
4147
4148 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4149 assert(!isNotUsableTU(CTUnit) &&
4150 "Unexpected unusable translation unit in TargetInfo");
4151
4152 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4153 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4154}
4155
4156void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4157 if (!TargetInfo)
4158 return;
4159
4160 delete TargetInfo;
4161}
4162
Guy Benyei11169dd2012-12-18 14:30:41 +00004163//===----------------------------------------------------------------------===//
4164// CXFile Operations.
4165//===----------------------------------------------------------------------===//
4166
Guy Benyei11169dd2012-12-18 14:30:41 +00004167CXString clang_getFileName(CXFile SFile) {
4168 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004169 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004170
4171 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004172 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004173}
4174
4175time_t clang_getFileTime(CXFile SFile) {
4176 if (!SFile)
4177 return 0;
4178
4179 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4180 return FEnt->getModificationTime();
4181}
4182
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004183CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004184 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004185 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004186 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004187 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004188
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004189 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004190
4191 FileManager &FMgr = CXXUnit->getFileManager();
4192 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4193}
4194
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004195const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4196 size_t *size) {
4197 if (isNotUsableTU(TU)) {
4198 LOG_BAD_TU(TU);
4199 return nullptr;
4200 }
4201
4202 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4203 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4204 bool Invalid = true;
4205 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4206 if (Invalid) {
4207 if (size)
4208 *size = 0;
4209 return nullptr;
4210 }
4211 if (size)
4212 *size = buf->getBufferSize();
4213 return buf->getBufferStart();
4214}
4215
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004216unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4217 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004218 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004219 LOG_BAD_TU(TU);
4220 return 0;
4221 }
4222
4223 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 return 0;
4225
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004226 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 FileEntry *FEnt = static_cast<FileEntry *>(file);
4228 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4229 .isFileMultipleIncludeGuarded(FEnt);
4230}
4231
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004232int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4233 if (!file || !outID)
4234 return 1;
4235
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004236 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004237 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4238 outID->data[0] = ID.getDevice();
4239 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004240 outID->data[2] = FEnt->getModificationTime();
4241 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004242}
4243
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004244int clang_File_isEqual(CXFile file1, CXFile file2) {
4245 if (file1 == file2)
4246 return true;
4247
4248 if (!file1 || !file2)
4249 return false;
4250
4251 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4252 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4253 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4254}
4255
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004256CXString clang_File_tryGetRealPathName(CXFile SFile) {
4257 if (!SFile)
4258 return cxstring::createNull();
4259
4260 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4261 return cxstring::createRef(FEnt->tryGetRealPathName());
4262}
4263
Guy Benyei11169dd2012-12-18 14:30:41 +00004264//===----------------------------------------------------------------------===//
4265// CXCursor Operations.
4266//===----------------------------------------------------------------------===//
4267
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004268static const Decl *getDeclFromExpr(const Stmt *E) {
4269 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 return getDeclFromExpr(CE->getSubExpr());
4271
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004272 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004274 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004276 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004278 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 if (PRE->isExplicitProperty())
4280 return PRE->getExplicitProperty();
4281 // It could be messaging both getter and setter as in:
4282 // ++myobj.myprop;
4283 // in which case prefer to associate the setter since it is less obvious
4284 // from inspecting the source that the setter is going to get called.
4285 if (PRE->isMessagingSetter())
4286 return PRE->getImplicitPropertySetter();
4287 return PRE->getImplicitPropertyGetter();
4288 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004289 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004291 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 if (Expr *Src = OVE->getSourceExpr())
4293 return getDeclFromExpr(Src);
4294
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004295 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004297 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 if (!CE->isElidable())
4299 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004300 if (const CXXInheritedCtorInitExpr *CE =
4301 dyn_cast<CXXInheritedCtorInitExpr>(E))
4302 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004303 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 return OME->getMethodDecl();
4305
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004306 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004308 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4310 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004311 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4313 isa<ParmVarDecl>(SizeOfPack->getPack()))
4314 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004315
4316 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004317}
4318
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004319static SourceLocation getLocationFromExpr(const Expr *E) {
4320 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 return getLocationFromExpr(CE->getSubExpr());
4322
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004323 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004325 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004327 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004329 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004331 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004333 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 return PropRef->getLocation();
4335
4336 return E->getLocStart();
4337}
4338
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004339extern "C" {
4340
Guy Benyei11169dd2012-12-18 14:30:41 +00004341unsigned clang_visitChildren(CXCursor parent,
4342 CXCursorVisitor visitor,
4343 CXClientData client_data) {
4344 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4345 /*VisitPreprocessorLast=*/false);
4346 return CursorVis.VisitChildren(parent);
4347}
4348
4349#ifndef __has_feature
4350#define __has_feature(x) 0
4351#endif
4352#if __has_feature(blocks)
4353typedef enum CXChildVisitResult
4354 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4355
4356static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4357 CXClientData client_data) {
4358 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4359 return block(cursor, parent);
4360}
4361#else
4362// If we are compiled with a compiler that doesn't have native blocks support,
4363// define and call the block manually, so the
4364typedef struct _CXChildVisitResult
4365{
4366 void *isa;
4367 int flags;
4368 int reserved;
4369 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4370 CXCursor);
4371} *CXCursorVisitorBlock;
4372
4373static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4374 CXClientData client_data) {
4375 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4376 return block->invoke(block, cursor, parent);
4377}
4378#endif
4379
4380
4381unsigned clang_visitChildrenWithBlock(CXCursor parent,
4382 CXCursorVisitorBlock block) {
4383 return clang_visitChildren(parent, visitWithBlock, block);
4384}
4385
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004386static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004388 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004389
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004390 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004392 if (const ObjCPropertyImplDecl *PropImpl =
4393 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004395 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004396
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004397 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004399 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004400
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004401 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 }
4403
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004404 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004405 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004406
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004407 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004408 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4409 // and returns different names. NamedDecl returns the class name and
4410 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004411 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004412
4413 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004414 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004415
4416 SmallString<1024> S;
4417 llvm::raw_svector_ostream os(S);
4418 ND->printName(os);
4419
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004420 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004421}
4422
4423CXString clang_getCursorSpelling(CXCursor C) {
4424 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004425 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004426
4427 if (clang_isReference(C.kind)) {
4428 switch (C.kind) {
4429 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004430 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004431 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 }
4433 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004434 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004435 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 }
4437 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004438 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004440 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 }
4442 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004443 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004444 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 }
4446 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004447 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 assert(Type && "Missing type decl");
4449
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004450 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 getAsString());
4452 }
4453 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004454 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 assert(Template && "Missing template decl");
4456
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004457 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 }
4459
4460 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004461 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 assert(NS && "Missing namespace decl");
4463
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004464 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 }
4466
4467 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004468 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 assert(Field && "Missing member decl");
4470
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004471 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 }
4473
4474 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004475 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 assert(Label && "Missing label");
4477
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004478 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 }
4480
4481 case CXCursor_OverloadedDeclRef: {
4482 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004483 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4484 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004485 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004486 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004488 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004489 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 OverloadedTemplateStorage *Ovl
4491 = Storage.get<OverloadedTemplateStorage*>();
4492 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004493 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004494 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 }
4496
4497 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004498 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 assert(Var && "Missing variable decl");
4500
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004501 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 }
4503
4504 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004505 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 }
4507 }
4508
4509 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004510 const Expr *E = getCursorExpr(C);
4511
4512 if (C.kind == CXCursor_ObjCStringLiteral ||
4513 C.kind == CXCursor_StringLiteral) {
4514 const StringLiteral *SLit;
4515 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4516 SLit = OSL->getString();
4517 } else {
4518 SLit = cast<StringLiteral>(E);
4519 }
4520 SmallString<256> Buf;
4521 llvm::raw_svector_ostream OS(Buf);
4522 SLit->outputString(OS);
4523 return cxstring::createDup(OS.str());
4524 }
4525
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004526 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 if (D)
4528 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004529 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 }
4531
4532 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004533 const Stmt *S = getCursorStmt(C);
4534 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004535 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004536
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004537 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 }
4539
4540 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004541 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 ->getNameStart());
4543
4544 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004545 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 ->getNameStart());
4547
4548 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004549 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004550
4551 if (clang_isDeclaration(C.kind))
4552 return getDeclSpelling(getCursorDecl(C));
4553
4554 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004555 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004556 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 }
4558
4559 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004560 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004561 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004562 }
4563
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004564 if (C.kind == CXCursor_PackedAttr) {
4565 return cxstring::createRef("packed");
4566 }
4567
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004568 if (C.kind == CXCursor_VisibilityAttr) {
4569 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4570 switch (AA->getVisibility()) {
4571 case VisibilityAttr::VisibilityType::Default:
4572 return cxstring::createRef("default");
4573 case VisibilityAttr::VisibilityType::Hidden:
4574 return cxstring::createRef("hidden");
4575 case VisibilityAttr::VisibilityType::Protected:
4576 return cxstring::createRef("protected");
4577 }
4578 llvm_unreachable("unknown visibility type");
4579 }
4580
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004581 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004582}
4583
4584CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4585 unsigned pieceIndex,
4586 unsigned options) {
4587 if (clang_Cursor_isNull(C))
4588 return clang_getNullRange();
4589
4590 ASTContext &Ctx = getCursorContext(C);
4591
4592 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004593 const Stmt *S = getCursorStmt(C);
4594 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 if (pieceIndex > 0)
4596 return clang_getNullRange();
4597 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4598 }
4599
4600 return clang_getNullRange();
4601 }
4602
4603 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004604 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4606 if (pieceIndex >= ME->getNumSelectorLocs())
4607 return clang_getNullRange();
4608 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4609 }
4610 }
4611
4612 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4613 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004614 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4616 if (pieceIndex >= MD->getNumSelectorLocs())
4617 return clang_getNullRange();
4618 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4619 }
4620 }
4621
4622 if (C.kind == CXCursor_ObjCCategoryDecl ||
4623 C.kind == CXCursor_ObjCCategoryImplDecl) {
4624 if (pieceIndex > 0)
4625 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004626 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4628 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004629 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4631 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4632 }
4633
4634 if (C.kind == CXCursor_ModuleImportDecl) {
4635 if (pieceIndex > 0)
4636 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004637 if (const ImportDecl *ImportD =
4638 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4640 if (!Locs.empty())
4641 return cxloc::translateSourceRange(Ctx,
4642 SourceRange(Locs.front(), Locs.back()));
4643 }
4644 return clang_getNullRange();
4645 }
4646
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004647 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004648 C.kind == CXCursor_ConversionFunction ||
4649 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004650 if (pieceIndex > 0)
4651 return clang_getNullRange();
4652 if (const FunctionDecl *FD =
4653 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4654 DeclarationNameInfo FunctionName = FD->getNameInfo();
4655 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4656 }
4657 return clang_getNullRange();
4658 }
4659
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 // FIXME: A CXCursor_InclusionDirective should give the location of the
4661 // filename, but we don't keep track of this.
4662
4663 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4664 // but we don't keep track of this.
4665
4666 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4667 // but we don't keep track of this.
4668
4669 // Default handling, give the location of the cursor.
4670
4671 if (pieceIndex > 0)
4672 return clang_getNullRange();
4673
4674 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4675 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4676 return cxloc::translateSourceRange(Ctx, Loc);
4677}
4678
Eli Bendersky44a206f2014-07-31 18:04:56 +00004679CXString clang_Cursor_getMangling(CXCursor C) {
4680 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4681 return cxstring::createEmpty();
4682
Eli Bendersky44a206f2014-07-31 18:04:56 +00004683 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004684 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004685 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4686 return cxstring::createEmpty();
4687
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004688 ASTContext &Ctx = D->getASTContext();
4689 index::CodegenNameGenerator CGNameGen(Ctx);
4690 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004691}
4692
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004693CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4694 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4695 return nullptr;
4696
4697 const Decl *D = getCursorDecl(C);
4698 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4699 return nullptr;
4700
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004701 ASTContext &Ctx = D->getASTContext();
4702 index::CodegenNameGenerator CGNameGen(Ctx);
4703 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004704 return cxstring::createSet(Manglings);
4705}
4706
Dave Lee1a532c92017-09-22 16:58:57 +00004707CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4708 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4709 return nullptr;
4710
4711 const Decl *D = getCursorDecl(C);
4712 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4713 return nullptr;
4714
4715 ASTContext &Ctx = D->getASTContext();
4716 index::CodegenNameGenerator CGNameGen(Ctx);
4717 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4718 return cxstring::createSet(Manglings);
4719}
4720
Jonathan Coe45ef5032018-01-16 10:19:56 +00004721CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4722 if (clang_Cursor_isNull(C))
4723 return 0;
4724 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4725}
4726
4727void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4728 if (Policy)
4729 delete static_cast<PrintingPolicy *>(Policy);
4730}
4731
4732unsigned
4733clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4734 enum CXPrintingPolicyProperty Property) {
4735 if (!Policy)
4736 return 0;
4737
4738 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4739 switch (Property) {
4740 case CXPrintingPolicy_Indentation:
4741 return P->Indentation;
4742 case CXPrintingPolicy_SuppressSpecifiers:
4743 return P->SuppressSpecifiers;
4744 case CXPrintingPolicy_SuppressTagKeyword:
4745 return P->SuppressTagKeyword;
4746 case CXPrintingPolicy_IncludeTagDefinition:
4747 return P->IncludeTagDefinition;
4748 case CXPrintingPolicy_SuppressScope:
4749 return P->SuppressScope;
4750 case CXPrintingPolicy_SuppressUnwrittenScope:
4751 return P->SuppressUnwrittenScope;
4752 case CXPrintingPolicy_SuppressInitializers:
4753 return P->SuppressInitializers;
4754 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4755 return P->ConstantArraySizeAsWritten;
4756 case CXPrintingPolicy_AnonymousTagLocations:
4757 return P->AnonymousTagLocations;
4758 case CXPrintingPolicy_SuppressStrongLifetime:
4759 return P->SuppressStrongLifetime;
4760 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4761 return P->SuppressLifetimeQualifiers;
4762 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4763 return P->SuppressTemplateArgsInCXXConstructors;
4764 case CXPrintingPolicy_Bool:
4765 return P->Bool;
4766 case CXPrintingPolicy_Restrict:
4767 return P->Restrict;
4768 case CXPrintingPolicy_Alignof:
4769 return P->Alignof;
4770 case CXPrintingPolicy_UnderscoreAlignof:
4771 return P->UnderscoreAlignof;
4772 case CXPrintingPolicy_UseVoidForZeroParams:
4773 return P->UseVoidForZeroParams;
4774 case CXPrintingPolicy_TerseOutput:
4775 return P->TerseOutput;
4776 case CXPrintingPolicy_PolishForDeclaration:
4777 return P->PolishForDeclaration;
4778 case CXPrintingPolicy_Half:
4779 return P->Half;
4780 case CXPrintingPolicy_MSWChar:
4781 return P->MSWChar;
4782 case CXPrintingPolicy_IncludeNewlines:
4783 return P->IncludeNewlines;
4784 case CXPrintingPolicy_MSVCFormatting:
4785 return P->MSVCFormatting;
4786 case CXPrintingPolicy_ConstantsAsWritten:
4787 return P->ConstantsAsWritten;
4788 case CXPrintingPolicy_SuppressImplicitBase:
4789 return P->SuppressImplicitBase;
4790 case CXPrintingPolicy_FullyQualifiedName:
4791 return P->FullyQualifiedName;
4792 }
4793
4794 assert(false && "Invalid CXPrintingPolicyProperty");
4795 return 0;
4796}
4797
4798void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4799 enum CXPrintingPolicyProperty Property,
4800 unsigned Value) {
4801 if (!Policy)
4802 return;
4803
4804 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4805 switch (Property) {
4806 case CXPrintingPolicy_Indentation:
4807 P->Indentation = Value;
4808 return;
4809 case CXPrintingPolicy_SuppressSpecifiers:
4810 P->SuppressSpecifiers = Value;
4811 return;
4812 case CXPrintingPolicy_SuppressTagKeyword:
4813 P->SuppressTagKeyword = Value;
4814 return;
4815 case CXPrintingPolicy_IncludeTagDefinition:
4816 P->IncludeTagDefinition = Value;
4817 return;
4818 case CXPrintingPolicy_SuppressScope:
4819 P->SuppressScope = Value;
4820 return;
4821 case CXPrintingPolicy_SuppressUnwrittenScope:
4822 P->SuppressUnwrittenScope = Value;
4823 return;
4824 case CXPrintingPolicy_SuppressInitializers:
4825 P->SuppressInitializers = Value;
4826 return;
4827 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4828 P->ConstantArraySizeAsWritten = Value;
4829 return;
4830 case CXPrintingPolicy_AnonymousTagLocations:
4831 P->AnonymousTagLocations = Value;
4832 return;
4833 case CXPrintingPolicy_SuppressStrongLifetime:
4834 P->SuppressStrongLifetime = Value;
4835 return;
4836 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4837 P->SuppressLifetimeQualifiers = Value;
4838 return;
4839 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4840 P->SuppressTemplateArgsInCXXConstructors = Value;
4841 return;
4842 case CXPrintingPolicy_Bool:
4843 P->Bool = Value;
4844 return;
4845 case CXPrintingPolicy_Restrict:
4846 P->Restrict = Value;
4847 return;
4848 case CXPrintingPolicy_Alignof:
4849 P->Alignof = Value;
4850 return;
4851 case CXPrintingPolicy_UnderscoreAlignof:
4852 P->UnderscoreAlignof = Value;
4853 return;
4854 case CXPrintingPolicy_UseVoidForZeroParams:
4855 P->UseVoidForZeroParams = Value;
4856 return;
4857 case CXPrintingPolicy_TerseOutput:
4858 P->TerseOutput = Value;
4859 return;
4860 case CXPrintingPolicy_PolishForDeclaration:
4861 P->PolishForDeclaration = Value;
4862 return;
4863 case CXPrintingPolicy_Half:
4864 P->Half = Value;
4865 return;
4866 case CXPrintingPolicy_MSWChar:
4867 P->MSWChar = Value;
4868 return;
4869 case CXPrintingPolicy_IncludeNewlines:
4870 P->IncludeNewlines = Value;
4871 return;
4872 case CXPrintingPolicy_MSVCFormatting:
4873 P->MSVCFormatting = Value;
4874 return;
4875 case CXPrintingPolicy_ConstantsAsWritten:
4876 P->ConstantsAsWritten = Value;
4877 return;
4878 case CXPrintingPolicy_SuppressImplicitBase:
4879 P->SuppressImplicitBase = Value;
4880 return;
4881 case CXPrintingPolicy_FullyQualifiedName:
4882 P->FullyQualifiedName = Value;
4883 return;
4884 }
4885
4886 assert(false && "Invalid CXPrintingPolicyProperty");
4887}
4888
4889CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4890 if (clang_Cursor_isNull(C))
4891 return cxstring::createEmpty();
4892
4893 if (clang_isDeclaration(C.kind)) {
4894 const Decl *D = getCursorDecl(C);
4895 if (!D)
4896 return cxstring::createEmpty();
4897
4898 SmallString<128> Str;
4899 llvm::raw_svector_ostream OS(Str);
4900 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4901 D->print(OS, UserPolicy ? *UserPolicy
4902 : getCursorContext(C).getPrintingPolicy());
4903
4904 return cxstring::createDup(OS.str());
4905 }
4906
4907 return cxstring::createEmpty();
4908}
4909
Guy Benyei11169dd2012-12-18 14:30:41 +00004910CXString clang_getCursorDisplayName(CXCursor C) {
4911 if (!clang_isDeclaration(C.kind))
4912 return clang_getCursorSpelling(C);
4913
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004914 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004916 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004917
4918 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004919 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 D = FunTmpl->getTemplatedDecl();
4921
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004922 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 SmallString<64> Str;
4924 llvm::raw_svector_ostream OS(Str);
4925 OS << *Function;
4926 if (Function->getPrimaryTemplate())
4927 OS << "<>";
4928 OS << "(";
4929 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4930 if (I)
4931 OS << ", ";
4932 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4933 }
4934
4935 if (Function->isVariadic()) {
4936 if (Function->getNumParams())
4937 OS << ", ";
4938 OS << "...";
4939 }
4940 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004941 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 }
4943
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004944 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 SmallString<64> Str;
4946 llvm::raw_svector_ostream OS(Str);
4947 OS << *ClassTemplate;
4948 OS << "<";
4949 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4950 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4951 if (I)
4952 OS << ", ";
4953
4954 NamedDecl *Param = Params->getParam(I);
4955 if (Param->getIdentifier()) {
4956 OS << Param->getIdentifier()->getName();
4957 continue;
4958 }
4959
4960 // There is no parameter name, which makes this tricky. Try to come up
4961 // with something useful that isn't too long.
4962 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4963 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4964 else if (NonTypeTemplateParmDecl *NTTP
4965 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4966 OS << NTTP->getType().getAsString(Policy);
4967 else
4968 OS << "template<...> class";
4969 }
4970
4971 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004972 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 }
4974
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004975 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4977 // If the type was explicitly written, use that.
4978 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004979 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004980
Benjamin Kramer9170e912013-02-22 15:46:01 +00004981 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004982 llvm::raw_svector_ostream OS(Str);
4983 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00004984 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
4985 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004986 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 }
4988
4989 return clang_getCursorSpelling(C);
4990}
4991
4992CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4993 switch (Kind) {
4994 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004995 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004996 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004997 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004999 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005000 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005001 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005002 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005003 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005005 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005007 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005008 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005009 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005011 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005013 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005015 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005017 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005019 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005021 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005023 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005025 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005027 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005029 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005031 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005033 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005035 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005037 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005039 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005041 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005043 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005045 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005047 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005049 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005051 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005053 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005055 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005057 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005061 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005065 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005067 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005069 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005072 case CXCursor_OMPArraySectionExpr:
5073 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005077 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005081 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005083 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005085 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005093 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005124 case CXCursor_ObjCAvailabilityCheckExpr:
5125 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005126 case CXCursor_ObjCSelfExpr:
5127 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005216 case CXCursor_SEHLeaveStmt:
5217 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005246 case CXCursor_PackedAttr:
5247 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005248 case CXCursor_PureAttr:
5249 return cxstring::createRef("attribute(pure)");
5250 case CXCursor_ConstAttr:
5251 return cxstring::createRef("attribute(const)");
5252 case CXCursor_NoDuplicateAttr:
5253 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005254 case CXCursor_CUDAConstantAttr:
5255 return cxstring::createRef("attribute(constant)");
5256 case CXCursor_CUDADeviceAttr:
5257 return cxstring::createRef("attribute(device)");
5258 case CXCursor_CUDAGlobalAttr:
5259 return cxstring::createRef("attribute(global)");
5260 case CXCursor_CUDAHostAttr:
5261 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005262 case CXCursor_CUDASharedAttr:
5263 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005264 case CXCursor_VisibilityAttr:
5265 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005266 case CXCursor_DLLExport:
5267 return cxstring::createRef("attribute(dllexport)");
5268 case CXCursor_DLLImport:
5269 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005315 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005317 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005318 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005319 return cxstring::createRef("OMPParallelDirective");
5320 case CXCursor_OMPSimdDirective:
5321 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005322 case CXCursor_OMPForDirective:
5323 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005324 case CXCursor_OMPForSimdDirective:
5325 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005326 case CXCursor_OMPSectionsDirective:
5327 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005328 case CXCursor_OMPSectionDirective:
5329 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005330 case CXCursor_OMPSingleDirective:
5331 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005332 case CXCursor_OMPMasterDirective:
5333 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005334 case CXCursor_OMPCriticalDirective:
5335 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005336 case CXCursor_OMPParallelForDirective:
5337 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005338 case CXCursor_OMPParallelForSimdDirective:
5339 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005340 case CXCursor_OMPParallelSectionsDirective:
5341 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005342 case CXCursor_OMPTaskDirective:
5343 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005344 case CXCursor_OMPTaskyieldDirective:
5345 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005346 case CXCursor_OMPBarrierDirective:
5347 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005348 case CXCursor_OMPTaskwaitDirective:
5349 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005350 case CXCursor_OMPTaskgroupDirective:
5351 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005352 case CXCursor_OMPFlushDirective:
5353 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005354 case CXCursor_OMPOrderedDirective:
5355 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005356 case CXCursor_OMPAtomicDirective:
5357 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005358 case CXCursor_OMPTargetDirective:
5359 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005360 case CXCursor_OMPTargetDataDirective:
5361 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005362 case CXCursor_OMPTargetEnterDataDirective:
5363 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005364 case CXCursor_OMPTargetExitDataDirective:
5365 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005366 case CXCursor_OMPTargetParallelDirective:
5367 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005368 case CXCursor_OMPTargetParallelForDirective:
5369 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005370 case CXCursor_OMPTargetUpdateDirective:
5371 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005372 case CXCursor_OMPTeamsDirective:
5373 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005374 case CXCursor_OMPCancellationPointDirective:
5375 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005376 case CXCursor_OMPCancelDirective:
5377 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005378 case CXCursor_OMPTaskLoopDirective:
5379 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005380 case CXCursor_OMPTaskLoopSimdDirective:
5381 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005382 case CXCursor_OMPDistributeDirective:
5383 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005384 case CXCursor_OMPDistributeParallelForDirective:
5385 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005386 case CXCursor_OMPDistributeParallelForSimdDirective:
5387 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005388 case CXCursor_OMPDistributeSimdDirective:
5389 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005390 case CXCursor_OMPTargetParallelForSimdDirective:
5391 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005392 case CXCursor_OMPTargetSimdDirective:
5393 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005394 case CXCursor_OMPTeamsDistributeDirective:
5395 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005396 case CXCursor_OMPTeamsDistributeSimdDirective:
5397 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005398 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5399 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005400 case CXCursor_OMPTeamsDistributeParallelForDirective:
5401 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005402 case CXCursor_OMPTargetTeamsDirective:
5403 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005404 case CXCursor_OMPTargetTeamsDistributeDirective:
5405 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005406 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5407 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005408 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5409 return cxstring::createRef(
5410 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005411 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5412 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005413 case CXCursor_OverloadCandidate:
5414 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005415 case CXCursor_TypeAliasTemplateDecl:
5416 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005417 case CXCursor_StaticAssert:
5418 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005419 case CXCursor_FriendDecl:
5420 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005421 }
5422
5423 llvm_unreachable("Unhandled CXCursorKind");
5424}
5425
5426struct GetCursorData {
5427 SourceLocation TokenBeginLoc;
5428 bool PointsAtMacroArgExpansion;
5429 bool VisitedObjCPropertyImplDecl;
5430 SourceLocation VisitedDeclaratorDeclStartLoc;
5431 CXCursor &BestCursor;
5432
5433 GetCursorData(SourceManager &SM,
5434 SourceLocation tokenBegin, CXCursor &outputCursor)
5435 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5436 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5437 VisitedObjCPropertyImplDecl = false;
5438 }
5439};
5440
5441static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5442 CXCursor parent,
5443 CXClientData client_data) {
5444 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5445 CXCursor *BestCursor = &Data->BestCursor;
5446
5447 // If we point inside a macro argument we should provide info of what the
5448 // token is so use the actual cursor, don't replace it with a macro expansion
5449 // cursor.
5450 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5451 return CXChildVisit_Recurse;
5452
5453 if (clang_isDeclaration(cursor.kind)) {
5454 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005455 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5457 if (MD->isImplicit())
5458 return CXChildVisit_Break;
5459
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005460 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005461 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5462 // Check that when we have multiple @class references in the same line,
5463 // that later ones do not override the previous ones.
5464 // If we have:
5465 // @class Foo, Bar;
5466 // source ranges for both start at '@', so 'Bar' will end up overriding
5467 // 'Foo' even though the cursor location was at 'Foo'.
5468 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5469 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005470 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5472 if (PrevID != ID &&
5473 !PrevID->isThisDeclarationADefinition() &&
5474 !ID->isThisDeclarationADefinition())
5475 return CXChildVisit_Break;
5476 }
5477
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005478 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005479 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5480 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5481 // Check that when we have multiple declarators in the same line,
5482 // that later ones do not override the previous ones.
5483 // If we have:
5484 // int Foo, Bar;
5485 // source ranges for both start at 'int', so 'Bar' will end up overriding
5486 // 'Foo' even though the cursor location was at 'Foo'.
5487 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5488 return CXChildVisit_Break;
5489 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5490
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005491 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005492 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5493 (void)PropImp;
5494 // Check that when we have multiple @synthesize in the same line,
5495 // that later ones do not override the previous ones.
5496 // If we have:
5497 // @synthesize Foo, Bar;
5498 // source ranges for both start at '@', so 'Bar' will end up overriding
5499 // 'Foo' even though the cursor location was at 'Foo'.
5500 if (Data->VisitedObjCPropertyImplDecl)
5501 return CXChildVisit_Break;
5502 Data->VisitedObjCPropertyImplDecl = true;
5503 }
5504 }
5505
5506 if (clang_isExpression(cursor.kind) &&
5507 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005508 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005509 // Avoid having the cursor of an expression replace the declaration cursor
5510 // when the expression source range overlaps the declaration range.
5511 // This can happen for C++ constructor expressions whose range generally
5512 // include the variable declaration, e.g.:
5513 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5514 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5515 D->getLocation() == Data->TokenBeginLoc)
5516 return CXChildVisit_Break;
5517 }
5518 }
5519
5520 // If our current best cursor is the construction of a temporary object,
5521 // don't replace that cursor with a type reference, because we want
5522 // clang_getCursor() to point at the constructor.
5523 if (clang_isExpression(BestCursor->kind) &&
5524 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5525 cursor.kind == CXCursor_TypeRef) {
5526 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5527 // as having the actual point on the type reference.
5528 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5529 return CXChildVisit_Recurse;
5530 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005531
5532 // If we already have an Objective-C superclass reference, don't
5533 // update it further.
5534 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5535 return CXChildVisit_Break;
5536
Guy Benyei11169dd2012-12-18 14:30:41 +00005537 *BestCursor = cursor;
5538 return CXChildVisit_Recurse;
5539}
5540
5541CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005542 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005543 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005544 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005545 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005546
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005547 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005548 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5549
5550 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5551 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5552
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005553 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 CXFile SearchFile;
5555 unsigned SearchLine, SearchColumn;
5556 CXFile ResultFile;
5557 unsigned ResultLine, ResultColumn;
5558 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5559 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5560 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005561
5562 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5563 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005564 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005565 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005566 SearchFileName = clang_getFileName(SearchFile);
5567 ResultFileName = clang_getFileName(ResultFile);
5568 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5569 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005570 *Log << llvm::format("(%s:%d:%d) = %s",
5571 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5572 clang_getCString(KindSpelling))
5573 << llvm::format("(%s:%d:%d):%s%s",
5574 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5575 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 clang_disposeString(SearchFileName);
5577 clang_disposeString(ResultFileName);
5578 clang_disposeString(KindSpelling);
5579 clang_disposeString(USR);
5580
5581 CXCursor Definition = clang_getCursorDefinition(Result);
5582 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5583 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5584 CXString DefinitionKindSpelling
5585 = clang_getCursorKindSpelling(Definition.kind);
5586 CXFile DefinitionFile;
5587 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005588 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005589 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005590 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005591 *Log << llvm::format(" -> %s(%s:%d:%d)",
5592 clang_getCString(DefinitionKindSpelling),
5593 clang_getCString(DefinitionFileName),
5594 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005595 clang_disposeString(DefinitionFileName);
5596 clang_disposeString(DefinitionKindSpelling);
5597 }
5598 }
5599
5600 return Result;
5601}
5602
5603CXCursor clang_getNullCursor(void) {
5604 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5605}
5606
5607unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005608 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5609 // can't set consistently. For example, when visiting a DeclStmt we will set
5610 // it but we don't set it on the result of clang_getCursorDefinition for
5611 // a reference of the same declaration.
5612 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5613 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5614 // to provide that kind of info.
5615 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005616 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005617 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005618 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005619
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 return X == Y;
5621}
5622
5623unsigned clang_hashCursor(CXCursor C) {
5624 unsigned Index = 0;
5625 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5626 Index = 1;
5627
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005628 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 std::make_pair(C.kind, C.data[Index]));
5630}
5631
5632unsigned clang_isInvalid(enum CXCursorKind K) {
5633 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5634}
5635
5636unsigned clang_isDeclaration(enum CXCursorKind K) {
5637 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005638 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5639}
5640
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005641unsigned clang_isInvalidDeclaration(CXCursor C) {
5642 if (clang_isDeclaration(C.kind)) {
5643 if (const Decl *D = getCursorDecl(C))
5644 return D->isInvalidDecl();
5645 }
5646
5647 return 0;
5648}
5649
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005650unsigned clang_isReference(enum CXCursorKind K) {
5651 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5652}
Guy Benyei11169dd2012-12-18 14:30:41 +00005653
5654unsigned clang_isExpression(enum CXCursorKind K) {
5655 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5656}
5657
5658unsigned clang_isStatement(enum CXCursorKind K) {
5659 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5660}
5661
5662unsigned clang_isAttribute(enum CXCursorKind K) {
5663 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5664}
5665
5666unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5667 return K == CXCursor_TranslationUnit;
5668}
5669
5670unsigned clang_isPreprocessing(enum CXCursorKind K) {
5671 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5672}
5673
5674unsigned clang_isUnexposed(enum CXCursorKind K) {
5675 switch (K) {
5676 case CXCursor_UnexposedDecl:
5677 case CXCursor_UnexposedExpr:
5678 case CXCursor_UnexposedStmt:
5679 case CXCursor_UnexposedAttr:
5680 return true;
5681 default:
5682 return false;
5683 }
5684}
5685
5686CXCursorKind clang_getCursorKind(CXCursor C) {
5687 return C.kind;
5688}
5689
5690CXSourceLocation clang_getCursorLocation(CXCursor C) {
5691 if (clang_isReference(C.kind)) {
5692 switch (C.kind) {
5693 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005694 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005695 = getCursorObjCSuperClassRef(C);
5696 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5697 }
5698
5699 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005700 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005701 = getCursorObjCProtocolRef(C);
5702 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5703 }
5704
5705 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005706 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005707 = getCursorObjCClassRef(C);
5708 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5709 }
5710
5711 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005712 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005713 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5714 }
5715
5716 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005717 std::pair<const TemplateDecl *, SourceLocation> P =
5718 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005719 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5720 }
5721
5722 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005723 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005724 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5725 }
5726
5727 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005728 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005729 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5730 }
5731
5732 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005733 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5735 }
5736
5737 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005738 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005739 if (!BaseSpec)
5740 return clang_getNullLocation();
5741
5742 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5743 return cxloc::translateSourceLocation(getCursorContext(C),
5744 TSInfo->getTypeLoc().getBeginLoc());
5745
5746 return cxloc::translateSourceLocation(getCursorContext(C),
5747 BaseSpec->getLocStart());
5748 }
5749
5750 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005751 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005752 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5753 }
5754
5755 case CXCursor_OverloadedDeclRef:
5756 return cxloc::translateSourceLocation(getCursorContext(C),
5757 getCursorOverloadedDeclRef(C).second);
5758
5759 default:
5760 // FIXME: Need a way to enumerate all non-reference cases.
5761 llvm_unreachable("Missed a reference kind");
5762 }
5763 }
5764
5765 if (clang_isExpression(C.kind))
5766 return cxloc::translateSourceLocation(getCursorContext(C),
5767 getLocationFromExpr(getCursorExpr(C)));
5768
5769 if (clang_isStatement(C.kind))
5770 return cxloc::translateSourceLocation(getCursorContext(C),
5771 getCursorStmt(C)->getLocStart());
5772
5773 if (C.kind == CXCursor_PreprocessingDirective) {
5774 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5775 return cxloc::translateSourceLocation(getCursorContext(C), L);
5776 }
5777
5778 if (C.kind == CXCursor_MacroExpansion) {
5779 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005780 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005781 return cxloc::translateSourceLocation(getCursorContext(C), L);
5782 }
5783
5784 if (C.kind == CXCursor_MacroDefinition) {
5785 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5786 return cxloc::translateSourceLocation(getCursorContext(C), L);
5787 }
5788
5789 if (C.kind == CXCursor_InclusionDirective) {
5790 SourceLocation L
5791 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5792 return cxloc::translateSourceLocation(getCursorContext(C), L);
5793 }
5794
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005795 if (clang_isAttribute(C.kind)) {
5796 SourceLocation L
5797 = cxcursor::getCursorAttr(C)->getLocation();
5798 return cxloc::translateSourceLocation(getCursorContext(C), L);
5799 }
5800
Guy Benyei11169dd2012-12-18 14:30:41 +00005801 if (!clang_isDeclaration(C.kind))
5802 return clang_getNullLocation();
5803
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005804 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005805 if (!D)
5806 return clang_getNullLocation();
5807
5808 SourceLocation Loc = D->getLocation();
5809 // FIXME: Multiple variables declared in a single declaration
5810 // currently lack the information needed to correctly determine their
5811 // ranges when accounting for the type-specifier. We use context
5812 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5813 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005814 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005815 if (!cxcursor::isFirstInDeclGroup(C))
5816 Loc = VD->getLocation();
5817 }
5818
5819 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005820 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 Loc = MD->getSelectorStartLoc();
5822
5823 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5824}
5825
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005826} // end extern "C"
5827
Guy Benyei11169dd2012-12-18 14:30:41 +00005828CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5829 assert(TU);
5830
5831 // Guard against an invalid SourceLocation, or we may assert in one
5832 // of the following calls.
5833 if (SLoc.isInvalid())
5834 return clang_getNullCursor();
5835
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005836 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005837
5838 // Translate the given source location to make it point at the beginning of
5839 // the token under the cursor.
5840 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5841 CXXUnit->getASTContext().getLangOpts());
5842
5843 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5844 if (SLoc.isValid()) {
5845 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5846 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5847 /*VisitPreprocessorLast=*/true,
5848 /*VisitIncludedEntities=*/false,
5849 SourceLocation(SLoc));
5850 CursorVis.visitFileRegion();
5851 }
5852
5853 return Result;
5854}
5855
5856static SourceRange getRawCursorExtent(CXCursor C) {
5857 if (clang_isReference(C.kind)) {
5858 switch (C.kind) {
5859 case CXCursor_ObjCSuperClassRef:
5860 return getCursorObjCSuperClassRef(C).second;
5861
5862 case CXCursor_ObjCProtocolRef:
5863 return getCursorObjCProtocolRef(C).second;
5864
5865 case CXCursor_ObjCClassRef:
5866 return getCursorObjCClassRef(C).second;
5867
5868 case CXCursor_TypeRef:
5869 return getCursorTypeRef(C).second;
5870
5871 case CXCursor_TemplateRef:
5872 return getCursorTemplateRef(C).second;
5873
5874 case CXCursor_NamespaceRef:
5875 return getCursorNamespaceRef(C).second;
5876
5877 case CXCursor_MemberRef:
5878 return getCursorMemberRef(C).second;
5879
5880 case CXCursor_CXXBaseSpecifier:
5881 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5882
5883 case CXCursor_LabelRef:
5884 return getCursorLabelRef(C).second;
5885
5886 case CXCursor_OverloadedDeclRef:
5887 return getCursorOverloadedDeclRef(C).second;
5888
5889 case CXCursor_VariableRef:
5890 return getCursorVariableRef(C).second;
5891
5892 default:
5893 // FIXME: Need a way to enumerate all non-reference cases.
5894 llvm_unreachable("Missed a reference kind");
5895 }
5896 }
5897
5898 if (clang_isExpression(C.kind))
5899 return getCursorExpr(C)->getSourceRange();
5900
5901 if (clang_isStatement(C.kind))
5902 return getCursorStmt(C)->getSourceRange();
5903
5904 if (clang_isAttribute(C.kind))
5905 return getCursorAttr(C)->getRange();
5906
5907 if (C.kind == CXCursor_PreprocessingDirective)
5908 return cxcursor::getCursorPreprocessingDirective(C);
5909
5910 if (C.kind == CXCursor_MacroExpansion) {
5911 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005912 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005913 return TU->mapRangeFromPreamble(Range);
5914 }
5915
5916 if (C.kind == CXCursor_MacroDefinition) {
5917 ASTUnit *TU = getCursorASTUnit(C);
5918 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5919 return TU->mapRangeFromPreamble(Range);
5920 }
5921
5922 if (C.kind == CXCursor_InclusionDirective) {
5923 ASTUnit *TU = getCursorASTUnit(C);
5924 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5925 return TU->mapRangeFromPreamble(Range);
5926 }
5927
5928 if (C.kind == CXCursor_TranslationUnit) {
5929 ASTUnit *TU = getCursorASTUnit(C);
5930 FileID MainID = TU->getSourceManager().getMainFileID();
5931 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5932 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5933 return SourceRange(Start, End);
5934 }
5935
5936 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005937 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005938 if (!D)
5939 return SourceRange();
5940
5941 SourceRange R = D->getSourceRange();
5942 // FIXME: Multiple variables declared in a single declaration
5943 // currently lack the information needed to correctly determine their
5944 // ranges when accounting for the type-specifier. We use context
5945 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5946 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005947 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005948 if (!cxcursor::isFirstInDeclGroup(C))
5949 R.setBegin(VD->getLocation());
5950 }
5951 return R;
5952 }
5953 return SourceRange();
5954}
5955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005956/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00005957/// the decl-specifier-seq for declarations.
5958static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5959 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005960 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005961 if (!D)
5962 return SourceRange();
5963
5964 SourceRange R = D->getSourceRange();
5965
5966 // Adjust the start of the location for declarations preceded by
5967 // declaration specifiers.
5968 SourceLocation StartLoc;
5969 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5970 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5971 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005972 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005973 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5974 StartLoc = TI->getTypeLoc().getLocStart();
5975 }
5976
5977 if (StartLoc.isValid() && R.getBegin().isValid() &&
5978 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5979 R.setBegin(StartLoc);
5980
5981 // FIXME: Multiple variables declared in a single declaration
5982 // currently lack the information needed to correctly determine their
5983 // ranges when accounting for the type-specifier. We use context
5984 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5985 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005986 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005987 if (!cxcursor::isFirstInDeclGroup(C))
5988 R.setBegin(VD->getLocation());
5989 }
5990
5991 return R;
5992 }
5993
5994 return getRawCursorExtent(C);
5995}
5996
Guy Benyei11169dd2012-12-18 14:30:41 +00005997CXSourceRange clang_getCursorExtent(CXCursor C) {
5998 SourceRange R = getRawCursorExtent(C);
5999 if (R.isInvalid())
6000 return clang_getNullRange();
6001
6002 return cxloc::translateSourceRange(getCursorContext(C), R);
6003}
6004
6005CXCursor clang_getCursorReferenced(CXCursor C) {
6006 if (clang_isInvalid(C.kind))
6007 return clang_getNullCursor();
6008
6009 CXTranslationUnit tu = getCursorTU(C);
6010 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006011 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006012 if (!D)
6013 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006014 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006015 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006016 if (const ObjCPropertyImplDecl *PropImpl =
6017 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006018 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6019 return MakeCXCursor(Property, tu);
6020
6021 return C;
6022 }
6023
6024 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006025 const Expr *E = getCursorExpr(C);
6026 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006027 if (D) {
6028 CXCursor declCursor = MakeCXCursor(D, tu);
6029 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6030 declCursor);
6031 return declCursor;
6032 }
6033
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006034 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006035 return MakeCursorOverloadedDeclRef(Ovl, tu);
6036
6037 return clang_getNullCursor();
6038 }
6039
6040 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006041 const Stmt *S = getCursorStmt(C);
6042 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006043 if (LabelDecl *label = Goto->getLabel())
6044 if (LabelStmt *labelS = label->getStmt())
6045 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6046
6047 return clang_getNullCursor();
6048 }
Richard Smith66a81862015-05-04 02:25:31 +00006049
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006051 if (const MacroDefinitionRecord *Def =
6052 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006053 return MakeMacroDefinitionCursor(Def, tu);
6054 }
6055
6056 if (!clang_isReference(C.kind))
6057 return clang_getNullCursor();
6058
6059 switch (C.kind) {
6060 case CXCursor_ObjCSuperClassRef:
6061 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6062
6063 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006064 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6065 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006066 return MakeCXCursor(Def, tu);
6067
6068 return MakeCXCursor(Prot, tu);
6069 }
6070
6071 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006072 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6073 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 return MakeCXCursor(Def, tu);
6075
6076 return MakeCXCursor(Class, tu);
6077 }
6078
6079 case CXCursor_TypeRef:
6080 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6081
6082 case CXCursor_TemplateRef:
6083 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6084
6085 case CXCursor_NamespaceRef:
6086 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6087
6088 case CXCursor_MemberRef:
6089 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6090
6091 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006092 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6094 tu ));
6095 }
6096
6097 case CXCursor_LabelRef:
6098 // FIXME: We end up faking the "parent" declaration here because we
6099 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006100 return MakeCXCursor(getCursorLabelRef(C).first,
6101 cxtu::getASTUnit(tu)->getASTContext()
6102 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006103 tu);
6104
6105 case CXCursor_OverloadedDeclRef:
6106 return C;
6107
6108 case CXCursor_VariableRef:
6109 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6110
6111 default:
6112 // We would prefer to enumerate all non-reference cursor kinds here.
6113 llvm_unreachable("Unhandled reference cursor kind");
6114 }
6115}
6116
6117CXCursor clang_getCursorDefinition(CXCursor C) {
6118 if (clang_isInvalid(C.kind))
6119 return clang_getNullCursor();
6120
6121 CXTranslationUnit TU = getCursorTU(C);
6122
6123 bool WasReference = false;
6124 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6125 C = clang_getCursorReferenced(C);
6126 WasReference = true;
6127 }
6128
6129 if (C.kind == CXCursor_MacroExpansion)
6130 return clang_getCursorReferenced(C);
6131
6132 if (!clang_isDeclaration(C.kind))
6133 return clang_getNullCursor();
6134
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006135 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 if (!D)
6137 return clang_getNullCursor();
6138
6139 switch (D->getKind()) {
6140 // Declaration kinds that don't really separate the notions of
6141 // declaration and definition.
6142 case Decl::Namespace:
6143 case Decl::Typedef:
6144 case Decl::TypeAlias:
6145 case Decl::TypeAliasTemplate:
6146 case Decl::TemplateTypeParm:
6147 case Decl::EnumConstant:
6148 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006149 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006150 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 case Decl::IndirectField:
6152 case Decl::ObjCIvar:
6153 case Decl::ObjCAtDefsField:
6154 case Decl::ImplicitParam:
6155 case Decl::ParmVar:
6156 case Decl::NonTypeTemplateParm:
6157 case Decl::TemplateTemplateParm:
6158 case Decl::ObjCCategoryImpl:
6159 case Decl::ObjCImplementation:
6160 case Decl::AccessSpec:
6161 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006162 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 case Decl::ObjCPropertyImpl:
6164 case Decl::FileScopeAsm:
6165 case Decl::StaticAssert:
6166 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006167 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006168 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006169 case Decl::Label: // FIXME: Is this right??
6170 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006171 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006172 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006173 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006174 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006175 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006176 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006177 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006178 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006179 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006180 return C;
6181
6182 // Declaration kinds that don't make any sense here, but are
6183 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006184 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006185 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006186 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006187 break;
6188
6189 // Declaration kinds for which the definition is not resolvable.
6190 case Decl::UnresolvedUsingTypename:
6191 case Decl::UnresolvedUsingValue:
6192 break;
6193
6194 case Decl::UsingDirective:
6195 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6196 TU);
6197
6198 case Decl::NamespaceAlias:
6199 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6200
6201 case Decl::Enum:
6202 case Decl::Record:
6203 case Decl::CXXRecord:
6204 case Decl::ClassTemplateSpecialization:
6205 case Decl::ClassTemplatePartialSpecialization:
6206 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6207 return MakeCXCursor(Def, TU);
6208 return clang_getNullCursor();
6209
6210 case Decl::Function:
6211 case Decl::CXXMethod:
6212 case Decl::CXXConstructor:
6213 case Decl::CXXDestructor:
6214 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006215 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006216 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006217 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006218 return clang_getNullCursor();
6219 }
6220
Larisse Voufo39a1e502013-08-06 01:03:05 +00006221 case Decl::Var:
6222 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006223 case Decl::VarTemplatePartialSpecialization:
6224 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006225 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006226 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006227 return MakeCXCursor(Def, TU);
6228 return clang_getNullCursor();
6229 }
6230
6231 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006232 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006233 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6234 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6235 return clang_getNullCursor();
6236 }
6237
6238 case Decl::ClassTemplate: {
6239 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6240 ->getDefinition())
6241 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6242 TU);
6243 return clang_getNullCursor();
6244 }
6245
Larisse Voufo39a1e502013-08-06 01:03:05 +00006246 case Decl::VarTemplate: {
6247 if (VarDecl *Def =
6248 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6249 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6250 return clang_getNullCursor();
6251 }
6252
Guy Benyei11169dd2012-12-18 14:30:41 +00006253 case Decl::Using:
6254 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6255 D->getLocation(), TU);
6256
6257 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006258 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006259 return clang_getCursorDefinition(
6260 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6261 TU));
6262
6263 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006264 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006265 if (Method->isThisDeclarationADefinition())
6266 return C;
6267
6268 // Dig out the method definition in the associated
6269 // @implementation, if we have it.
6270 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006271 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006272 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6273 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6274 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6275 Method->isInstanceMethod()))
6276 if (Def->isThisDeclarationADefinition())
6277 return MakeCXCursor(Def, TU);
6278
6279 return clang_getNullCursor();
6280 }
6281
6282 case Decl::ObjCCategory:
6283 if (ObjCCategoryImplDecl *Impl
6284 = cast<ObjCCategoryDecl>(D)->getImplementation())
6285 return MakeCXCursor(Impl, TU);
6286 return clang_getNullCursor();
6287
6288 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006289 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 return MakeCXCursor(Def, TU);
6291 return clang_getNullCursor();
6292
6293 case Decl::ObjCInterface: {
6294 // There are two notions of a "definition" for an Objective-C
6295 // class: the interface and its implementation. When we resolved a
6296 // reference to an Objective-C class, produce the @interface as
6297 // the definition; when we were provided with the interface,
6298 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006299 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006300 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006301 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 return MakeCXCursor(Def, TU);
6303 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6304 return MakeCXCursor(Impl, TU);
6305 return clang_getNullCursor();
6306 }
6307
6308 case Decl::ObjCProperty:
6309 // FIXME: We don't really know where to find the
6310 // ObjCPropertyImplDecls that implement this property.
6311 return clang_getNullCursor();
6312
6313 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006314 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006315 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006316 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006317 return MakeCXCursor(Def, TU);
6318
6319 return clang_getNullCursor();
6320
6321 case Decl::Friend:
6322 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6323 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6324 return clang_getNullCursor();
6325
6326 case Decl::FriendTemplate:
6327 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6328 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6329 return clang_getNullCursor();
6330 }
6331
6332 return clang_getNullCursor();
6333}
6334
6335unsigned clang_isCursorDefinition(CXCursor C) {
6336 if (!clang_isDeclaration(C.kind))
6337 return 0;
6338
6339 return clang_getCursorDefinition(C) == C;
6340}
6341
6342CXCursor clang_getCanonicalCursor(CXCursor C) {
6343 if (!clang_isDeclaration(C.kind))
6344 return C;
6345
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006346 if (const Decl *D = getCursorDecl(C)) {
6347 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006348 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6349 return MakeCXCursor(CatD, getCursorTU(C));
6350
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006351 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6352 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 return MakeCXCursor(IFD, getCursorTU(C));
6354
6355 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6356 }
6357
6358 return C;
6359}
6360
6361int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6362 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6363}
6364
6365unsigned clang_getNumOverloadedDecls(CXCursor C) {
6366 if (C.kind != CXCursor_OverloadedDeclRef)
6367 return 0;
6368
6369 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006370 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006371 return E->getNumDecls();
6372
6373 if (OverloadedTemplateStorage *S
6374 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6375 return S->size();
6376
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006377 const Decl *D = Storage.get<const Decl *>();
6378 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006379 return Using->shadow_size();
6380
6381 return 0;
6382}
6383
6384CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6385 if (cursor.kind != CXCursor_OverloadedDeclRef)
6386 return clang_getNullCursor();
6387
6388 if (index >= clang_getNumOverloadedDecls(cursor))
6389 return clang_getNullCursor();
6390
6391 CXTranslationUnit TU = getCursorTU(cursor);
6392 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006393 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 return MakeCXCursor(E->decls_begin()[index], TU);
6395
6396 if (OverloadedTemplateStorage *S
6397 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6398 return MakeCXCursor(S->begin()[index], TU);
6399
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006400 const Decl *D = Storage.get<const Decl *>();
6401 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 // FIXME: This is, unfortunately, linear time.
6403 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6404 std::advance(Pos, index);
6405 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6406 }
6407
6408 return clang_getNullCursor();
6409}
6410
6411void clang_getDefinitionSpellingAndExtent(CXCursor C,
6412 const char **startBuf,
6413 const char **endBuf,
6414 unsigned *startLine,
6415 unsigned *startColumn,
6416 unsigned *endLine,
6417 unsigned *endColumn) {
6418 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006419 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006420 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6421
6422 SourceManager &SM = FD->getASTContext().getSourceManager();
6423 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6424 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6425 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6426 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6427 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6428 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6429}
6430
6431
6432CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6433 unsigned PieceIndex) {
6434 RefNamePieces Pieces;
6435
6436 switch (C.kind) {
6437 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006438 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6440 E->getQualifierLoc().getSourceRange());
6441 break;
6442
6443 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006444 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6445 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6446 Pieces =
6447 buildPieces(NameFlags, false, E->getNameInfo(),
6448 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6449 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006450 break;
6451
6452 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006453 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006455 const Expr *Callee = OCE->getCallee();
6456 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 Callee = ICE->getSubExpr();
6458
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006459 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006460 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6461 DRE->getQualifierLoc().getSourceRange());
6462 }
6463 break;
6464
6465 default:
6466 break;
6467 }
6468
6469 if (Pieces.empty()) {
6470 if (PieceIndex == 0)
6471 return clang_getCursorExtent(C);
6472 } else if (PieceIndex < Pieces.size()) {
6473 SourceRange R = Pieces[PieceIndex];
6474 if (R.isValid())
6475 return cxloc::translateSourceRange(getCursorContext(C), R);
6476 }
6477
6478 return clang_getNullRange();
6479}
6480
6481void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006482 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6483 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006484}
6485
6486void clang_executeOnThread(void (*fn)(void*), void *user_data,
6487 unsigned stack_size) {
6488 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6489}
6490
Guy Benyei11169dd2012-12-18 14:30:41 +00006491//===----------------------------------------------------------------------===//
6492// Token-based Operations.
6493//===----------------------------------------------------------------------===//
6494
6495/* CXToken layout:
6496 * int_data[0]: a CXTokenKind
6497 * int_data[1]: starting token location
6498 * int_data[2]: token length
6499 * int_data[3]: reserved
6500 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6501 * otherwise unused.
6502 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006503CXTokenKind clang_getTokenKind(CXToken CXTok) {
6504 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6505}
6506
6507CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6508 switch (clang_getTokenKind(CXTok)) {
6509 case CXToken_Identifier:
6510 case CXToken_Keyword:
6511 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006512 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 ->getNameStart());
6514
6515 case CXToken_Literal: {
6516 // We have stashed the starting pointer in the ptr_data field. Use it.
6517 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006518 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 }
6520
6521 case CXToken_Punctuation:
6522 case CXToken_Comment:
6523 break;
6524 }
6525
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006526 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006527 LOG_BAD_TU(TU);
6528 return cxstring::createEmpty();
6529 }
6530
Guy Benyei11169dd2012-12-18 14:30:41 +00006531 // We have to find the starting buffer pointer the hard way, by
6532 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006533 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006534 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006535 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006536
6537 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6538 std::pair<FileID, unsigned> LocInfo
6539 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6540 bool Invalid = false;
6541 StringRef Buffer
6542 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6543 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006544 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006545
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006546 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006547}
6548
6549CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006550 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006551 LOG_BAD_TU(TU);
6552 return clang_getNullLocation();
6553 }
6554
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006555 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 if (!CXXUnit)
6557 return clang_getNullLocation();
6558
6559 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6560 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6561}
6562
6563CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006564 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006565 LOG_BAD_TU(TU);
6566 return clang_getNullRange();
6567 }
6568
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006569 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 if (!CXXUnit)
6571 return clang_getNullRange();
6572
6573 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6574 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6575}
6576
6577static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6578 SmallVectorImpl<CXToken> &CXTokens) {
6579 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6580 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006581 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006583 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006584
6585 // Cannot tokenize across files.
6586 if (BeginLocInfo.first != EndLocInfo.first)
6587 return;
6588
6589 // Create a lexer
6590 bool Invalid = false;
6591 StringRef Buffer
6592 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6593 if (Invalid)
6594 return;
6595
6596 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6597 CXXUnit->getASTContext().getLangOpts(),
6598 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6599 Lex.SetCommentRetentionState(true);
6600
6601 // Lex tokens until we hit the end of the range.
6602 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6603 Token Tok;
6604 bool previousWasAt = false;
6605 do {
6606 // Lex the next token
6607 Lex.LexFromRawLexer(Tok);
6608 if (Tok.is(tok::eof))
6609 break;
6610
6611 // Initialize the CXToken.
6612 CXToken CXTok;
6613
6614 // - Common fields
6615 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6616 CXTok.int_data[2] = Tok.getLength();
6617 CXTok.int_data[3] = 0;
6618
6619 // - Kind-specific fields
6620 if (Tok.isLiteral()) {
6621 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006622 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006623 } else if (Tok.is(tok::raw_identifier)) {
6624 // Lookup the identifier to determine whether we have a keyword.
6625 IdentifierInfo *II
6626 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6627
6628 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6629 CXTok.int_data[0] = CXToken_Keyword;
6630 }
6631 else {
6632 CXTok.int_data[0] = Tok.is(tok::identifier)
6633 ? CXToken_Identifier
6634 : CXToken_Keyword;
6635 }
6636 CXTok.ptr_data = II;
6637 } else if (Tok.is(tok::comment)) {
6638 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006639 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 } else {
6641 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006642 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006643 }
6644 CXTokens.push_back(CXTok);
6645 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006646 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006647}
6648
6649void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6650 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006651 LOG_FUNC_SECTION {
6652 *Log << TU << ' ' << Range;
6653 }
6654
Guy Benyei11169dd2012-12-18 14:30:41 +00006655 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006656 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006657 if (NumTokens)
6658 *NumTokens = 0;
6659
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006660 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006661 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006662 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006663 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006664
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006665 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006666 if (!CXXUnit || !Tokens || !NumTokens)
6667 return;
6668
6669 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6670
6671 SourceRange R = cxloc::translateCXSourceRange(Range);
6672 if (R.isInvalid())
6673 return;
6674
6675 SmallVector<CXToken, 32> CXTokens;
6676 getTokens(CXXUnit, R, CXTokens);
6677
6678 if (CXTokens.empty())
6679 return;
6680
Serge Pavlov52525732018-02-21 02:02:39 +00006681 *Tokens = static_cast<CXToken *>(
6682 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6684 *NumTokens = CXTokens.size();
6685}
6686
6687void clang_disposeTokens(CXTranslationUnit TU,
6688 CXToken *Tokens, unsigned NumTokens) {
6689 free(Tokens);
6690}
6691
Guy Benyei11169dd2012-12-18 14:30:41 +00006692//===----------------------------------------------------------------------===//
6693// Token annotation APIs.
6694//===----------------------------------------------------------------------===//
6695
Guy Benyei11169dd2012-12-18 14:30:41 +00006696static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6697 CXCursor parent,
6698 CXClientData client_data);
6699static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6700 CXClientData client_data);
6701
6702namespace {
6703class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006704 CXToken *Tokens;
6705 CXCursor *Cursors;
6706 unsigned NumTokens;
6707 unsigned TokIdx;
6708 unsigned PreprocessingTokIdx;
6709 CursorVisitor AnnotateVis;
6710 SourceManager &SrcMgr;
6711 bool HasContextSensitiveKeywords;
6712
6713 struct PostChildrenInfo {
6714 CXCursor Cursor;
6715 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006716 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006717 unsigned BeforeChildrenTokenIdx;
6718 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006719 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006720
6721 CXToken &getTok(unsigned Idx) {
6722 assert(Idx < NumTokens);
6723 return Tokens[Idx];
6724 }
6725 const CXToken &getTok(unsigned Idx) const {
6726 assert(Idx < NumTokens);
6727 return Tokens[Idx];
6728 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006729 bool MoreTokens() const { return TokIdx < NumTokens; }
6730 unsigned NextToken() const { return TokIdx; }
6731 void AdvanceToken() { ++TokIdx; }
6732 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006733 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006734 }
6735 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006736 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006737 }
6738 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006739 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 }
6741
6742 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006743 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006744 SourceRange);
6745
6746public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006747 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006748 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006749 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006751 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006752 AnnotateTokensVisitor, this,
6753 /*VisitPreprocessorLast=*/true,
6754 /*VisitIncludedEntities=*/false,
6755 RegionOfInterest,
6756 /*VisitDeclsOnly=*/false,
6757 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006758 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006759 HasContextSensitiveKeywords(false) { }
6760
6761 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6762 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6763 bool postVisitChildren(CXCursor cursor);
6764 void AnnotateTokens();
6765
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006766 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006767 /// context-sensitive keywords.
6768 bool hasContextSensitiveKeywords() const {
6769 return HasContextSensitiveKeywords;
6770 }
6771
6772 ~AnnotateTokensWorker() {
6773 assert(PostChildrenInfos.empty());
6774 }
6775};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006776}
Guy Benyei11169dd2012-12-18 14:30:41 +00006777
6778void AnnotateTokensWorker::AnnotateTokens() {
6779 // Walk the AST within the region of interest, annotating tokens
6780 // along the way.
6781 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006782}
Guy Benyei11169dd2012-12-18 14:30:41 +00006783
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006784static inline void updateCursorAnnotation(CXCursor &Cursor,
6785 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006786 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006787 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006788 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006789}
6790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006791/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006792//// between the cursor location and the source range is the same as
6793/// \arg compResult.
6794///
6795/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6796/// Pass RangeOverlap to annotate tokens inside a range.
6797void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6798 RangeComparisonResult compResult,
6799 SourceRange range) {
6800 while (MoreTokens()) {
6801 const unsigned I = NextToken();
6802 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006803 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6804 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006805
6806 SourceLocation TokLoc = GetTokenLoc(I);
6807 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006808 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006809 AdvanceToken();
6810 continue;
6811 }
6812 break;
6813 }
6814}
6815
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006816/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006817/// \returns true if it advanced beyond all macro tokens, false otherwise.
6818bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006819 CXCursor updateC,
6820 RangeComparisonResult compResult,
6821 SourceRange range) {
6822 assert(MoreTokens());
6823 assert(isFunctionMacroToken(NextToken()) &&
6824 "Should be called only for macro arg tokens");
6825
6826 // This works differently than annotateAndAdvanceTokens; because expanded
6827 // macro arguments can have arbitrary translation-unit source order, we do not
6828 // advance the token index one by one until a token fails the range test.
6829 // We only advance once past all of the macro arg tokens if all of them
6830 // pass the range test. If one of them fails we keep the token index pointing
6831 // at the start of the macro arg tokens so that the failing token will be
6832 // annotated by a subsequent annotation try.
6833
6834 bool atLeastOneCompFail = false;
6835
6836 unsigned I = NextToken();
6837 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6838 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6839 if (TokLoc.isFileID())
6840 continue; // not macro arg token, it's parens or comma.
6841 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6842 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6843 Cursors[I] = updateC;
6844 } else
6845 atLeastOneCompFail = true;
6846 }
6847
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006848 if (atLeastOneCompFail)
6849 return false;
6850
6851 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6852 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006853}
6854
6855enum CXChildVisitResult
6856AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 SourceRange cursorRange = getRawCursorExtent(cursor);
6858 if (cursorRange.isInvalid())
6859 return CXChildVisit_Recurse;
6860
6861 if (!HasContextSensitiveKeywords) {
6862 // Objective-C properties can have context-sensitive keywords.
6863 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006864 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006865 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6866 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6867 }
6868 // Objective-C methods can have context-sensitive keywords.
6869 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6870 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006871 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006872 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6873 if (Method->getObjCDeclQualifier())
6874 HasContextSensitiveKeywords = true;
6875 else {
David Majnemer59f77922016-06-24 04:05:48 +00006876 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006877 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006878 HasContextSensitiveKeywords = true;
6879 break;
6880 }
6881 }
6882 }
6883 }
6884 }
6885 // C++ methods can have context-sensitive keywords.
6886 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006887 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006888 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6889 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6890 HasContextSensitiveKeywords = true;
6891 }
6892 }
6893 // C++ classes can have context-sensitive keywords.
6894 else if (cursor.kind == CXCursor_StructDecl ||
6895 cursor.kind == CXCursor_ClassDecl ||
6896 cursor.kind == CXCursor_ClassTemplate ||
6897 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006898 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006899 if (D->hasAttr<FinalAttr>())
6900 HasContextSensitiveKeywords = true;
6901 }
6902 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006903
6904 // Don't override a property annotation with its getter/setter method.
6905 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6906 parent.kind == CXCursor_ObjCPropertyDecl)
6907 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006908
6909 if (clang_isPreprocessing(cursor.kind)) {
6910 // Items in the preprocessing record are kept separate from items in
6911 // declarations, so we keep a separate token index.
6912 unsigned SavedTokIdx = TokIdx;
6913 TokIdx = PreprocessingTokIdx;
6914
6915 // Skip tokens up until we catch up to the beginning of the preprocessing
6916 // entry.
6917 while (MoreTokens()) {
6918 const unsigned I = NextToken();
6919 SourceLocation TokLoc = GetTokenLoc(I);
6920 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6921 case RangeBefore:
6922 AdvanceToken();
6923 continue;
6924 case RangeAfter:
6925 case RangeOverlap:
6926 break;
6927 }
6928 break;
6929 }
6930
6931 // Look at all of the tokens within this range.
6932 while (MoreTokens()) {
6933 const unsigned I = NextToken();
6934 SourceLocation TokLoc = GetTokenLoc(I);
6935 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6936 case RangeBefore:
6937 llvm_unreachable("Infeasible");
6938 case RangeAfter:
6939 break;
6940 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006941 // For macro expansions, just note where the beginning of the macro
6942 // expansion occurs.
6943 if (cursor.kind == CXCursor_MacroExpansion) {
6944 if (TokLoc == cursorRange.getBegin())
6945 Cursors[I] = cursor;
6946 AdvanceToken();
6947 break;
6948 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006949 // We may have already annotated macro names inside macro definitions.
6950 if (Cursors[I].kind != CXCursor_MacroExpansion)
6951 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006953 continue;
6954 }
6955 break;
6956 }
6957
6958 // Save the preprocessing token index; restore the non-preprocessing
6959 // token index.
6960 PreprocessingTokIdx = TokIdx;
6961 TokIdx = SavedTokIdx;
6962 return CXChildVisit_Recurse;
6963 }
6964
6965 if (cursorRange.isInvalid())
6966 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006967
6968 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006970 const enum CXCursorKind K = clang_getCursorKind(parent);
6971 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006972 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6973 // Attributes are annotated out-of-order, skip tokens until we reach it.
6974 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 ? clang_getNullCursor() : parent;
6976
6977 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6978
6979 // Avoid having the cursor of an expression "overwrite" the annotation of the
6980 // variable declaration that it belongs to.
6981 // This can happen for C++ constructor expressions whose range generally
6982 // include the variable declaration, e.g.:
6983 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006984 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006985 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006986 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006987 const unsigned I = NextToken();
6988 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6989 E->getLocStart() == D->getLocation() &&
6990 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006991 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006992 AdvanceToken();
6993 }
6994 }
6995 }
6996
6997 // Before recursing into the children keep some state that we are going
6998 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6999 // extra work after the child nodes are visited.
7000 // Note that we don't call VisitChildren here to avoid traversing statements
7001 // code-recursively which can blow the stack.
7002
7003 PostChildrenInfo Info;
7004 Info.Cursor = cursor;
7005 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007006 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007007 Info.BeforeChildrenTokenIdx = NextToken();
7008 PostChildrenInfos.push_back(Info);
7009
7010 return CXChildVisit_Recurse;
7011}
7012
7013bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7014 if (PostChildrenInfos.empty())
7015 return false;
7016 const PostChildrenInfo &Info = PostChildrenInfos.back();
7017 if (!clang_equalCursors(Info.Cursor, cursor))
7018 return false;
7019
7020 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7021 const unsigned AfterChildren = NextToken();
7022 SourceRange cursorRange = Info.CursorRange;
7023
7024 // Scan the tokens that are at the end of the cursor, but are not captured
7025 // but the child cursors.
7026 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7027
7028 // Scan the tokens that are at the beginning of the cursor, but are not
7029 // capture by the child cursors.
7030 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7031 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7032 break;
7033
7034 Cursors[I] = cursor;
7035 }
7036
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007037 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7038 // encountered the attribute cursor.
7039 if (clang_isAttribute(cursor.kind))
7040 TokIdx = Info.BeforeReachingCursorIdx;
7041
Guy Benyei11169dd2012-12-18 14:30:41 +00007042 PostChildrenInfos.pop_back();
7043 return false;
7044}
7045
7046static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7047 CXCursor parent,
7048 CXClientData client_data) {
7049 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7050}
7051
7052static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7053 CXClientData client_data) {
7054 return static_cast<AnnotateTokensWorker*>(client_data)->
7055 postVisitChildren(cursor);
7056}
7057
7058namespace {
7059
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007060/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007061/// and mark tokens that are macro arguments. This info is used by the
7062/// AnnotateTokensWorker.
7063class MarkMacroArgTokensVisitor {
7064 SourceManager &SM;
7065 CXToken *Tokens;
7066 unsigned NumTokens;
7067 unsigned CurIdx;
7068
7069public:
7070 MarkMacroArgTokensVisitor(SourceManager &SM,
7071 CXToken *tokens, unsigned numTokens)
7072 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7073
7074 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7075 if (cursor.kind != CXCursor_MacroExpansion)
7076 return CXChildVisit_Continue;
7077
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007078 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007079 if (macroRange.getBegin() == macroRange.getEnd())
7080 return CXChildVisit_Continue; // it's not a function macro.
7081
7082 for (; CurIdx < NumTokens; ++CurIdx) {
7083 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7084 macroRange.getBegin()))
7085 break;
7086 }
7087
7088 if (CurIdx == NumTokens)
7089 return CXChildVisit_Break;
7090
7091 for (; CurIdx < NumTokens; ++CurIdx) {
7092 SourceLocation tokLoc = getTokenLoc(CurIdx);
7093 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7094 break;
7095
7096 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7097 }
7098
7099 if (CurIdx == NumTokens)
7100 return CXChildVisit_Break;
7101
7102 return CXChildVisit_Continue;
7103 }
7104
7105private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007106 CXToken &getTok(unsigned Idx) {
7107 assert(Idx < NumTokens);
7108 return Tokens[Idx];
7109 }
7110 const CXToken &getTok(unsigned Idx) const {
7111 assert(Idx < NumTokens);
7112 return Tokens[Idx];
7113 }
7114
Guy Benyei11169dd2012-12-18 14:30:41 +00007115 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007116 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007117 }
7118
7119 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7120 // The third field is reserved and currently not used. Use it here
7121 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007122 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007123 }
7124};
7125
7126} // end anonymous namespace
7127
7128static CXChildVisitResult
7129MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7130 CXClientData client_data) {
7131 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7132 parent);
7133}
7134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007135/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007136/// \returns true if lexing was finished, false otherwise.
7137static bool lexNext(Lexer &Lex, Token &Tok,
7138 unsigned &NextIdx, unsigned NumTokens) {
7139 if (NextIdx >= NumTokens)
7140 return true;
7141
7142 ++NextIdx;
7143 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007144 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007145}
7146
Guy Benyei11169dd2012-12-18 14:30:41 +00007147static void annotatePreprocessorTokens(CXTranslationUnit TU,
7148 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007149 CXCursor *Cursors,
7150 CXToken *Tokens,
7151 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007152 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007153
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007154 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007155 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7156 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007157 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007159 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007160
7161 if (BeginLocInfo.first != EndLocInfo.first)
7162 return;
7163
7164 StringRef Buffer;
7165 bool Invalid = false;
7166 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7167 if (Buffer.empty() || Invalid)
7168 return;
7169
7170 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7171 CXXUnit->getASTContext().getLangOpts(),
7172 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7173 Buffer.end());
7174 Lex.SetCommentRetentionState(true);
7175
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007176 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007177 // Lex tokens in raw mode until we hit the end of the range, to avoid
7178 // entering #includes or expanding macros.
7179 while (true) {
7180 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007181 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7182 break;
7183 unsigned TokIdx = NextIdx-1;
7184 assert(Tok.getLocation() ==
7185 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007186
7187 reprocess:
7188 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007189 // We have found a preprocessing directive. Annotate the tokens
7190 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007191 //
7192 // FIXME: Some simple tests here could identify macro definitions and
7193 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007194
7195 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007196 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7197 break;
7198
Craig Topper69186e72014-06-08 08:38:04 +00007199 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007200 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007201 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7202 break;
7203
7204 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007205 IdentifierInfo &II =
7206 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007207 SourceLocation MappedTokLoc =
7208 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7209 MI = getMacroInfo(II, MappedTokLoc, TU);
7210 }
7211 }
7212
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007213 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007214 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007215 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7216 finished = true;
7217 break;
7218 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007219 // If we are in a macro definition, check if the token was ever a
7220 // macro name and annotate it if that's the case.
7221 if (MI) {
7222 SourceLocation SaveLoc = Tok.getLocation();
7223 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007224 MacroDefinitionRecord *MacroDef =
7225 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007226 Tok.setLocation(SaveLoc);
7227 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007228 Cursors[NextIdx - 1] =
7229 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007230 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007231 } while (!Tok.isAtStartOfLine());
7232
7233 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7234 assert(TokIdx <= LastIdx);
7235 SourceLocation EndLoc =
7236 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7237 CXCursor Cursor =
7238 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7239
7240 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007241 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007242
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007243 if (finished)
7244 break;
7245 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007246 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 }
7248}
7249
7250// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007251static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7252 CXToken *Tokens, unsigned NumTokens,
7253 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007254 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7256 setThreadBackgroundPriority();
7257
7258 // Determine the region of interest, which contains all of the tokens.
7259 SourceRange RegionOfInterest;
7260 RegionOfInterest.setBegin(
7261 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7262 RegionOfInterest.setEnd(
7263 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7264 Tokens[NumTokens-1])));
7265
Guy Benyei11169dd2012-12-18 14:30:41 +00007266 // Relex the tokens within the source range to look for preprocessing
7267 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007268 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007269
7270 // If begin location points inside a macro argument, set it to the expansion
7271 // location so we can have the full context when annotating semantically.
7272 {
7273 SourceManager &SM = CXXUnit->getSourceManager();
7274 SourceLocation Loc =
7275 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7276 if (Loc.isMacroID())
7277 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7278 }
7279
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7281 // Search and mark tokens that are macro argument expansions.
7282 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7283 Tokens, NumTokens);
7284 CursorVisitor MacroArgMarker(TU,
7285 MarkMacroArgTokensVisitorDelegate, &Visitor,
7286 /*VisitPreprocessorLast=*/true,
7287 /*VisitIncludedEntities=*/false,
7288 RegionOfInterest);
7289 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7290 }
7291
7292 // Annotate all of the source locations in the region of interest that map to
7293 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007294 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007295
7296 // FIXME: We use a ridiculous stack size here because the data-recursion
7297 // algorithm uses a large stack frame than the non-data recursive version,
7298 // and AnnotationTokensWorker currently transforms the data-recursion
7299 // algorithm back into a traditional recursion by explicitly calling
7300 // VisitChildren(). We will need to remove this explicit recursive call.
7301 W.AnnotateTokens();
7302
7303 // If we ran into any entities that involve context-sensitive keywords,
7304 // take another pass through the tokens to mark them as such.
7305 if (W.hasContextSensitiveKeywords()) {
7306 for (unsigned I = 0; I != NumTokens; ++I) {
7307 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7308 continue;
7309
7310 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7311 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007312 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007313 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7314 if (Property->getPropertyAttributesAsWritten() != 0 &&
7315 llvm::StringSwitch<bool>(II->getName())
7316 .Case("readonly", true)
7317 .Case("assign", true)
7318 .Case("unsafe_unretained", true)
7319 .Case("readwrite", true)
7320 .Case("retain", true)
7321 .Case("copy", true)
7322 .Case("nonatomic", true)
7323 .Case("atomic", true)
7324 .Case("getter", true)
7325 .Case("setter", true)
7326 .Case("strong", true)
7327 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007328 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007329 .Default(false))
7330 Tokens[I].int_data[0] = CXToken_Keyword;
7331 }
7332 continue;
7333 }
7334
7335 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7336 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7337 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7338 if (llvm::StringSwitch<bool>(II->getName())
7339 .Case("in", true)
7340 .Case("out", true)
7341 .Case("inout", true)
7342 .Case("oneway", true)
7343 .Case("bycopy", true)
7344 .Case("byref", true)
7345 .Default(false))
7346 Tokens[I].int_data[0] = CXToken_Keyword;
7347 continue;
7348 }
7349
7350 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7351 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7352 Tokens[I].int_data[0] = CXToken_Keyword;
7353 continue;
7354 }
7355 }
7356 }
7357}
7358
Guy Benyei11169dd2012-12-18 14:30:41 +00007359void clang_annotateTokens(CXTranslationUnit TU,
7360 CXToken *Tokens, unsigned NumTokens,
7361 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007362 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007363 LOG_BAD_TU(TU);
7364 return;
7365 }
7366 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007367 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007368 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007369 }
7370
7371 LOG_FUNC_SECTION {
7372 *Log << TU << ' ';
7373 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7374 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7375 *Log << clang_getRange(bloc, eloc);
7376 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007377
7378 // Any token we don't specifically annotate will have a NULL cursor.
7379 CXCursor C = clang_getNullCursor();
7380 for (unsigned I = 0; I != NumTokens; ++I)
7381 Cursors[I] = C;
7382
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007383 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007384 if (!CXXUnit)
7385 return;
7386
7387 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007388
7389 auto AnnotateTokensImpl = [=]() {
7390 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7391 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007392 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007393 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007394 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7395 }
7396}
7397
Guy Benyei11169dd2012-12-18 14:30:41 +00007398//===----------------------------------------------------------------------===//
7399// Operations for querying linkage of a cursor.
7400//===----------------------------------------------------------------------===//
7401
Guy Benyei11169dd2012-12-18 14:30:41 +00007402CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7403 if (!clang_isDeclaration(cursor.kind))
7404 return CXLinkage_Invalid;
7405
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007406 const Decl *D = cxcursor::getCursorDecl(cursor);
7407 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007408 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007409 case NoLinkage:
7410 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007411 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007412 case InternalLinkage: return CXLinkage_Internal;
7413 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007414 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 case ExternalLinkage: return CXLinkage_External;
7416 };
7417
7418 return CXLinkage_Invalid;
7419}
Guy Benyei11169dd2012-12-18 14:30:41 +00007420
7421//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007422// Operations for querying visibility of a cursor.
7423//===----------------------------------------------------------------------===//
7424
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007425CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7426 if (!clang_isDeclaration(cursor.kind))
7427 return CXVisibility_Invalid;
7428
7429 const Decl *D = cxcursor::getCursorDecl(cursor);
7430 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7431 switch (ND->getVisibility()) {
7432 case HiddenVisibility: return CXVisibility_Hidden;
7433 case ProtectedVisibility: return CXVisibility_Protected;
7434 case DefaultVisibility: return CXVisibility_Default;
7435 };
7436
7437 return CXVisibility_Invalid;
7438}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007439
7440//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007441// Operations for querying language of a cursor.
7442//===----------------------------------------------------------------------===//
7443
7444static CXLanguageKind getDeclLanguage(const Decl *D) {
7445 if (!D)
7446 return CXLanguage_C;
7447
7448 switch (D->getKind()) {
7449 default:
7450 break;
7451 case Decl::ImplicitParam:
7452 case Decl::ObjCAtDefsField:
7453 case Decl::ObjCCategory:
7454 case Decl::ObjCCategoryImpl:
7455 case Decl::ObjCCompatibleAlias:
7456 case Decl::ObjCImplementation:
7457 case Decl::ObjCInterface:
7458 case Decl::ObjCIvar:
7459 case Decl::ObjCMethod:
7460 case Decl::ObjCProperty:
7461 case Decl::ObjCPropertyImpl:
7462 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007463 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007464 return CXLanguage_ObjC;
7465 case Decl::CXXConstructor:
7466 case Decl::CXXConversion:
7467 case Decl::CXXDestructor:
7468 case Decl::CXXMethod:
7469 case Decl::CXXRecord:
7470 case Decl::ClassTemplate:
7471 case Decl::ClassTemplatePartialSpecialization:
7472 case Decl::ClassTemplateSpecialization:
7473 case Decl::Friend:
7474 case Decl::FriendTemplate:
7475 case Decl::FunctionTemplate:
7476 case Decl::LinkageSpec:
7477 case Decl::Namespace:
7478 case Decl::NamespaceAlias:
7479 case Decl::NonTypeTemplateParm:
7480 case Decl::StaticAssert:
7481 case Decl::TemplateTemplateParm:
7482 case Decl::TemplateTypeParm:
7483 case Decl::UnresolvedUsingTypename:
7484 case Decl::UnresolvedUsingValue:
7485 case Decl::Using:
7486 case Decl::UsingDirective:
7487 case Decl::UsingShadow:
7488 return CXLanguage_CPlusPlus;
7489 }
7490
7491 return CXLanguage_C;
7492}
7493
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007494static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7495 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007496 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007497
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007498 switch (D->getAvailability()) {
7499 case AR_Available:
7500 case AR_NotYetIntroduced:
7501 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007502 return getCursorAvailabilityForDecl(
7503 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007504 return CXAvailability_Available;
7505
7506 case AR_Deprecated:
7507 return CXAvailability_Deprecated;
7508
7509 case AR_Unavailable:
7510 return CXAvailability_NotAvailable;
7511 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007512
7513 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007514}
7515
Guy Benyei11169dd2012-12-18 14:30:41 +00007516enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7517 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007518 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7519 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007520
7521 return CXAvailability_Available;
7522}
7523
7524static CXVersion convertVersion(VersionTuple In) {
7525 CXVersion Out = { -1, -1, -1 };
7526 if (In.empty())
7527 return Out;
7528
7529 Out.Major = In.getMajor();
7530
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007531 Optional<unsigned> Minor = In.getMinor();
7532 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007533 Out.Minor = *Minor;
7534 else
7535 return Out;
7536
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007537 Optional<unsigned> Subminor = In.getSubminor();
7538 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007539 Out.Subminor = *Subminor;
7540
7541 return Out;
7542}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007543
Alex Lorenz1345ea22017-06-12 19:06:30 +00007544static void getCursorPlatformAvailabilityForDecl(
7545 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7546 int *always_unavailable, CXString *unavailable_message,
7547 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007548 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007549 for (auto A : D->attrs()) {
7550 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007551 HadAvailAttr = true;
7552 if (always_deprecated)
7553 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007554 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007555 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007556 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007557 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007558 continue;
7559 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007560
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007561 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007562 HadAvailAttr = true;
7563 if (always_unavailable)
7564 *always_unavailable = 1;
7565 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007566 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007567 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7568 }
7569 continue;
7570 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007571
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007572 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007573 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007574 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007575 }
7576 }
7577
7578 if (!HadAvailAttr)
7579 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7580 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007581 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7582 deprecated_message, always_unavailable, unavailable_message,
7583 AvailabilityAttrs);
7584
7585 if (AvailabilityAttrs.empty())
7586 return;
7587
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007588 llvm::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7589 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7590 return LHS->getPlatform()->getName() <
7591 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007592 });
7593 ASTContext &Ctx = D->getASTContext();
7594 auto It = std::unique(
7595 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7596 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7597 if (LHS->getPlatform() != RHS->getPlatform())
7598 return false;
7599
7600 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7601 LHS->getDeprecated() == RHS->getDeprecated() &&
7602 LHS->getObsoleted() == RHS->getObsoleted() &&
7603 LHS->getMessage() == RHS->getMessage() &&
7604 LHS->getReplacement() == RHS->getReplacement())
7605 return true;
7606
7607 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7608 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7609 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7610 return false;
7611
7612 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7613 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7614
7615 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7616 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7617 if (LHS->getMessage().empty())
7618 LHS->setMessage(Ctx, RHS->getMessage());
7619 if (LHS->getReplacement().empty())
7620 LHS->setReplacement(Ctx, RHS->getReplacement());
7621 }
7622
7623 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7624 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7625 if (LHS->getMessage().empty())
7626 LHS->setMessage(Ctx, RHS->getMessage());
7627 if (LHS->getReplacement().empty())
7628 LHS->setReplacement(Ctx, RHS->getReplacement());
7629 }
7630
7631 return true;
7632 });
7633 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007634}
7635
Alex Lorenz1345ea22017-06-12 19:06:30 +00007636int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007637 CXString *deprecated_message,
7638 int *always_unavailable,
7639 CXString *unavailable_message,
7640 CXPlatformAvailability *availability,
7641 int availability_size) {
7642 if (always_deprecated)
7643 *always_deprecated = 0;
7644 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007645 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007646 if (always_unavailable)
7647 *always_unavailable = 0;
7648 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007649 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007650
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 if (!clang_isDeclaration(cursor.kind))
7652 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007653
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007654 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 if (!D)
7656 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007657
Alex Lorenz1345ea22017-06-12 19:06:30 +00007658 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7659 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7660 always_unavailable, unavailable_message,
7661 AvailabilityAttrs);
7662 for (const auto &Avail :
7663 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7664 .take_front(availability_size))) {
7665 availability[Avail.index()].Platform =
7666 cxstring::createDup(Avail.value()->getPlatform()->getName());
7667 availability[Avail.index()].Introduced =
7668 convertVersion(Avail.value()->getIntroduced());
7669 availability[Avail.index()].Deprecated =
7670 convertVersion(Avail.value()->getDeprecated());
7671 availability[Avail.index()].Obsoleted =
7672 convertVersion(Avail.value()->getObsoleted());
7673 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7674 availability[Avail.index()].Message =
7675 cxstring::createDup(Avail.value()->getMessage());
7676 }
7677
7678 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007679}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007680
Guy Benyei11169dd2012-12-18 14:30:41 +00007681void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7682 clang_disposeString(availability->Platform);
7683 clang_disposeString(availability->Message);
7684}
7685
7686CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7687 if (clang_isDeclaration(cursor.kind))
7688 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7689
7690 return CXLanguage_Invalid;
7691}
7692
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007693CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7694 const Decl *D = cxcursor::getCursorDecl(cursor);
7695 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7696 switch (VD->getTLSKind()) {
7697 case VarDecl::TLS_None:
7698 return CXTLS_None;
7699 case VarDecl::TLS_Dynamic:
7700 return CXTLS_Dynamic;
7701 case VarDecl::TLS_Static:
7702 return CXTLS_Static;
7703 }
7704 }
7705
7706 return CXTLS_None;
7707}
7708
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007709 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007710 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007711 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007712static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007713 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007714 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007715
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007716 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007717 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7718 return FunTmpl;
7719
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007720 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7722 return ClassTmpl;
7723
7724 return D;
7725}
7726
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007727
7728enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7729 StorageClass sc = SC_None;
7730 const Decl *D = getCursorDecl(C);
7731 if (D) {
7732 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7733 sc = FD->getStorageClass();
7734 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7735 sc = VD->getStorageClass();
7736 } else {
7737 return CX_SC_Invalid;
7738 }
7739 } else {
7740 return CX_SC_Invalid;
7741 }
7742 switch (sc) {
7743 case SC_None:
7744 return CX_SC_None;
7745 case SC_Extern:
7746 return CX_SC_Extern;
7747 case SC_Static:
7748 return CX_SC_Static;
7749 case SC_PrivateExtern:
7750 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007751 case SC_Auto:
7752 return CX_SC_Auto;
7753 case SC_Register:
7754 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007755 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007756 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007757}
7758
Guy Benyei11169dd2012-12-18 14:30:41 +00007759CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7760 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007761 if (const Decl *D = getCursorDecl(cursor)) {
7762 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007763 if (!DC)
7764 return clang_getNullCursor();
7765
7766 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7767 getCursorTU(cursor));
7768 }
7769 }
7770
7771 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007772 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007773 return MakeCXCursor(D, getCursorTU(cursor));
7774 }
7775
7776 return clang_getNullCursor();
7777}
7778
7779CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7780 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007781 if (const Decl *D = getCursorDecl(cursor)) {
7782 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007783 if (!DC)
7784 return clang_getNullCursor();
7785
7786 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7787 getCursorTU(cursor));
7788 }
7789 }
7790
7791 // FIXME: Note that we can't easily compute the lexical context of a
7792 // statement or expression, so we return nothing.
7793 return clang_getNullCursor();
7794}
7795
7796CXFile clang_getIncludedFile(CXCursor cursor) {
7797 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007798 return nullptr;
7799
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007800 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007801 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007802}
7803
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007804unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7805 if (C.kind != CXCursor_ObjCPropertyDecl)
7806 return CXObjCPropertyAttr_noattr;
7807
7808 unsigned Result = CXObjCPropertyAttr_noattr;
7809 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7810 ObjCPropertyDecl::PropertyAttributeKind Attr =
7811 PD->getPropertyAttributesAsWritten();
7812
7813#define SET_CXOBJCPROP_ATTR(A) \
7814 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7815 Result |= CXObjCPropertyAttr_##A
7816 SET_CXOBJCPROP_ATTR(readonly);
7817 SET_CXOBJCPROP_ATTR(getter);
7818 SET_CXOBJCPROP_ATTR(assign);
7819 SET_CXOBJCPROP_ATTR(readwrite);
7820 SET_CXOBJCPROP_ATTR(retain);
7821 SET_CXOBJCPROP_ATTR(copy);
7822 SET_CXOBJCPROP_ATTR(nonatomic);
7823 SET_CXOBJCPROP_ATTR(setter);
7824 SET_CXOBJCPROP_ATTR(atomic);
7825 SET_CXOBJCPROP_ATTR(weak);
7826 SET_CXOBJCPROP_ATTR(strong);
7827 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007828 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007829#undef SET_CXOBJCPROP_ATTR
7830
7831 return Result;
7832}
7833
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007834unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7835 if (!clang_isDeclaration(C.kind))
7836 return CXObjCDeclQualifier_None;
7837
7838 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7839 const Decl *D = getCursorDecl(C);
7840 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7841 QT = MD->getObjCDeclQualifier();
7842 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7843 QT = PD->getObjCDeclQualifier();
7844 if (QT == Decl::OBJC_TQ_None)
7845 return CXObjCDeclQualifier_None;
7846
7847 unsigned Result = CXObjCDeclQualifier_None;
7848 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7849 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7850 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7851 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7852 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7853 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7854
7855 return Result;
7856}
7857
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007858unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7859 if (!clang_isDeclaration(C.kind))
7860 return 0;
7861
7862 const Decl *D = getCursorDecl(C);
7863 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7864 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7865 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7866 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7867
7868 return 0;
7869}
7870
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007871unsigned clang_Cursor_isVariadic(CXCursor C) {
7872 if (!clang_isDeclaration(C.kind))
7873 return 0;
7874
7875 const Decl *D = getCursorDecl(C);
7876 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7877 return FD->isVariadic();
7878 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7879 return MD->isVariadic();
7880
7881 return 0;
7882}
7883
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007884unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7885 CXString *language, CXString *definedIn,
7886 unsigned *isGenerated) {
7887 if (!clang_isDeclaration(C.kind))
7888 return 0;
7889
7890 const Decl *D = getCursorDecl(C);
7891
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00007892 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007893 if (language)
7894 *language = cxstring::createDup(attr->getLanguage());
7895 if (definedIn)
7896 *definedIn = cxstring::createDup(attr->getDefinedIn());
7897 if (isGenerated)
7898 *isGenerated = attr->getGeneratedDeclaration();
7899 return 1;
7900 }
7901 return 0;
7902}
7903
Guy Benyei11169dd2012-12-18 14:30:41 +00007904CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7905 if (!clang_isDeclaration(C.kind))
7906 return clang_getNullRange();
7907
7908 const Decl *D = getCursorDecl(C);
7909 ASTContext &Context = getCursorContext(C);
7910 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7911 if (!RC)
7912 return clang_getNullRange();
7913
7914 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7915}
7916
7917CXString clang_Cursor_getRawCommentText(CXCursor C) {
7918 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007919 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007920
7921 const Decl *D = getCursorDecl(C);
7922 ASTContext &Context = getCursorContext(C);
7923 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7924 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7925 StringRef();
7926
7927 // Don't duplicate the string because RawText points directly into source
7928 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007929 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007930}
7931
7932CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7933 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007934 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007935
7936 const Decl *D = getCursorDecl(C);
7937 const ASTContext &Context = getCursorContext(C);
7938 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7939
7940 if (RC) {
7941 StringRef BriefText = RC->getBriefText(Context);
7942
7943 // Don't duplicate the string because RawComment ensures that this memory
7944 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007945 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007946 }
7947
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007948 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007949}
7950
Guy Benyei11169dd2012-12-18 14:30:41 +00007951CXModule clang_Cursor_getModule(CXCursor C) {
7952 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007953 if (const ImportDecl *ImportD =
7954 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007955 return ImportD->getImportedModule();
7956 }
7957
Craig Topper69186e72014-06-08 08:38:04 +00007958 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007959}
7960
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007961CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7962 if (isNotUsableTU(TU)) {
7963 LOG_BAD_TU(TU);
7964 return nullptr;
7965 }
7966 if (!File)
7967 return nullptr;
7968 FileEntry *FE = static_cast<FileEntry *>(File);
7969
7970 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7971 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7972 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7973
Richard Smithfeb54b62014-10-23 02:01:19 +00007974 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007975}
7976
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007977CXFile clang_Module_getASTFile(CXModule CXMod) {
7978 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007979 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007980 Module *Mod = static_cast<Module*>(CXMod);
7981 return const_cast<FileEntry *>(Mod->getASTFile());
7982}
7983
Guy Benyei11169dd2012-12-18 14:30:41 +00007984CXModule clang_Module_getParent(CXModule CXMod) {
7985 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007986 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007987 Module *Mod = static_cast<Module*>(CXMod);
7988 return Mod->Parent;
7989}
7990
7991CXString clang_Module_getName(CXModule CXMod) {
7992 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007993 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007995 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007996}
7997
7998CXString clang_Module_getFullName(CXModule CXMod) {
7999 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008000 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008002 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008003}
8004
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008005int clang_Module_isSystem(CXModule CXMod) {
8006 if (!CXMod)
8007 return 0;
8008 Module *Mod = static_cast<Module*>(CXMod);
8009 return Mod->IsSystem;
8010}
8011
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008012unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8013 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008014 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008015 LOG_BAD_TU(TU);
8016 return 0;
8017 }
8018 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008019 return 0;
8020 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008021 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8022 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8023 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008024}
8025
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008026CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8027 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008028 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008029 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008030 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008031 }
8032 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008033 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008034 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008035 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008036
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008037 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8038 if (Index < TopHeaders.size())
8039 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008040
Craig Topper69186e72014-06-08 08:38:04 +00008041 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008042}
8043
Guy Benyei11169dd2012-12-18 14:30:41 +00008044//===----------------------------------------------------------------------===//
8045// C++ AST instrospection.
8046//===----------------------------------------------------------------------===//
8047
Jonathan Coe29565352016-04-27 12:48:25 +00008048unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8049 if (!clang_isDeclaration(C.kind))
8050 return 0;
8051
8052 const Decl *D = cxcursor::getCursorDecl(C);
8053 const CXXConstructorDecl *Constructor =
8054 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8055 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8056}
8057
8058unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8059 if (!clang_isDeclaration(C.kind))
8060 return 0;
8061
8062 const Decl *D = cxcursor::getCursorDecl(C);
8063 const CXXConstructorDecl *Constructor =
8064 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8065 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8066}
8067
8068unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8069 if (!clang_isDeclaration(C.kind))
8070 return 0;
8071
8072 const Decl *D = cxcursor::getCursorDecl(C);
8073 const CXXConstructorDecl *Constructor =
8074 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8075 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8076}
8077
8078unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8079 if (!clang_isDeclaration(C.kind))
8080 return 0;
8081
8082 const Decl *D = cxcursor::getCursorDecl(C);
8083 const CXXConstructorDecl *Constructor =
8084 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8085 // Passing 'false' excludes constructors marked 'explicit'.
8086 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8087}
8088
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008089unsigned clang_CXXField_isMutable(CXCursor C) {
8090 if (!clang_isDeclaration(C.kind))
8091 return 0;
8092
8093 if (const auto D = cxcursor::getCursorDecl(C))
8094 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8095 return FD->isMutable() ? 1 : 0;
8096 return 0;
8097}
8098
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008099unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8100 if (!clang_isDeclaration(C.kind))
8101 return 0;
8102
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008103 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008104 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008105 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008106 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8107}
8108
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008109unsigned clang_CXXMethod_isConst(CXCursor C) {
8110 if (!clang_isDeclaration(C.kind))
8111 return 0;
8112
8113 const Decl *D = cxcursor::getCursorDecl(C);
8114 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008115 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008116 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
8117}
8118
Jonathan Coe29565352016-04-27 12:48:25 +00008119unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8120 if (!clang_isDeclaration(C.kind))
8121 return 0;
8122
8123 const Decl *D = cxcursor::getCursorDecl(C);
8124 const CXXMethodDecl *Method =
8125 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8126 return (Method && Method->isDefaulted()) ? 1 : 0;
8127}
8128
Guy Benyei11169dd2012-12-18 14:30:41 +00008129unsigned clang_CXXMethod_isStatic(CXCursor C) {
8130 if (!clang_isDeclaration(C.kind))
8131 return 0;
8132
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008133 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008134 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008135 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008136 return (Method && Method->isStatic()) ? 1 : 0;
8137}
8138
8139unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8140 if (!clang_isDeclaration(C.kind))
8141 return 0;
8142
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008143 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008144 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008145 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 return (Method && Method->isVirtual()) ? 1 : 0;
8147}
Guy Benyei11169dd2012-12-18 14:30:41 +00008148
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008149unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8150 if (!clang_isDeclaration(C.kind))
8151 return 0;
8152
8153 const auto *D = cxcursor::getCursorDecl(C);
8154 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8155 if (RD)
8156 RD = RD->getDefinition();
8157 return (RD && RD->isAbstract()) ? 1 : 0;
8158}
8159
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008160unsigned clang_EnumDecl_isScoped(CXCursor C) {
8161 if (!clang_isDeclaration(C.kind))
8162 return 0;
8163
8164 const Decl *D = cxcursor::getCursorDecl(C);
8165 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8166 return (Enum && Enum->isScoped()) ? 1 : 0;
8167}
8168
Guy Benyei11169dd2012-12-18 14:30:41 +00008169//===----------------------------------------------------------------------===//
8170// Attribute introspection.
8171//===----------------------------------------------------------------------===//
8172
Guy Benyei11169dd2012-12-18 14:30:41 +00008173CXType clang_getIBOutletCollectionType(CXCursor C) {
8174 if (C.kind != CXCursor_IBOutletCollectionAttr)
8175 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8176
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008177 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008178 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8179
8180 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8181}
Guy Benyei11169dd2012-12-18 14:30:41 +00008182
8183//===----------------------------------------------------------------------===//
8184// Inspecting memory usage.
8185//===----------------------------------------------------------------------===//
8186
8187typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8188
8189static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8190 enum CXTUResourceUsageKind k,
8191 unsigned long amount) {
8192 CXTUResourceUsageEntry entry = { k, amount };
8193 entries.push_back(entry);
8194}
8195
Guy Benyei11169dd2012-12-18 14:30:41 +00008196const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8197 const char *str = "";
8198 switch (kind) {
8199 case CXTUResourceUsage_AST:
8200 str = "ASTContext: expressions, declarations, and types";
8201 break;
8202 case CXTUResourceUsage_Identifiers:
8203 str = "ASTContext: identifiers";
8204 break;
8205 case CXTUResourceUsage_Selectors:
8206 str = "ASTContext: selectors";
8207 break;
8208 case CXTUResourceUsage_GlobalCompletionResults:
8209 str = "Code completion: cached global results";
8210 break;
8211 case CXTUResourceUsage_SourceManagerContentCache:
8212 str = "SourceManager: content cache allocator";
8213 break;
8214 case CXTUResourceUsage_AST_SideTables:
8215 str = "ASTContext: side tables";
8216 break;
8217 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8218 str = "SourceManager: malloc'ed memory buffers";
8219 break;
8220 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8221 str = "SourceManager: mmap'ed memory buffers";
8222 break;
8223 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8224 str = "ExternalASTSource: malloc'ed memory buffers";
8225 break;
8226 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8227 str = "ExternalASTSource: mmap'ed memory buffers";
8228 break;
8229 case CXTUResourceUsage_Preprocessor:
8230 str = "Preprocessor: malloc'ed memory";
8231 break;
8232 case CXTUResourceUsage_PreprocessingRecord:
8233 str = "Preprocessor: PreprocessingRecord";
8234 break;
8235 case CXTUResourceUsage_SourceManager_DataStructures:
8236 str = "SourceManager: data structures and tables";
8237 break;
8238 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8239 str = "Preprocessor: header search tables";
8240 break;
8241 }
8242 return str;
8243}
8244
8245CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008246 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008247 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008248 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008249 return usage;
8250 }
8251
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008252 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008253 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008254 ASTContext &astContext = astUnit->getASTContext();
8255
8256 // How much memory is used by AST nodes and types?
8257 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8258 (unsigned long) astContext.getASTAllocatedMemory());
8259
8260 // How much memory is used by identifiers?
8261 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8262 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8263
8264 // How much memory is used for selectors?
8265 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8266 (unsigned long) astContext.Selectors.getTotalMemory());
8267
8268 // How much memory is used by ASTContext's side tables?
8269 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8270 (unsigned long) astContext.getSideTableAllocatedMemory());
8271
8272 // How much memory is used for caching global code completion results?
8273 unsigned long completionBytes = 0;
8274 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008275 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008276 completionBytes = completionAllocator->getTotalMemory();
8277 }
8278 createCXTUResourceUsageEntry(*entries,
8279 CXTUResourceUsage_GlobalCompletionResults,
8280 completionBytes);
8281
8282 // How much memory is being used by SourceManager's content cache?
8283 createCXTUResourceUsageEntry(*entries,
8284 CXTUResourceUsage_SourceManagerContentCache,
8285 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8286
8287 // How much memory is being used by the MemoryBuffer's in SourceManager?
8288 const SourceManager::MemoryBufferSizes &srcBufs =
8289 astUnit->getSourceManager().getMemoryBufferSizes();
8290
8291 createCXTUResourceUsageEntry(*entries,
8292 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8293 (unsigned long) srcBufs.malloc_bytes);
8294 createCXTUResourceUsageEntry(*entries,
8295 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8296 (unsigned long) srcBufs.mmap_bytes);
8297 createCXTUResourceUsageEntry(*entries,
8298 CXTUResourceUsage_SourceManager_DataStructures,
8299 (unsigned long) astContext.getSourceManager()
8300 .getDataStructureSizes());
8301
8302 // How much memory is being used by the ExternalASTSource?
8303 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8304 const ExternalASTSource::MemoryBufferSizes &sizes =
8305 esrc->getMemoryBufferSizes();
8306
8307 createCXTUResourceUsageEntry(*entries,
8308 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8309 (unsigned long) sizes.malloc_bytes);
8310 createCXTUResourceUsageEntry(*entries,
8311 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8312 (unsigned long) sizes.mmap_bytes);
8313 }
8314
8315 // How much memory is being used by the Preprocessor?
8316 Preprocessor &pp = astUnit->getPreprocessor();
8317 createCXTUResourceUsageEntry(*entries,
8318 CXTUResourceUsage_Preprocessor,
8319 pp.getTotalMemory());
8320
8321 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8322 createCXTUResourceUsageEntry(*entries,
8323 CXTUResourceUsage_PreprocessingRecord,
8324 pRec->getTotalMemory());
8325 }
8326
8327 createCXTUResourceUsageEntry(*entries,
8328 CXTUResourceUsage_Preprocessor_HeaderSearch,
8329 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008330
Guy Benyei11169dd2012-12-18 14:30:41 +00008331 CXTUResourceUsage usage = { (void*) entries.get(),
8332 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008333 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008334 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008335 return usage;
8336}
8337
8338void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8339 if (usage.data)
8340 delete (MemUsageEntries*) usage.data;
8341}
8342
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008343CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8344 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008345 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008346 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008347
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008348 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008349 LOG_BAD_TU(TU);
8350 return skipped;
8351 }
8352
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008353 if (!file)
8354 return skipped;
8355
8356 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8357 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8358 if (!ppRec)
8359 return skipped;
8360
8361 ASTContext &Ctx = astUnit->getASTContext();
8362 SourceManager &sm = Ctx.getSourceManager();
8363 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8364 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008365 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008366
8367 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8368 std::vector<SourceRange> wantedRanges;
8369 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8370 i != ei; ++i) {
8371 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8372 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008373 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8374 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008375 }
8376
8377 skipped->count = wantedRanges.size();
8378 skipped->ranges = new CXSourceRange[skipped->count];
8379 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8380 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8381
8382 return skipped;
8383}
8384
Cameron Desrochersd8091282016-08-18 15:43:55 +00008385CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8386 CXSourceRangeList *skipped = new CXSourceRangeList;
8387 skipped->count = 0;
8388 skipped->ranges = nullptr;
8389
8390 if (isNotUsableTU(TU)) {
8391 LOG_BAD_TU(TU);
8392 return skipped;
8393 }
8394
8395 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8396 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8397 if (!ppRec)
8398 return skipped;
8399
8400 ASTContext &Ctx = astUnit->getASTContext();
8401
8402 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8403
8404 skipped->count = SkippedRanges.size();
8405 skipped->ranges = new CXSourceRange[skipped->count];
8406 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8407 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8408
8409 return skipped;
8410}
8411
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008412void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8413 if (ranges) {
8414 delete[] ranges->ranges;
8415 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008416 }
8417}
8418
Guy Benyei11169dd2012-12-18 14:30:41 +00008419void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8420 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8421 for (unsigned I = 0; I != Usage.numEntries; ++I)
8422 fprintf(stderr, " %s: %lu\n",
8423 clang_getTUResourceUsageName(Usage.entries[I].kind),
8424 Usage.entries[I].amount);
8425
8426 clang_disposeCXTUResourceUsage(Usage);
8427}
8428
8429//===----------------------------------------------------------------------===//
8430// Misc. utility functions.
8431//===----------------------------------------------------------------------===//
8432
8433/// Default to using an 8 MB stack size on "safety" threads.
8434static unsigned SafetyStackThreadSize = 8 << 20;
8435
8436namespace clang {
8437
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008438bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008439 unsigned Size) {
8440 if (!Size)
8441 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008442 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008443 return CRC.RunSafelyOnThread(Fn, Size);
8444 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008445}
8446
8447unsigned GetSafetyThreadStackSize() {
8448 return SafetyStackThreadSize;
8449}
8450
8451void SetSafetyThreadStackSize(unsigned Value) {
8452 SafetyStackThreadSize = Value;
8453}
8454
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008455}
Guy Benyei11169dd2012-12-18 14:30:41 +00008456
8457void clang::setThreadBackgroundPriority() {
8458 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8459 return;
8460
Alp Toker1a86ad22014-07-06 06:24:00 +00008461#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008462 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8463#endif
8464}
8465
8466void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8467 if (!Unit)
8468 return;
8469
8470 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8471 DEnd = Unit->stored_diag_end();
8472 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008473 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008474 CXString Msg = clang_formatDiagnostic(&Diag,
8475 clang_defaultDiagnosticDisplayOptions());
8476 fprintf(stderr, "%s\n", clang_getCString(Msg));
8477 clang_disposeString(Msg);
8478 }
Nico Weber1865df42018-04-27 19:11:14 +00008479#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008480 // On Windows, force a flush, since there may be multiple copies of
8481 // stderr and stdout in the file system, all with different buffers
8482 // but writing to the same device.
8483 fflush(stderr);
8484#endif
8485}
8486
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008487MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8488 SourceLocation MacroDefLoc,
8489 CXTranslationUnit TU){
8490 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008491 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008492 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008493 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008494
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008495 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008496 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008497 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008498 if (MD) {
8499 for (MacroDirective::DefInfo
8500 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8501 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8502 return Def.getMacroInfo();
8503 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008504 }
8505
Craig Topper69186e72014-06-08 08:38:04 +00008506 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008507}
8508
Richard Smith66a81862015-05-04 02:25:31 +00008509const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008510 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008511 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008512 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008513 const IdentifierInfo *II = MacroDef->getName();
8514 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008515 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008516
8517 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8518}
8519
Richard Smith66a81862015-05-04 02:25:31 +00008520MacroDefinitionRecord *
8521cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8522 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008523 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008524 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008525 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008526 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008527
8528 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008529 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008530 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8531 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008532 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008533
8534 // Check that the token is inside the definition and not its argument list.
8535 SourceManager &SM = Unit->getSourceManager();
8536 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008537 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008538 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008539 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008540
8541 Preprocessor &PP = Unit->getPreprocessor();
8542 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8543 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008544 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008545
Alp Toker2d57cea2014-05-17 04:53:25 +00008546 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008547 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008548 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008549
8550 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008551 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008552 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008553
Richard Smith20e883e2015-04-29 23:20:19 +00008554 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008555 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008556 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008557
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008558 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008559}
8560
Richard Smith66a81862015-05-04 02:25:31 +00008561MacroDefinitionRecord *
8562cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8563 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008564 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008565 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008566
8567 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008568 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008569 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008570 Preprocessor &PP = Unit->getPreprocessor();
8571 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008572 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008573 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8574 Token Tok;
8575 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008576 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008577
8578 return checkForMacroInMacroDefinition(MI, Tok, TU);
8579}
8580
Guy Benyei11169dd2012-12-18 14:30:41 +00008581CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008582 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008583}
8584
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008585Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8586 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008587 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008588 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008589 if (Unit->isMainFileAST())
8590 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008591 return *this;
8592 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008593 } else {
8594 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008595 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008596 return *this;
8597}
8598
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008599Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8600 *this << FE->getName();
8601 return *this;
8602}
8603
8604Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8605 CXString cursorName = clang_getCursorDisplayName(cursor);
8606 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8607 clang_disposeString(cursorName);
8608 return *this;
8609}
8610
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008611Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8612 CXFile File;
8613 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008614 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008615 CXString FileName = clang_getFileName(File);
8616 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8617 clang_disposeString(FileName);
8618 return *this;
8619}
8620
8621Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8622 CXSourceLocation BLoc = clang_getRangeStart(range);
8623 CXSourceLocation ELoc = clang_getRangeEnd(range);
8624
8625 CXFile BFile;
8626 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008627 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008628
8629 CXFile EFile;
8630 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008631 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008632
8633 CXString BFileName = clang_getFileName(BFile);
8634 if (BFile == EFile) {
8635 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8636 BLine, BColumn, ELine, EColumn);
8637 } else {
8638 CXString EFileName = clang_getFileName(EFile);
8639 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8640 BLine, BColumn)
8641 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8642 ELine, EColumn);
8643 clang_disposeString(EFileName);
8644 }
8645 clang_disposeString(BFileName);
8646 return *this;
8647}
8648
8649Logger &cxindex::Logger::operator<<(CXString Str) {
8650 *this << clang_getCString(Str);
8651 return *this;
8652}
8653
8654Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8655 LogOS << Fmt;
8656 return *this;
8657}
8658
Chandler Carruth37ad2582014-06-27 15:14:39 +00008659static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8660
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008661cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008662 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008663
8664 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8665
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008666 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008667 OS << "[libclang:" << Name << ':';
8668
Alp Toker1a86ad22014-07-06 06:24:00 +00008669#ifdef USE_DARWIN_THREADS
8670 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008671 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8672 OS << tid << ':';
8673#endif
8674
8675 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8676 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008677 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008678
8679 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008680 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008681 OS << "--------------------------------------------------\n";
8682 }
8683}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008684
8685#ifdef CLANG_TOOL_EXTRA_BUILD
8686// This anchor is used to force the linker to link the clang-tidy plugin.
8687extern volatile int ClangTidyPluginAnchorSource;
8688static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8689 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008690
8691// This anchor is used to force the linker to link the clang-include-fixer
8692// plugin.
8693extern volatile int ClangIncludeFixerPluginAnchorSource;
8694static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8695 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008696#endif